Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.
For example:
#include <msclr\marshal_cppstd.h>
System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.
enter = datetime.time(hour=1) # Example enter time
exit = datetime.time(hour=2) # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta
difference_delta is your difference which you can use for your reasons.
You can use Collections.swap(List<?> list, int i, int j);
The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.
If the contents of the list are primitive data types, you can use a comprehension
new_list = [i for i in old_list]
You can nest it for multidimensional lists like:
new_grid = [[i for i in row] for row in grid]
Use Material with shadowColor inside Container like this:
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Color(0xffA22447).withOpacity(.05),
offset: Offset(0, 0),
blurRadius: 20,
spreadRadius: 3)
]),
child: Material(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
elevation: 5,
shadowColor: Color(0xffA22447).withOpacity(.05),
color: Color(0xFFF7F7F7),
child: SizedBox(
height: MediaQuery.of(context).size.height / 3,
),
),
)
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
You must declare your MyComponentComponent in the same module of your AppComponent.
import { AppComponent } from '...';
import { MyComponentComponent } from '...';
@NgModule({
declarations: [ AppComponent, MyComponentComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
If you don't want to modify ansible.cfg
or the playbook.yml
then you can just set an environment variable:
export ANSIBLE_HOST_KEY_CHECKING=False
Make sure to copy the .csv file to /usr/local/bin or whatever folder your mondodb is in
$.delay is used to delay animations in a queue, not halt execution.
Instead of using a while loop, you need to recursively call a method that performs the check every second using setTimeout
:
var check = function(){
if(condition){
// run when condition is met
}
else {
setTimeout(check, 1000); // check again in a second
}
}
check();
All that answer not fully correct. I use That:
protected void SetPageSort(GridViewSortEventArgs e)
{
if (e.SortExpression == SortExpression)
{
if (SortDirection == "ASC")
{
SortDirection = "DESC";
}
else
{
SortDirection = "ASC";
}
}
else
{
if (SortDirection == "ASC")
{
SortDirection = "DESC";
}
else
{
SortDirection = "ASC";
}
SortExpression = e.SortExpression;
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
SetPageSort(e);
in gridView_Sorting...
You can use the keyword IDENTITY
as the data type to the column along with PRIMARY KEY
constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
You can try something like this:
Image logo = Image.GetInstance("pathToTheImage")
logo.ScaleAbsolute(500, 300)
The following works for me, after much trial
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<id>xjc1</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.clientSummary</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetClientSummary.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>xjc2</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.wsclient.employerProfile</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetEmployerProfile.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>xjc3</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.wsclient.producersLicenseData</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetProducersLicenseData.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
</executions>
</plugin>
Be sure to test any solution across different Reader preferences. A site visitor may have their browser set to open the PDF in Reader/Acrobat as opposed to the browser, e.g., by disabling the Acrobat plugin in Firefox..
I can't be sure of my results, because I have two different Acrobat plugins that Firefox recognizes due to my having different versions of Adobe Acrobat and Adobe Reader, but it does appear that you at least need to test what happens if a website visitor has their browser set to not open the PDF in the browser. It could be quite annoying when they look at what appears to be an otherwise usable web page and their browser is nagging them to open a PDF file that they think they didn't request. In some cases, the PDF file spontaneously opened in Adobe Reader, not the browser, and in other cases the browser threw up a dialog saying the file didn't exist.
I ran into such mismatches with iframe and object both, different issues for different code.
This is for simple HTML code. I haven't tried the suggested frameworks.
[
is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:
elif [
you can use the example from Microsoft - for you without namespace:
using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");
should do it
If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases - Your Database - Security - Schemas.
To create one using a script is as easy as (for example):
CREATE SCHEMA [EnterSchemaNameHere] AUTHORIZATION [dbo]
You can use them to logically group your tables, for example by creating a schema for "Financial" information and another for "Personal" data. Your tables would then display as:
Financial.BankAccounts Financial.Transactions Personal.Address
Rather than using the default schema of dbo.
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
You could use a .before with a content with a unicode symbol for a circle (25CF).
.circle:before {_x000D_
content: ' \25CF';_x000D_
font-size: 200px;_x000D_
}
_x000D_
<span class="circle"></span>
_x000D_
I suggest this as border-radius won't work in IE8 and below (I recognize the fact that the suggestion is a bit mental).
Actually the orderBy
filter can take as a parameter not only a string but also a function. From the orderBy
documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
The other thing worth noting is that orderBy
is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy
should be enough for most uses cases).
If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like
myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go
and import it like this
import (
"common"
"routers"
"routers/middleware"
)
This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.
FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes
For more learning about this feature, try to look up here
Understanding and Using Vendor Folder by Daniel Theophanes
Understanding Go Dependency Management by Lucas Fernandes da Costa
I hope you or someone else find it helpfully
Use execute_script
, here's a python example:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python")
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")
So it was a simple fix. Just had to move the ng-click
to a scope click handler:
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
$scope.clickUpload = function(){
angular.element('#upload').trigger('click');
};
In a follow-up answer, you asked about the relative performance of these two alternatives:
z1 = dict(x.items() + y.items())
z2 = dict(x, **y)
On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative z2
is not only shorter and simpler but also significantly faster. You can verify this for yourself using the timeit
module that comes with Python.
Example 1: identical dictionaries mapping 20 consecutive integers to themselves:
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'
100000 loops, best of 3: 5.67 usec per loop
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)'
100000 loops, best of 3: 1.53 usec per loop
z2
wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but z2
always seems to come out ahead. (If you get inconsistent results for the same test, try passing in -r
with a number larger than the default 3.)
Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'
1000 loops, best of 3: 260 usec per loop
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)'
10000 loops, best of 3: 26.9 usec per loop
z2
wins by about a factor of 10. That's a pretty big win in my book!
After comparing those two, I wondered if z1
's poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:
from itertools import chain
z3 = dict(chain(x.iteritems(), y.iteritems()))
A few quick tests, e.g.
% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'
10000 loops, best of 3: 66 usec per loop
lead me to conclude that z3
is somewhat faster than z1
, but not nearly as fast as z2
. Definitely not worth all the extra typing.
This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the update
method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:
z0 = dict(x)
z0.update(y)
A typical result:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'
10000 loops, best of 3: 26.9 usec per loop
In other words, z0
and z2
seem to have essentially identical performance. Do you think this might be a coincidence? I don't....
In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses dict
in lots of places; optimizing its operations is a big deal.
You could also write this as
z0 = x.copy()
z0.update(y)
as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand.
I just find this solution but in my case it doesn't work:
@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true)
orphanRemoval = true has no effect.
but what i am doing is purely synchronous
You could use HttpClient
for synchronous requests just fine:
using (var client = new HttpClient())
{
var response = client.GetAsync("http://google.com").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
}
As far as why you should use HttpClient
over WebRequest
is concerned, well, HttpClient
is the new kid on the block and could contain improvements over the old client.
You probably want to use the 'onbeforeunload' event. It will allow you call a function in the parent window from the child immediately before the child window closes.
So probably something like this:
window.onbeforeunload = function (e) {
window.parent.functonToCallBeforeThisWindowCloses();
};
You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:
$('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B');
This works on the original HTML without using value attributes.
If you want to rewrite the url, you have to change your site virtualhost adding this lines:
### Enabling mod_rewrite
Options FollowSymLinks
RewriteEngine on
### Rewrite http:// => https://
RewriteCond %{SERVER_PORT} 80$
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,NC,L]
But, if you want to redirect all your requests on the port 80 to the port 443 of the web servers behind the proxy, you can try this example conf on your haproxy.cfg:
##########
# Global #
##########
global
maxconn 100
spread-checks 50
daemon
nbproc 4
############
# Defaults #
############
defaults
maxconn 100
log global
mode http
option dontlognull
retries 3
contimeout 60000
clitimeout 60000
srvtimeout 60000
#####################
# Frontend: HTTP-IN #
#####################
frontend http-in
bind *:80
option logasap
option httplog
option httpclose
log global
default_backend sslwebserver
#########################
# Backend: SSLWEBSERVER #
#########################
backend sslwebserver
option httplog
option forwardfor
option abortonclose
log global
balance roundrobin
# Server List
server sslws01 webserver01:443 check
server sslws02 webserver02:443 check
server sslws03 webserver03:443 check
I hope this help you
Don't try to get them inside its constructor. Try Call them in onDraw()
method.
@Column
AnnotationThe nullable
attribute of the @Column
annotation has two purposes:
The HBM2DDL schema generation tool translates the @Column(nullable = false)
entity attribute to a NOT NULL
constraint for the associated table column when generating the CREATE TABLE
statement.
As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.
When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false)
entity attribute:
new Nullability( session ).checkNullability( values, persister, true );
If the validation fails, Hibernate will throw a PropertyValueException
, and prevents the INSERT or UPDATE statement to be executed needesly:
if ( !nullability[i] && value == null ) {
//check basic level one nullablilty
throw new PropertyValueException(
"not-null property references a null or transient value",
persister.getEntityName(),
persister.getPropertyNames()[i]
);
}
@NotNull
AnnotationThe @NotNull
annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.
When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation
when validating the entity.
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
in windows, I set ANDROID_HOME=E:\android\adt-bundle-windows-x86_64-20131030\sdk Then it works as expect.
When in Linux, you need to set sdk.dir.
The script uses two different variables.
It will be more flexible with hover()
:
$(".my-popover").hover(
function() { // mouse in event
$this = $(this);
$this.popover({
html: true,
content: "Your content",
trigger: "manual",
animation: false
});
$this.popover("show");
$(".popover").on("mouseleave", function() {
$this.popover("hide");
});
},
function() { // mouse out event
setTimeout(function() {
if (!$(".popover:hover").length) {
$this.popover("hide");
}
}, 100);
}
)
From the documentation:
The BuildAction property indicates what Visual Studio does with a file when a build is executed. BuildAction can have one of several values:
None - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Compile - The file is compiled into the build output. This setting is used for code files.
Content - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.
Embedded Resource - This file is embedded in the main project build output as a DLL or executable. It is typically used for resource files.
Checkout TickTick.
It's a true Bash JSON parser.
#!/bin/bash
. /path/to/ticktick.sh
# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`
tickParse "$DATA"
echo ``pathname``
echo ``headers["user-agent"]``
For compatibility with Tensorflow 2.0, you can use tf.get_logger
import logging
tf.get_logger().setLevel(logging.ERROR)
This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:
@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.
So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.
Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.
The complete solution:
*:not(html) {
-webkit-transform: translate3d(0, 0, 0);
}
Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch
. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.
So, thanks again, and hope this helps some other lost soul. This surely helped me big time!
NOTE : this is just an abbreviation of this answer above
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing
, System.Web.Net
and System.Net.Http
dlls if not there already
Add the following class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Add Application_Start
method if not there already (in global.asax.cs file)
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Right click controllers folder > add new item > web > Add Web API controller
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
}
}
I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini
Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;
After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.
Goodluck. if it works comment.
You can use strtok
to get string before first occurence of ?
$url = strtok($_SERVER["REQUEST_URI"], '?');
strtok()
represents the most concise technique to directly extract the substring before the ?
in the querystring. explode()
is less direct because it must produce a potentially two-element array by which the first element must be accessed.
Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.
$urls = [
'www.example.com/myurl.html?unwantedthngs#hastag',
'www.example.com/myurl.html'
];
foreach ($urls as $url) {
var_export(['strtok: ', strtok($url, '?')]);
echo "\n";
var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
echo "\n";
var_export(['explode/2: ', explode('?', $url, 2)[0]]); // limit allows func to stop searching after first encounter
echo "\n";
var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]); // not reliable; still not with strpos()
echo "\n---\n";
}
Output:
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => 'www.example.com/myurl.html',
)
---
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => false, // bad news
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => '', // bad news
)
---
Difference between Proxy server (also called forward proxy) and Reverse Proxy Server depends on the point of reference.
Technically, both are exactly the same. Both serve the same purpose of transmitting data to a destination on behalf of a source.
The difference lies in 'on whose behalf is the proxy server acting / who is the proxy server representing?'
If the proxy server is forwarding requests to internet server on behalf of the end users (Example: students in a college accessing internet through college proxy server.), then the proxy is called 'Forward proxy' or simply 'Proxy'.
If the proxy server is responding to incoming requests, on behalf of a server, then the proxy is called 'Reverse Proxy', as it is working in the reverse direction, from the point of view of the end user.
Some Examples of Reverse proxies:
Use of forward proxy:
Use of Reverse proxy:
Options:
or
if your object class implements Serializable
, you don't need to do anything else, you can pass a serializable object.
that's what i use.
Was getting call to undefined function bcmod()
yum install php-bcmath
systemctl restart httpd.service
you should then see something similar to /etc/php.d/bcmath.ini
listed under phpinfo.
Centos 7
Plesk 12
PHP 5.4.16
JSON.parse()
is for "parsing" something that was received as JSON.
JSON.stringify()
is to create a JSON string out of an object/array.
Try this
new DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (_) {},
)
Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.
In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64
equivalent of the int
input. float32
datatype is also available in GoLang
Code:
package main
import "fmt"
func main() {
var i int
fmt.Println("Enter an Integer input: ")
fmt.Scanf("%d", &i)
f := float64(i)
fmt.Printf("The float64 representation of %d is %f\n", i, f)
}
Solution:
>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
I suspect there is something wrong either with your Git installation or your repository.
Try running:
GIT_TRACE=2 git <command>
See if you get anything useful. If that doesn't help, just use strace and see what's going wrong:
strace git <command>
Test::StaticTest()
is called exactly once during global static initialization.
Caller only has to add one line to the function that is to be their static constructor.
static_constructor<&Test::StaticTest>::c;
forces initialization of c
during global static initialization.
template<void(*ctor)()>
struct static_constructor
{
struct constructor { constructor() { ctor(); } };
static constructor c;
};
template<void(*ctor)()>
typename static_constructor<ctor>::constructor static_constructor<ctor>::c;
/////////////////////////////
struct Test
{
static int number;
static void StaticTest()
{
static_constructor<&Test::StaticTest>::c;
number = 123;
cout << "static ctor" << endl;
}
};
int Test::number;
int main(int argc, char *argv[])
{
cout << Test::number << endl;
return 0;
}
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';
// U+1F638
var_dump(
"cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
"cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);
function escape_sequence_decode($str) {
// [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
$regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
|\\\u([\da-fA-F]{4})/sx';
return preg_replace_callback($regex, function($matches) {
if (isset($matches[3])) {
$cp = hexdec($matches[3]);
} else {
$lead = hexdec($matches[1]);
$trail = hexdec($matches[2]);
// http://unicode.org/faq/utf_bom.html#utf16-4
$cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
}
// https://tools.ietf.org/html/rfc3629#section-3
// Characters between U+D800 and U+DFFF are not allowed in UTF-8
if ($cp > 0xD7FF && 0xE000 > $cp) {
$cp = 0xFFFD;
}
// https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
// php_utf32_utf8(unsigned char *buf, unsigned k)
if ($cp < 0x80) {
return chr($cp);
} else if ($cp < 0xA0) {
return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
}
return html_entity_decode('&#'.$cp.';');
}, $str);
}
My project uses node v10.21.0, which still does not support ES6 import
keyword. There are multiple ways to make node recognize import
, one of them is to start node with node --experimental-modules index.mjs
(The mjs
extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require
in your code. If there is need to use both nodejs's require
keyword along with ES6's import
, then the way out is to use the esm
npm package. After adding esm
package as a dependency, node needs to be started with a special configuration like: node -r esm index.js
When you read the string from the GUI control, it is already a "raw" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.
>>> a='\nu + \lambda + \theta'
>>> a
'\nu + \\lambda + \theta'
>>> len(a)
20
>>> b=r'\nu + \lambda + \theta'
>>> b
'\\nu + \\lambda + \\theta'
>>> len(b)
22
>>> b[0]
'\\'
>>> print b
\nu + \lambda + \theta
If you're using this for debugging, and you just want a recursive dump of everything, the accepted answer is unsatisfying because it requires that your classes have good __str__
implementations already. If that's not the case, this works much better:
import json
print(json.dumps(YOUR_OBJECT,
default=lambda obj: vars(obj),
indent=1))
Consider this array:
$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
To remove an element using the array key
:
// To unset an element from array using Key:
unset($arr["key2"]);
var_dump($arr);
// output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
To remove element by value
:
// remove an element by value:
$arr = array_diff($arr, ["value1"]);
var_dump($arr);
// output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
read more about array_diff: http://php.net/manual/en/function.array-diff.php
To remove an element by using index
:
array_splice($arr, 1, 1);
var_dump($arr);
// array(1) { ["key3"]=> string(6) "value3" }
read more about array_splice: http://php.net/manual/en/function.array-splice.php
My suggestion would be to use Unit Tests.
In your application do the following switches in Program.cs
:
#if DEBUG
public class Program
#else
class Program
#endif
and the same for static Main(string[] args)
.
Or alternatively use Friend Assemblies by adding
[assembly: InternalsVisibleTo("TestAssembly")]
to your AssemblyInfo.cs
.
Then create a unit test project and a test that looks a bit like so:
[TestClass]
public class TestApplication
{
[TestMethod]
public void TestMyArgument()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw); // this makes any Console.Writes etc go to sw
Program.Main(new[] { "argument" });
var result = sw.ToString();
Assert.AreEqual("expected", result);
}
}
}
This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.
Code and explanation from Pointer Basics:
The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.
void main() {
int* x; // Allocate the pointer x
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
}
Depending on the boost version libboost-system comes with the -mt suffix which should indicate the libraries multithreading capability.
So if -lboost_system
cannot be found by the linker try -lboost_system-mt
.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations
For you, blindLeftToggle
and blindRightToggle
is the appropriate choice.
I know this is a way late, but I thought I'd add yet another way of doing this.
You can take advantage of the fact that the Text property can be set using "Runs", so you can set up multiple bindings using a Run for each one. This is useful if you don't have access to MultiBinding (which I didn't find when developing for Windows Phone)
<TextBlock>
<Run Text="Name = "/>
<Run Text="{Binding Name}"/>
<Run Text=", Id ="/>
<Run Text="{Binding Id}"/>
</TextBlock>
FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).
For more information try this link.
For me, I am working on .net 4.5.2 with web api 2.0, I have the same error, i set it just by adding requestPathInvalidCharacters="" in the requestPathInvalidCharacters you have to set not allowed characters else you have to remove characters that cause this problem.
<system.web>
<httpRuntime targetFramework="4.5.2" requestPathInvalidCharacters="" />
<pages >
<namespaces>
....
</namespaces>
</pages>
</system.web>
**Note that it is not a good practice, may be a post with this parameter as attribute of an object is better or try to encode the special character. -- After searching on best practice for designing rest api, i found that in search, sort and paginnation, we have to handle the query parameter like this
/companies?search=Digital%26Mckinsey
and this solve the problem when we encode & and remplace it on the url by %26 any way, on the server we receive the correct parameter Digital&Mckinsey
this link may help on best practice of designing rest web api https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9
Or try the Ruby 1.9 way:
array.inject(0, :+)
Note: the 0
base case is needed otherwise nil
will be returned on empty arrays:
> [].inject(:+)
nil
> [].inject(0, :+)
0
df.drop(df.index[[0,2]])
Pandas uses zero based numbering, so 0 is the first row, 1 is the second row and 2 is the third row.
Just make rdg2.nPhoneNumber varchar everywhere instead of int !
"." | "!" | "~" | "*" | "'" | "(" | ")"
are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.
Had the same problem until I tried deleting the .git folder. It worked. I guess this type of problem can have different causes.
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
You don't need FileInputStream to calculate file size, new File(path_to_file).length()
is enough. Or, if you insist, use fileinputstream.getChannel().size()
.
may be you can write like this:
#graphic {
background-image: url(image.jpg);
background-position: 0 -50px;
width: 200px;
height: 100px;
}
The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.
And as said in the first comment: you can add info to any line you feel the need to
SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS
As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.
SOME CODE
GOTO LABEL ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL
SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP
:LABEL
CODE TO EXECUTE
I think you want (this won't fit in a int
though, you'll need to store it as a long
):
long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;
Alternatively, storing the ticks is a better idea.
In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.
Sub Demo()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim query As String
Dim Col, Row As Integer
Dim objWS As New clsws_GlobalWeather
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
query = objWS.wsm_GetCitiesByCountry("india")
If Not XDoc.LoadXML(query) Then 'strXML is the string with XML'
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (query)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Worksheets("Sheet3").Cells(1, 1).Value = "Country"
Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
Worksheets("Sheet3").Cells(1, 2).Value = "City"
Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
For Each xChild In xParent.ChildNodes
Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
Col = Col + 1
Next xChild
Row = Row + 1
Col = 1
Next xParent
End Sub
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
Since you are on a mac, you could add yourself to the _www (the apache user group) group on your mac:
sudo dseditgroup -o edit -a $USER -t user _www
and add _www user to the wheel group which seems to be what the mac creates files as:
sudo dseditgroup -o edit -a _www -t user wheel
**The best is to use try except block to get rid of EOF **
try:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
except EOFError as e:
print(end="")
I had the same error and google brought me to this question, so here is what I did, hoping that it helps others in a similar situation.
This is applicable for OS X.
Check in the Terminal which version of OpenSSL I had:
$ python3 -c "import ssl; print(ssl.OPENSSL_VERSION)"
>> OpenSSL 0.9.8zh 14 Jan 2016
As my version of OpenSSL was too old, the accepted answer did not work.
So I had to update OpenSSL. To do this, I updated Python to the latest version (from version 3.5 to version 3.6) with Homebrew, following some of the steps suggested here:
$ brew update
$ brew install openssl
$ brew install python3
Then I was having problems with the PATH and the version of python being used, so I just created a new virtualenv
making sure that the newest version of python was taken:
$ virtualenv webapp --python=python3.6
Issue solved.
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
They do behave differently when the value
is null
.
null.toString()
throws an error - Cannot call method 'toString' of nullString(null)
returns - "null"null + ""
also returns - "null"Very similar behaviour happens if value
is undefined
(see jbabey's answer).
Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
Check out: MSDN Article
You can use GetModuleName
(I think?) to get the name and check against that.
Passing data to view is simple as passing object to method. Take a look at Controller.View Method
protected internal ViewResult View(
Object model
)
Something like this
//controller
List<MyObject> list = new List<MyObject>();
return View(list);
//view
@model List<MyObject>
// and property Model is type of List<MyObject>
@foreach(var item in Model)
{
<span>@item.Name</span>
}
I actually managed to work out what I was doing wrong (and it was my fault).
I'm used to using pre-jQuery Rails, so when I included the Bootstrap JS files I didn't think that including the version of jQuery bundled with them would cause any issues, however when I removed that one JS file everything started working perfectly.
Lesson learnt, triple check which JS files are loaded, see if there's any conflicts.
If you set your UILable properties from Plain to Attributed...the UILabel will hold multiline text no matter how many paragraphs for along as your UILabel height and width are set to fit the screen area you want to display the text in.
After reading the w3.org spec. I found the sandbox property.
You can set sandbox=""
, which prevents the iframe from redirecting. That being said it won't redirect the iframe either. You will lose the click essentially.
Example here: http://jsfiddle.net/ppkzS/1/
Example without sandbox: http://jsfiddle.net/ppkzS/
I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
1.The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226). Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.
For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.
Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime? The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state: 1) If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061 2) If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy. a. This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds). 3) If the Windows Update service is in a non-ready state, you can see errors reflecting that. a. We recently investigated a failure with an error code indicating the WUSA service was shutting down.
To identify if the prerequisite KB2919355 is installed there are 2 options: Registry key: 64bit hive HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14 CurrentState = 112 32bit hive HKLM\SOFTWARE[WOW6432Node]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14 CurrentState = 112
Or check the file version of: C:\Windows\SysWOW64\wuaueng.dll C:\Windows\System32\wuaueng.dll 7.9.9600.17031 or later
You could use module scope. Say you have a module called utils
:
f_value = 'foo'
def f():
return f_value
f_value
is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils
from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value
in the local scope, but then rebinding it to the string bar
, while the function f
is still referring to the module attribute.
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.
If you want to know if it is a reference, you can use ref
. If you want to know the reference type,
you can use the reftype
routine from Scalar::Util.
If you want to know if it is an object, you can use the blessed
routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL
has some methods to tell you about an object: if you want to check that it has the method you want to call, use can
; if you want to see that it inherits from something, use isa
; and if you want to see it the object handles a role, use DOES
.
If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied
. If you get an object, continue your checks.
If you want to know if it looks like a number, you can use looks_like_number
from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.
If you need to do something more fancy, you can use a module such as Params::Validate.
In my situation, this error seems to occur only if my client's computer has a strict firewall policy, which prevents my program from communicating with the web service.
So only solution I could find is to catch the error and inform user about changing the firewall settings manually.
I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
You need to link the with the -lm
linker option
You need to compile as
gcc test.c -o test -lm
gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l
linker option followed by the library name m
thus -lm
.
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
The easier way I believe to be:
import time
def executeSomething():
#code here
time.sleep(60)
while True:
executeSomething()
This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D
Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.
If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.
I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.
The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].
Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.
you can use like this:
string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
You can use the Pattern
class for this. If you want to match only word characters inside the {}
then you can use the following regex. \w
is a shorthand for [a-zA-Z0-9_]
. If you are ok with _
then use \w
or else use [a-zA-Z0-9]
.
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
Remove Padding: 10%;
or use px instead of percent for .wrap
see the example : http://jsfiddle.net/C93mk/493/
HTML :
<div id="wrapper">
<div id="wrap">
Some relative item placed item
<div id="fixed"></div>
</div>
</div>
CSS:
body{ height:20000px }
#wrapper {padding:10%;}
#wrap{
float: left;
position: relative;
width: 200px;
background:#ccc;
}
#fixed{
position:fixed;
width:inherit;
padding:0px;
height:10px;
background-color:#333;
}
This is how I did it.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SAP Multiple Entries");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(10,10,10,10));
frame.setLayout(new FlowLayout());
frame.setSize(512, 512);
JButton button = new JButton("Select File");
button.setPreferredSize(new Dimension(256, 256));
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
keep = selectedFile.getAbsolutePath();
// System.out.println(keep);
//out.println(file.flag);
if(file.flag==true) {
JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
For the correct and efficient computation of the hash value of a file (in Python 3):
'b'
to the filemode) to avoid character encoding and line-ending conversion issues.readinto()
to avoid buffer churning.Example:
import hashlib
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
If you're looking to only download the punkt
model:
import nltk
nltk.download('punkt')
If you're unsure which data/model you need, you can install the popular datasets, models and taggers from NLTK:
import nltk
nltk.download('popular')
With the above command, there is no need to use the GUI to download the datasets.
I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :
compile fileTree(dir: 'libs', include: '*.jar')}
BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries
http://tools.android.com/recent
Hope this helps people!
This simple example shows how to capture curl output, and use it in a bash script
function main
{
\curl -vs 'http://google.com' 2>&1
# note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file.
}
# capture output of curl to a variable
OUT=$(main)
# search output for something using grep.
echo
echo "$OUT" | grep 302
echo
echo "$OUT" | grep title
There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.
GUI:
Output:
This is how you can modify registry, without yes or no prompt and don't forget to run as administrator
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\etc\etc /v Valuename /t REG_SZ /d valuedata /f
Below is a real example to set internet explorer as my default browser
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice /v ProgId /t REG_SZ /d IE.HTTPS /f
/f Force: Force an update without prompting "Value exists, overwrite Y/N"
/d Data : The actual data to store as a "String", integer etc
/v Value : The value name eg ProgId
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ
Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from here
Use std::uppercase
and std::hex
to format integer variable a
to be displayed in hexadecimal format.
#include <iostream>
int main() {
int a = 255;
// Formatting Integer
std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
std::cout << std::showbase << std::hex << a << std::endl; // Output: 0XFF
std::cout << std::nouppercase << std::showbase << std::hex << a << std::endl; // Output: 0xff
return 0;
}
I had something similar happen to me just recently. I updated my iPhone to 8.1.3, and started getting the 'application could not be verified' error message from Xcode on an app that installed just fine on the same iOS device from the same Mac just a few days ago.
I deleted the app from the device, restarted Xcode, and the app subsequently installed on the device just fine without any error message. Not sure if deleting the app was the fix, or the problem was due to "the phase of the moon".
The most efficient selector you can use is an attribute selector.
input[name="btnPage"]:hover {/*your css here*/}
Here's a live demo: http://tinkerbin.com/3G6B93Cb
The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app). The Home button is considered the user's "safe zone" and will always launch the user's configured home app.
The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
When pressing the home button, the current home app's activity's onNewIntent
will be called.
I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.
@mixin fade-in {
opacity: 1;
animation-name: fadeInOpacity;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-duration: 2s;
}
@keyframes fadeInOpacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
and if you don't want to use mixins, you can create a normal class .fade-in.
I remember someday that I spent a lot of time trying to center a div, using margin: 0 auto
.
I had display: inline-block
on it, when I removed it, the div centered correctly.
As Ross pointed out, it doesn't work on inline elements.
Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.
The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.
Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.
Open the System Properties box. Via Command line use sysdm.cpl
** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **
Re-open the Device Manager, under view click Show Hidden Devices.
From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.
ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#
Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.
Below code worked fine for me
using System.Diagnostics;
public void ExecuteBatFile()
{
Process proc = null;
string _batDir = string.Format(@"C:\");
proc = new Process();
proc.StartInfo.WorkingDirectory = _batDir;
proc.StartInfo.FileName = "myfile.bat";
proc.StartInfo.CreateNoWindow = false;
proc.Start();
proc.WaitForExit();
ExitCode = proc.ExitCode;
proc.Close();
MessageBox.Show("Bat file executed...");
}
Don't do this.
Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages
or /var/opt/udi
or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.
Bottom line: Do not mingle code and data.
Data is precious. Code comes and goes.
Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)
Make it a required argument value and do this.
import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )
Do not "assume" a directory based on the location of your software. It will not work out well in the long run.
GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.
You can also use percentages, and/or specify in the column headers:
<table width="300">
<tr>
<th width="20%">Column 1</th>
<th width="20%">Column 2</th>
<th width="20%">Column 3</th>
<th width="20%">Column 4</th>
<th width="20%">Column 5</th>
</tr>
<tr>
<!--- row data -->
</tr>
</table>
The bonus with percentages is lower code maintenance: you can change your table width without having to re-specify the column widths.
Caveat: It is my understanding that table width specified in pixels isn't supported in HTML 5; you need to use CSS instead.
Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang
#!/bin/sh -
(it can also be two dashes, i.e. --
) ends bash options everything after will be treated as filenames and arguments.
Using the env
command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use
#!/usr/bin/env bash
Or for whatever the language such as for Perl
#!/usr/bin/env perl
Be sure to look at the man
pages for bash
:
man bash
and env
:
man env
Note: On Debian and Debian-based systems, like Ubuntu, sh
is linked to dash
not bash
. As all system scripts use sh
. This allows bash to grow and the system to stay stable, according to Debian.
Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.
This is what I did.
Note: Please check App.js for the code.
If you liked it, you can drop a star.??
Update:
import * as htmlToImage from 'html-to-image';
import download from 'downloadjs';
import logo from './logo.svg';
import './App.css';
const App = () => {
const onButtonClick = () => {
var domElement = document.getElementById('my-node');
htmlToImage.toJpeg(domElement)
.then(function (dataUrl) {
console.log(dataUrl);
download(dataUrl, 'image.jpeg');
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
};
return (
<div className="App" id="my-node">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a><br></br>
<button onClick={onButtonClick}>Download as JPEG</button>
</header>
</div>
);
}
export default App;
Why are you changing android os inbuilt theme.
As per your activity Require You have to implements this way
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
as per @arianoo
says you have to used this feature.
I think this is better way to hide titlebar theme.
This worked well for me (MySQL 5.5), also solving the problem of a "starting" position.
SELECT
IF(res.nextID, res.nextID, @r) AS nextID
FROM
(SELECT @r := 30) AS vars,
(
SELECT MIN(t1.id + 1) AS nextID
FROM test t1
LEFT JOIN test t2
ON t1.id + 1 = t2.id
WHERE t1.id >= @r
AND t2.id IS NULL
AND EXISTS (
SELECT id
FROM test
WHERE id = @r
)
LIMIT 1
) AS res
LIMIT 1
As mentioned before these types of queries are very slow, at least in MySQL.
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.
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.title = "Notes"
let sendButton = UIBarButtonItem(title: "New", style: .plain, target: self, action: #selector(goToNoteEditorViewController))
self.tabBarController?.navigationItem.rightBarButtonItem = sendButton
}
func goToNoteEditorViewController(){
// action what you want
}
Hope it helps!! #swift 3
\a
is the bell/alert character, which on some systems triggers a sound. \nnn
, represents an arbitrary ASCII character in octal base. However, \0
is special in that it represents the null character no matter what.
To answer your original question, you could escape your '0' characters as well, as:
std::string ("\060\000\060", 3);
(since an ASCII '0' is 60 in octal)
The MSDN documentation has a pretty detailed article on this, as well cppreference
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject)
;
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.
A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.
You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well - you should.
You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that."
. As suggested in this answer.
This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.
Here is a CSS trick you could use:
video {
pointer-events: none;
}
CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls
cannot be enabled either, in other words they must be set to false
. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video
tag then this is a feasible option.
controls
also has a download button so using it is not such a good idea either.
Here is a JSFiddle example.
If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).
From TxRegex answer:
<video oncontextmenu="return false;" controls>
<source type="video/mp4" id="video">
</video>
Now add the video via JavaScript:
document.getElementById("video").src = "https://www.w3schools.com/html/mov_bbb.mp4";
Functional JSFiddle
Another way to prevent right click involves using the embed
tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:
<embed src="https://www.w3schools.com/html/mov_bbb.mp4"></embed>
var temp="/yourapp/";
$(location).attr('href','http://abcd.com'+temp);
Try this... used as an alternative
Async Arrow function syntax with parameters
const myFunction = async (a, b, c) => {
// Code here
}
I was facing same problem.
When I rightclick-> run on server then select my server manually it worked.
Do
Alt+Shift+X
then mannually select your server. It might help.
Use this code to pass arraylist<customobj>
to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);
//An example of implementation :
// we set the score of one player to a value
[Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1];
// We copy the value in a NSNumber
NSNumber *aNumber = [Game getCurrent].scorePlayer1;
// Conversion of the NSNumber aNumber to a String with stringValue
NSString *StringScorePlayer1 = [aNumber stringValue];
I've got this problem too. My solution is use Expanded
widget to expand remain space.
new Column(
children: <Widget>[
new Expanded(
child: horizontalList,
)
],
);
If you have new mac you can go to IOS developer center --> Provisioning Portal --> Certificates --> Development --> Revoke and create new certificate. My problem solved. My error is "Code Sign error: The identity 'iPhone Developer' doesn't match any valid, non-expired certificate/private key pair in your keychains"
Make sure to have your apache SSH dlls loading correctly. On a fresh install I had to download and load into my apache bin directory the following dll "libssh2.dll"
After ssl dll was loaded cURL was able to load with no issues.
You can download it from the link below:
If you subclass InputFilter you can create your own InputFilter that would filter out any non-alpha-numeric characters.
The InputFilter Interface has one method, filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
, and it provides you with all the information you need to know about which characters were entered into the EditText it is assigned to.
Once you have created your own InputFilter, you can assign it to the EditText by calling setFilters(...).
http://developer.android.com/reference/android/text/InputFilter.html#filter(java.lang.CharSequence, int, int, android.text.Spanned, int, int)
So I run a functionally equivalent form of your code in an IPython notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()
I get what I believe to be very reasonable output.
It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?
The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.
import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline
# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)
Besides len
you can also use operator.length_hint
(requires Python 3.4+). For a normal list
both are equivalent, but length_hint
makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:
>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3
>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3
But length_hint
is by definition only a "hint", so most of the time len
is better.
I've seen several answers suggesting accessing __len__
. This is all right when dealing with built-in classes like list
, but it could lead to problems with custom classes, because len
(and length_hint
) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize
value). So it's always safer to use the len
function instead of the __len__
method!
I think your problem is that the margin should be specified in the border tag and not in the grid.
To import classes on the fly :
On OSX press Alt(Option) + Enter.
I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject")
to @RequestBody
. Like this:
@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {
@RequestMapping(method = RequestMethod.POST)
public String post(@RequestBody NewObject newObject) {
// ...
}
}
Then in your tests you can simply say:
NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject
mockMvc.perform(MockMvcRequestBuilders.post(uri)
.content(asJsonString(newObjectInstance))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
Where the asJsonString
method is just:
public static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I disagree on the comment posted by Hogan. Those instructions will work for IBM DB2 Mini, but it's not the case of DB2 Z/OS.
Here is an example:
Exception data: org.apache.ibatis.exceptions.PersistenceException:
The error occurred while setting parameters
SQL: INSERT INTO TABLENAME(ID_, F1_, F2_, F3_, F4_, F5_) VALUES
(?, 1, ?, ?, ?, ?),
(?, 1, ?, ?, ?, ?)
Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException:
ILLEGAL SYMBOL ",". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: FOR <END-OF-STATEMENT> NOT ATOMIC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.25.17
So I can confirm that inline comma separated bulk inserts are not working on DB2 Z/OS (maybe you could feed it some props to get it working...)
For US Address Parsing,
I prefer using usaddress package that is available in pip for usaddress only
python3 -m pip install usaddress
This worked well for me for US address.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# address_parser.py
import sys
from usaddress import tag
from json import dumps, loads
if __name__ == '__main__':
tag_mapping = {
'Recipient': 'recipient',
'AddressNumber': 'addressStreet',
'AddressNumberPrefix': 'addressStreet',
'AddressNumberSuffix': 'addressStreet',
'StreetName': 'addressStreet',
'StreetNamePreDirectional': 'addressStreet',
'StreetNamePreModifier': 'addressStreet',
'StreetNamePreType': 'addressStreet',
'StreetNamePostDirectional': 'addressStreet',
'StreetNamePostModifier': 'addressStreet',
'StreetNamePostType': 'addressStreet',
'CornerOf': 'addressStreet',
'IntersectionSeparator': 'addressStreet',
'LandmarkName': 'addressStreet',
'USPSBoxGroupID': 'addressStreet',
'USPSBoxGroupType': 'addressStreet',
'USPSBoxID': 'addressStreet',
'USPSBoxType': 'addressStreet',
'BuildingName': 'addressStreet',
'OccupancyType': 'addressStreet',
'OccupancyIdentifier': 'addressStreet',
'SubaddressIdentifier': 'addressStreet',
'SubaddressType': 'addressStreet',
'PlaceName': 'addressCity',
'StateName': 'addressState',
'ZipCode': 'addressPostalCode',
}
try:
address, _ = tag(' '.join(sys.argv[1:]), tag_mapping=tag_mapping)
except:
with open('failed_address.txt', 'a') as fp:
fp.write(sys.argv[1] + '\n')
print(dumps({}))
else:
print(dumps(dict(address)))
Running the address_parser.py
python3 address_parser.py 9757 East Arcadia Ave. Saugus MA 01906
{"addressStreet": "9757 East Arcadia Ave.", "addressCity": "Saugus", "addressState": "MA", "addressPostalCode": "01906"}
In this an arrow on compass shows the direction from your location to Kaaba(destination Location)
you can simple use bearingTo in this way.bearing to will give you the direct angle from your location to destination location
Location userLoc=new Location("service Provider");
//get longitudeM Latitude and altitude of current location with gps class and set in userLoc
userLoc.setLongitude(longitude);
userLoc.setLatitude(latitude);
userLoc.setAltitude(altitude);
Location destinationLoc = new Location("service Provider");
destinationLoc.setLatitude(21.422487); //kaaba latitude setting
destinationLoc.setLongitude(39.826206); //kaaba longitude setting
float bearTo=userLoc.bearingTo(destinationLoc);
bearingTo will give you a range from -180 to 180, which will confuse things a bit. We will need to convert this value into a range from 0 to 360 to get the correct rotation.
This is a table of what we really want, comparing to what bearingTo gives us
+-----------+--------------+
| bearingTo | Real bearing |
+-----------+--------------+
| 0 | 0 |
+-----------+--------------+
| 90 | 90 |
+-----------+--------------+
| 180 | 180 |
+-----------+--------------+
| -90 | 270 |
+-----------+--------------+
| -135 | 225 |
+-----------+--------------+
| -180 | 180 |
+-----------+--------------+
so we have to add this code after bearTo
// If the bearTo is smaller than 0, add 360 to get the rotation clockwise.
if (bearTo < 0) {
bearTo = bearTo + 360;
//bearTo = -100 + 360 = 260;
}
you need to implements the SensorEventListener and its functions(onSensorChanged,onAcurracyChabge) and write all the code inside onSensorChanged
Complete code is here for Direction of Qibla compass
public class QiblaDirectionCompass extends Service implements SensorEventListener{
public static ImageView image,arrow;
// record the compass picture angle turned
private float currentDegree = 0f;
private float currentDegreeNeedle = 0f;
Context context;
Location userLoc=new Location("service Provider");
// device sensor manager
private static SensorManager mSensorManager ;
private Sensor sensor;
public static TextView tvHeading;
public QiblaDirectionCompass(Context context, ImageView compass, ImageView needle,TextView heading, double longi,double lati,double alti ) {
image = compass;
arrow = needle;
// TextView that will tell the user what degree is he heading
tvHeading = heading;
userLoc.setLongitude(longi);
userLoc.setLatitude(lati);
userLoc.setAltitude(alti);
mSensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
if(sensor!=null) {
// for the system's orientation sensor registered listeners
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);//SensorManager.SENSOR_DELAY_Fastest
}else{
Toast.makeText(context,"Not Supported", Toast.LENGTH_SHORT).show();
}
// initialize your android device sensor capabilities
this.context =context;
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(context, "Started", Toast.LENGTH_SHORT).show();
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); //SensorManager.SENSOR_DELAY_Fastest
super.onCreate();
}
@Override
public void onDestroy() {
mSensorManager.unregisterListener(this);
Toast.makeText(context, "Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Location destinationLoc = new Location("service Provider");
destinationLoc.setLatitude(21.422487); //kaaba latitude setting
destinationLoc.setLongitude(39.826206); //kaaba longitude setting
float bearTo=userLoc.bearingTo(destinationLoc);
//bearTo = The angle from true north to the destination location from the point we're your currently standing.(asal image k N se destination taak angle )
//head = The angle that you've rotated your phone from true north. (jaise image lagi hai wo true north per hai ab phone jitne rotate yani jitna image ka n change hai us ka angle hai ye)
GeomagneticField geoField = new GeomagneticField( Double.valueOf( userLoc.getLatitude() ).floatValue(), Double
.valueOf( userLoc.getLongitude() ).floatValue(),
Double.valueOf( userLoc.getAltitude() ).floatValue(),
System.currentTimeMillis() );
head -= geoField.getDeclination(); // converts magnetic north into true north
if (bearTo < 0) {
bearTo = bearTo + 360;
//bearTo = -100 + 360 = 260;
}
//This is where we choose to point it
float direction = bearTo - head;
// If the direction is smaller than 0, add 360 to get the rotation clockwise.
if (direction < 0) {
direction = direction + 360;
}
tvHeading.setText("Heading: " + Float.toString(degree) + " degrees" );
RotateAnimation raQibla = new RotateAnimation(currentDegreeNeedle, direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
raQibla.setDuration(210);
raQibla.setFillAfter(true);
arrow.startAnimation(raQibla);
currentDegreeNeedle = direction;
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
image.startAnimation(ra);
currentDegree = -degree;
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
xml code is here
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/flag_pakistan">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/heading"
android:textColor="@color/colorAccent"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:layout_marginTop="20dp"
android:text="Heading: 0.0" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/heading"
android:scaleType="centerInside"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
<ImageView
android:id="@+id/imageCompass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/images_compass"/>
<ImageView
android:id="@+id/needle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:scaleType="centerInside"
android:src="@drawable/arrow2"/>
</RelativeLayout>
</RelativeLayout>
Firstly checked the list of installed Python packages by:
pip list | grep -i keras
If there is keras shown then install it by:
pip install keras --upgrade --log ./pip-keras.log
now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.
Is there a better way to get the EXACT count of the number of rows of a table?
To answer your question simply, No.
If you need a DBMS independent way of doing this, the fastest way will always be:
SELECT COUNT(*) FROM TableName
Some DBMS vendors may have quicker ways which will work for their systems only. Some of these options are already posted in other answers.
COUNT(*)
should be optimized by the DBMS (at least any PROD worthy DB) anyway, so don't try to bypass their optimizations.
On a side note:
I am sure many of your other queries also take a long time to finish because of your table size. Any performance concerns should probably be addressed by thinking about your schema design with speed in mind. I realize you said that it is not an option to change but it might turn out that 10+ minute queries aren't an option either. 3rd NF is not always the best approach when you need speed, and sometimes data can be partitioned in several tables if the records don't have to be stored together. Something to think about...
You do not have to install urllib3
. You can choose any HTTP-request-making library that fits your needs and feed the response to BeautifulSoup
. The choice is though usually requests
because of the rich feature set and convenient API. You can install requests
by entering pip install requests
in the command line. Here is a basic example:
from bs4 import BeautifulSoup
import requests
url = "url"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
My favourite (flot) has already been mentioned.
But be sure to investigate Ortho. It is excellent for tree charts and timelines.
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string
to either int
or Guid
, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext
:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
>>> [str(ord(string.lower(c)) - ord('a') + 1) for c in string.letters]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17',
'18', '19', '20', '21', '22', '23', '24', '25', '26', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
'25', '26']
You can do that using animate
like in the following link:
http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery
If you want to do it using scrollTo
plugin, then take a look the following:
How's this:
$(t).first().next()
Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t)
variable. Is it an array of <TD>
or is it a <TR>
node with several <TD>s
inside it?
To further illustrate the point, see the jsPerf scores on a <ul>
list with 50 <li>
children:
The $(t).first().next()
method is the fastest here, by far.
But, on the other hand, if you take the <tr>
node and find the <td>
children and and run the same test, the results won't be the same.
Hope it helps. :)
Thankfully, PHP developers aren't "Camel case bigots" like some development communities I know.
Your conventions sound fine.
Just so long as they're a) simple, and b) consistent - I don't see any problems :)
PS: Personally, I think 5) is overkill...
i used the empty div solution, with this CSS:
#throbber {
background-image: url(/Content/pictures/ajax-loader.gif);
background-repeat: no-repeat;
width: 48px;
height: 48px;
min-width: 48px;
min-height: 48px;
}
HTML:
<div id="throbber"></div>
To add to the other answers, note that property sheets can be configured for the project, creating custom project-specific parameters.
To access or create them navigate to(at least in Visual Studio 2013) View -> Other Windows -> Property Manager. You can also find them in the source folder as .prop files
check all the variables names in both of the combined files. Name of variables of both files to be combines should be exact same or else it will produce the above mentioned errors. I was facing the same problem as well, and after making all names same in both the file, rbind works accurately.
Thanks
select * from DB1.dbo.Table a inner join DB2.dbo.Table b on b.PrimKey = a.PrimKey
where a.FirstColumn <> b.FirstColumn ...
Checksum that Matt recommended is probably a better approach to compare columns rather than comparing each column
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
With jQuery this is working for me :
$('img').error(function() {
$(this).attr('src', '/no-img.png').addClass('no-img');
});
And I can use this picture everywhere on my website regardless of the size of it with the following CSS3 property :
img.no-img {
object-fit: cover;
object-position: 50% 50%;
}
TIP 1 : use a square image of at least 800 x 800 pixels.
TIP 2 : for use with portrait of people, use
object-position: 20% 50%;
For missing background images, I also added the following on each background-image
declaration :
background-image: url('path-to-image.png'), url('no-img.png');
NOTE : not working for transparent images.
Another solution is to detect missing image with Apache before to send to browser and remplace it by the default no-img.png content.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /images/.*\.(gif|jpg|jpeg|png)$
RewriteRule .* /images/no-img.png [L,R=307]
This is how did it works like a charm.
#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}
in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)
<div id="loader">
</div>
JS at the bottom of _layout file
<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
$("#loader").fadeOut(1000);
</script>
Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.
You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:
set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"
Open your SQL command line and type the following:
SQL> connect / as sysdba
Once connected,you can enter the following query to get details of username and password:
SQL> select username,password from dba_users;
This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user. For changing the password,use the below query:
SQL> alter user username identified by password;
Here username is the name of user whose password you want to change and password is the new password.
Building on Mark Byers's answer.
The 3rd project could be a WCF project, hosted as a Windows Service. If all programs listened to that service, one application could call the service. The service passes the message on to all listening clients and they can perform an action if suitable.
Good WCF videos here - http://msdn.microsoft.com/en-us/netframework/dd728059
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
Since nullptr
is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.
I know it is too late to answer to this question. But, I thought it would still be nice to share how I sorted this out when I had the same issue. Here is what I did.
Yes this is happening because you are accessing mi
variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi
so that's why its telling you to set it to final.
Complete code to disable SSL hostname verifier,
RestTemplate restTemplate = new RestTemplate();
//to disable ssl hostname verifier
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(new NoopHostnameVerifier());
}
super.prepareConnection(connection, httpMethod);
}
});
Try this
Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",
customer[DisplayPos],
sales_figures[DisplayPos],
fee_payable[DisplayPos],
seventy_percent_value,
thirty_percent_value);
where the first number inside the curly brackets is the index and the second is the alignment. The sign of the second number indicates if the string should be left or right aligned. Use negative numbers for left alignment.
Or look at http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx
If you are using jQuery there is a perfect function for you: .scrollTop()
doc here -> http://api.jquery.com/scrollTop/
note: you can use this function to retrieve OR set the position.
see also: http://api.jquery.com/?s=scroll
LSP says that ''Objects should be replaceable by their subtypes''. On the other hand, this principle points to
Child classes should never break the parent class`s type definitions.
and the following example helps to have a better understanding of LSP.
Without LSP:
public interface CustomerLayout{
public void render();
}
public FreeCustomer implements CustomerLayout {
...
@Override
public void render(){
//code
}
}
public PremiumCustomer implements CustomerLayout{
...
@Override
public void render(){
if(!hasSeenAd)
return; //it isn`t rendered in this case
//code
}
}
public void renderView(CustomerLayout layout){
layout.render();
}
Fixing by LSP:
public interface CustomerLayout{
public void render();
}
public FreeCustomer implements CustomerLayout {
...
@Override
public void render(){
//code
}
}
public PremiumCustomer implements CustomerLayout{
...
@Override
public void render(){
if(!hasSeenAd)
showAd();//it has a specific behavior based on its requirement
//code
}
}
public void renderView(CustomerLayout layout){
layout.render();
}
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
There's no need to add space before closing quote if path doesn't contain trailing backslash, so following command should work:
robocopy "C:\Source Path" "C:\Destination Path" /option1 /option2...
But, following will not work:
robocopy "C:\Source Path\" "C:\Destination Path\" /option1 /option2...
This is due to the escaping issue that is described here:
The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote " at the end of the line will be escaped \".
You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Pattern if you want to do this in order to extend the functionality of an existing object.
Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)
<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
}
$('#clickme').on('click', function() {
bootstrap_alert.warning('Your text goes here');
});
</script>?
EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js
You need to implement RefreshTokenProvider. First create class for RefreshTokenProvider ie.
public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
public override void Create(AuthenticationTokenCreateContext context)
{
// Expiration time in seconds
int expire = 5*60;
context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
context.SetToken(context.SerializeTicket());
}
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
}
Then add instance to OAuthOptions.
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/authenticate"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(expire),
RefreshTokenProvider = new ApplicationRefreshTokenProvider()
};
Your formula looks fine. Maybe the value you are looking for is not in the first column of the second table?
If the second sheet is in another workbook, you need to add a Workbook reference to your formula:
=VLOOKUP(M3,[Book1]Sheet1!$A$2:$Q$47,13,FALSE)
The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.
In my case i was missing trailing /
in path.
find /var/opt/gitlab/backups/ -name *.tar
I had the same problem, no possible connection at second login.
After solving the problem (useSecurity, etc., see above), I realized that admin/admin worked (with Synology, it that's relevant).
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
This one works better if you don't have the python on path or want to specify the directory :
//for Windows
npm config set python C:\Python27\python.exe
//for Linux
npm config set python /usr/bin/python27