After all the Jquery script tag's add
<script>jQuery.noConflict();</script>
to avoid the conflict between Prototype and Jquery.
I think this one is working. Recording a video or audio;
<input type="file" accept="video/*;capture=camcorder">
<input type="file" accept="audio/*;capture=microphone">
or (new method)
<device type="media" onchange="update(this.data)"></device>
<video autoplay></video>
<script>
function update(stream) {
document.querySelector('video').src = stream.url;
}
</script>
If it is not, probably will work on ios6, more detail can be found at get user media
Extracted from this comment by bkDJ:
^(?!bar$).*
The nice property of this solution is that it's possible to clearly negate (exclude) multiple words:
^(?!bar$|foo$|banana$).*
In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items()
; loading is a simple OrderedDict(<list of key-value pairs>)
. This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order).
It is indeed nice to take advantage of the fact that json
dumps the OrderedDict in the correct order. However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook
argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too.
I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.
So, for instance, on your HTML...
<a class="btn" ng-remove-birthday="$index">Delete</a>
Then, create a directive...
angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
return function(scope, element, attrs){
angular.element(element.bind('click', function(){
myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);
};
};
}])
Then in your service...
angular.module('myApp').factory('myService', [function(){
return {
removeBirthday: function(birthdayIndex, scope){
scope.bdays.splice(birthdayIndex);
scope.$apply();
}
};
}]);
When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.
For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.
Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)
Happy Developing!!!
Generally I just use the command line for svn
, it's the fastest and easiest way to do it to be honest, I'd recommend you try it.
Before you dismiss this, you should probably ask yourself if there is really any feature that you need a GUI for, and whether you would prefer to open up a GUI app and download the files, or just type svn co svn://site-goes-here.org/trunk
You can easily add
, remove
, move
, commit
, copy
or update
files with simple commands given with svn help
, so for most users it is more than enough.
Actually, the best solution is using JSON:
JSON.parse(text[, reviver]);
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3) Passing a function to JSON
var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();
Check this out.
Exponential is worse than polynomial.
O(n^2) falls into the quadratic category, which is a type of polynomial (the special case of the exponent being equal to 2) and better than exponential.
Exponential is much worse than polynomial. Look at how the functions grow
n = 10 | 100 | 1000
n^2 = 100 | 10000 | 1000000
k^n = k^10 | k^100 | k^1000
k^1000 is exceptionally huge unless k is smaller than something like 1.1. Like, something like every particle in the universe would have to do 100 billion billion billion operations per second for trillions of billions of billions of years to get that done.
I didn't calculate it out, but ITS THAT BIG.
If you want to set environment variables permanently in Git-Bash, you have two options:
Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.
Set up env variables in .bash_profile
file.
.bash_profile
is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile
. You can change the path to the bash home folder by setting HOME
Windows environment variable.
.bash_profile
file uses the regular Bash syntax and commands
# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir
# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"
Read more information about Bash configurations files.
The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.
If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.
The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.
require 'alien'
if alien.platform == "windows" then
kernel32 = alien.load("kernel32.dll")
sleep = kernel32.Sleep
sleep:types{ret="void",abi="stdcall","uint"}
else
-- untested !!!
libc = alien.default
local usleep = libc.usleep
usleep:types('int', 'uint')
sleep = function(ms)
while ms > 1000 do
usleep(1000)
ms = ms - 1000
end
usleep(1000 * ms)
end
end
print('hello')
sleep(500) -- sleep 500 ms
print('world')
First you need to understand, that both are different things. Stored Procedures
are best used for INSERT-UPDATE-DELETE
statements. Whereas Views
are used for SELECT
statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE
on Views
.
Which Oracle client are you using?
Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.
Basic validation can be performed by choosing the type attribute of input elements. For example:
<input type="email" />
<input type="URL" />
<input type="number" />
using pattern attribute like:
<input type="text" pattern="[1-4]{5}" />
required attribute
<input type="text" required />
maxlength:
<input type="text" maxlength="20" />
min & max:
<input type="number" min="1" max="4" />
GNU Trove support this but not using generics. http://trove4j.sourceforge.net/javadocs/gnu/trove/TObjectIntHashMap.html
First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :
PM> Install-Package SignalR.Hosting.Self -Version 0.5.2
PM> Install-Package Microsoft.AspNet.SignalR.Client
Then add the following code to your projects ;)
(run the projects as administrator)
Server console app:
using System;
using SignalR.Hubs;
namespace SignalR.Hosting.Self.Samples {
class Program {
static void Main(string[] args) {
string url = "http://127.0.0.1:8088/";
var server = new Server(url);
// Map the default hub url (/signalr)
server.MapHubs();
// Start the server
server.Start();
Console.WriteLine("Server running on {0}", url);
// Keep going until somebody hits 'x'
while (true) {
ConsoleKeyInfo ki = Console.ReadKey(true);
if (ki.Key == ConsoleKey.X) {
break;
}
}
}
[HubName("CustomHub")]
public class MyHub : Hub {
public string Send(string message) {
return message;
}
public void DoSomething(string param) {
Clients.addMessage(param);
}
}
}
}
Client console app:
using System;
using SignalR.Client.Hubs;
namespace SignalRConsoleApp {
internal class Program {
private static void Main(string[] args) {
//Set connection
var connection = new HubConnection("http://127.0.0.1:8088/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("CustomHub");
//Start connection
connection.Start().ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine("Connected");
}
}).Wait();
myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error calling send: {0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine(task.Result);
}
});
myHub.On<string>("addMessage", param => {
Console.WriteLine(param);
});
myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();
Console.Read();
connection.Stop();
}
}
}
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
Here is what you can try
OpenWindow.document.write(output);
call OpenWindow.init()
when the dom is ready So the parent window will have
OpenWindow.onload = function(){
OpenWindow.init('test');
}
and in the child
function init(txt){
$('#test').text(txt);
}
The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.
BOTTOM PART OF _Layout.cshtml:
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
I moved them above the @RenderBody() and all was fine.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
The empty string is false as a rule.
Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.
Just put this blur view on the imageView. Here is an example in Objective-C:
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = imageView.bounds;
[imageView addSubview:visualEffectView];
and Swift:
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
visualEffectView.frame = imageView.bounds
imageView.addSubview(visualEffectView)
And yet another approach using the decorator pattern and PHPs magic getter & setters:
// A simple StdClass object
$stdclass = new StdClass();
$stdclass->foo = 'bar';
// Decorator base class to inherit from
class Decorator {
protected $object = NULL;
public function __construct($object)
{
$this->object = $object;
}
public function __get($property_name)
{
return $this->object->$property_name;
}
public function __set($property_name, $value)
{
$this->object->$property_name = $value;
}
}
class MyClass extends Decorator {}
$myclass = new MyClass($stdclass)
// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
echo $object->foo . '<br>';
$object->foo = 'baz';
echo $object->foo;
}
test($myclass);
Commenting both Fetch
and LazyCollection
sometimes helps to run project.
@Fetch(FetchMode.JOIN)
@LazyCollection(LazyCollectionOption.FALSE)
get
takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.
dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'
If you do not give the second parameter, None
will be returned.
If you use indexing as in dictionary['Year']
, nonexistent keys will raise KeyError
.
You can use the eclipse plugin as suggested by Oscar earlier. Or if you are a command line person, you can use Apache Axis WSDL2Java tool from command prompt. You can find more details here http://axis.apache.org/axis/java/reference.html#WSDL2JavaReference
Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.
For example, in the directory with all the text files, execute the following:
for %f in (*.txt) do type "%f" >> combined.txt
This will merge all files matching *.txt into one file called combined.txt.
For more information:
About REST return codes: it is wrong to mix HTTP protocol codes and REST results.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.
For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?
Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.
Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".
For ES6/ES2015 you can import directly like:
// example.json
{
"name": "testing"
}
// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
If you use typescript, you may declare json module like:
// tying.d.ts
declare module "*.json" {
const value: any;
export default value;
}
Set a https://mitmproxy.org/ as proxy on a same LAN
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
If you want to use it with groups, you can use:
library(plyr)
mydata<-mtcars
ddply(mydata,.(carb),colwise(sd))
carb mpg cyl disp hp drat wt qsec vs am gear
1 1 6.001349 0.9759001 75.90037 19.78215 0.5548702 0.6214499 0.590867 0.0000000 0.5345225 0.5345225
2 2 5.472152 2.0655911 122.50499 43.96413 0.6782568 0.8269761 1.967069 0.5270463 0.5163978 0.7888106
3 3 1.053565 0.0000000 0.00000 0.00000 0.0000000 0.1835756 0.305505 0.0000000 0.0000000 0.0000000
4 4 3.911081 1.0327956 132.06337 62.94972 0.4575102 1.0536001 1.394937 0.4216370 0.4830459 0.6992059
5 6 NA NA NA NA NA NA NA NA NA NA
6 8 NA NA NA NA NA NA NA NA NA NA
You might have an old (global) installation of npm which causes the issue. As of 12/19, npm does not support global installations.
First, uninstall the package using:
npm uninstall -g create-react-app
Some osx/Linux users may need to also remove the old npm using:
rm -rf /usr/local/bin/create-react-app
This is now the only supported method for generating a project:
npx create-react-app my-app
Finally you can run:
npm start
You could use curl
instead. It is installed by default into /usr/bin
.
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.
Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)
byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations
You see that we simply apply the .decode(utf8)
function.
https://docs.python.org/3.3/library/stdtypes.html#bytes
https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals
stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "u" | "R" | "U"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
stringescapeseq ::= "\" <any source character>
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
pch=20 returns a symbol sized between "." and 19.
It's a filled symbol (which is probably what you want).
Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,
dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)
with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
ann=F, bg="steelblue2", fg=NULL))
Use libraries https://jar-download.com/maven-repository-class-search.php?search_box=org.apache.http.entity.mime Download the library and put it in your project
The standard Python library module random has what you want:
normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.
For the algorithm itself, take a look at the function in random.py in the Python library.
Replace the value in select statement itself...
(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)
a:before {
content: "\f055";
font-family: FontAwesome;
left:0;
position:absolute;
top:0;
}
Example Link: https://codepen.io/bungeedesign/pen/XqeLQg
Get Icon code from: https://fontawesome.com/cheatsheet?from=io
If it's a sorted array you could use a Binary search algorithm (O(log n)
). For example, extending the Array-class with this functionality:
class Array
def b_search(e, l = 0, u = length - 1)
return if lower_index > upper_index
midpoint_index = (lower_index + upper_index) / 2
return midpoint_index if self[midpoint_index] == value
if value < self[midpoint_index]
b_search(value, lower_index, upper_index - 1)
else
b_search(value, lower_index + 1, upper_index)
end
end
end
In addition to the other answers, which I subscribe, you may consider using the /I
switch of the IF
command.
... the /I switch, if specified, says to do case insensitive string compares.
it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.
IF /I "%1"=="-b" GOTO SPECIFIC
Just add &
to the end of the command, e.g:
bash -c some_command && another_command &
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
You can use find()
>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s[:s.find('&')]
'http://www.domain.com/?s=some'
Of course, if there is a chance that the searched for text will not be present then you need to write more lengthy code:
pos = s.find('&')
if pos != -1:
s = s[:pos]
Whilst you can make some progress using code like this, more complex situations demand a true URL parser.
A very simple infinite loop.. :)
while true ; do continue ; done
Fr your question it would be:
while true; do foo ; sleep 2 ; done
Just use
del /f /q C:\Users\%username%\AppData\Local\temp
And it will work.
Note: It will delete the whole folder however, Windows will remake it as it needs.
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
Inner join and natural join are almost same but there is a slight difference between them. The difference is in natural join no need to specify condition but in inner join condition is obligatory. If we do specify the condition in inner join , it resultant tables is like a cartesian product.
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
If you're getting error TS1005: 'finally' expected.
, it means you forgot to implement catch
after try
. Generally, it means the syntax you attempted to use was incorrect.
I will expand on the earlier answer about np.fliplr()
. Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock()
will be used to keep time, which is presented in terms of seconds.
import time
import numpy as np
start = time.clock()
x = np.array(range(3))
#transform to 2d
x = np.atleast_2d(x)
#flip array
x = np.fliplr(x)
#take first (and only) element
x = x[0]
#print x
end = time.clock()
print end-start
With print statement uncommented:
[2 1 0]
0.00203907123594
With print statement commented out:
5.59799927506e-05
So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.
np.fliplr(np.atleast_2d(np.array(range(3))))[0]
Not sure if this sort of solves what you're after, or fits with your general development landscape but the first thing I would try would be to change the background colour of the button on the touchDown event.
Option 1:
You would need two events to be capture, UIControlEventTouchDown would be for when the user presses the button. UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];
[myButton setBackgroundColor:[UIColor blueColor]];
[myButton setTitle:@"click me:" forState:UIControlStateNormal];
[myButton setTitle:@"changed" forState:UIControlStateHighlighted];
[myButton addTarget:self action:@selector(buttonHighlight:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];
Option 2:
Return an image made from the highlight colour you want. This could also be a category.
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
and then change the highlighted state of the button:
[myButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];
Of course there is! Win CMD can do a lot more than just split text files :)
Split a text file into separate files of 'max' lines each:
Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000
set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul
echo Number of lines in %input%:
find /c /v "" < %input%
: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)
REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)
If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):
eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.
set
command to be fed to /g
flag of findstr
list1.txt
\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]
list2.txt
\[[3-5][0-9][0-9][0-9]\]
list3.txt
\[[6-9][0-9][0-9][0-9]\]
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do ( set a=%i set a=!a:*]=]! echo:!a:~1!>>file_1.txt)
Notes:
Works with leading whitespace, blank lines & whitespace lines.
Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.
I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.
Here's a utility class providing min/max
methods for primitive types: Primitives.java
int [] numbers= {10,1,8,7,6,5,2};
int a=Integer.MAX_VALUE;
for(int c:numbers) {
a=c<a?c:a;
}
System.out.println("Lowest value is"+a);
For XAMPP, do the following steps:
G:\xampp\apache\conf\extra\httpd-ssl.conf"
Search 'DocumentRoot' text.
Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".
if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile
require 'pull_tempfile'
PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
CSV.foreach(tmp_file.path) do |row|
# ....
end
end
In .Net 4, you can use the multipleSiteBindingsEnabled
option:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
Then, you won't have to specify each address.
By default, all paths you define will be relative. The question is: relative to what? There are several options:
Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.
I had this problem when running automated tests from a continuous integration server. I tried adding the VM argument "-Duser.timezone=GMT
" to the build parameters, but that didn't solve the problem. However, adding the environment variable "TZ=GMT
" did fix it for me.
Alternative solution, where you can have the database in the folder you want inside the solution. That worked for me:
.ConnectionString(@"Data Source=LocalDB)\MSSQLLocalDB;
AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
Integrated Security=True;")
function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];
moveElement(arr, "2","4");
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
Another way to do this is by using event listeners, here how you use them:
document.addEventListener("DOMContentLoaded", function() {
you_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
com/xyz/customandroid/ TextViewWithImages .java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TextViewWithImages extends TextView {
public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewWithImages(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithImages(Context context) {
super(context);
}
@Override
public void setText(CharSequence text, BufferType type) {
Spannable s = getTextWithImages(getContext(), text);
super.setText(s, BufferType.SPANNABLE);
}
private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
private static boolean addImages(Context context, Spannable spannable) {
Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
boolean hasChanges = false;
Matcher matcher = refImg.matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end()
) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
if (set) {
hasChanges = true;
spannable.setSpan( new ImageSpan(context, id),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
private static Spannable getTextWithImages(Context context, CharSequence text) {
Spannable spannable = spannableFactory.newSpannable(text);
addImages(context, spannable);
return spannable;
}
}
Use:
in res/layout/mylayout.xml:
<com.xyz.customandroid.TextViewWithImages
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF00"
android:text="@string/can_try_again"
android:textSize="12dip"
style=...
/>
Note that if you place TextViewWithImages.java in some location other than com/xyz/customandroid/, you also must change the package name, com.xyz.customandroid
above.
in res/values/strings.xml:
<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>
where ok16.png and retry16.png are icons in the res/drawable/ folder
I ran into the same problem while I was changing some npm settings. I did a mistake with one npm config set
command and this added a line referring to a non-existing directory to C:\Users\{User}\.npmrc
. After I deleted that line manually from .npmrc
, the problem was gone.
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html()
function to escape characters, your mileage may vary)
This example converts a songs current position into an angle range of 20 - 40.
/// <summary>
/// This test converts Current songtime to an angle in a range.
/// </summary>
[Fact]
public void ConvertRangeTests()
{
//Convert a songs time to an angle of a range 20 - 40
var result = ConvertAndGetCurrentValueOfRange(
TimeSpan.Zero, TimeSpan.FromMinutes(5.4),
20, 40,
2.7
);
Assert.True(result == 30);
}
/// <summary>
/// Gets the current value from the mixValue maxValue range.
/// </summary>
/// <param name="startTime">Start of the song</param>
/// <param name="duration"></param>
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <param name="value">Current time</param>
/// <returns></returns>
public double ConvertAndGetCurrentValueOfRange(
TimeSpan startTime,
TimeSpan duration,
double minValue,
double maxValue,
double value)
{
var timeRange = duration - startTime;
var newRange = maxValue - minValue;
var ratio = newRange / timeRange.TotalMinutes;
var newValue = value * ratio;
var currentValue= newValue + minValue;
return currentValue;
}
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
you have:
WHERE ID = " & siteID & ";", dbOpenSnapshot)
you need:
WHERE ID = "'" & siteID & "';", dbOpenSnapshot)
Note the extra quotations ('
). . . this kills me everytime
Edit: added missing double quote
The simplest solution would be to simply use an actual button
element, which centers its content vertically without any special CSS in most or all browsers, and can otherwise be styled as usual.
I got this issue when I accidently tried to update the object instead of save!
I had
if (IsNewSchema(model))
unitOfWork.SchemaRepository.Update(schema);
else
unitOfWork.SchemaRepository.Insert(schema);
when I should of had
if (IsNewSchema(model))
unitOfWork.SchemaRepository.Insert(schema);
else
unitOfWork.SchemaRepository.Update(schema);
Iterables.elementsEqual
is best choice:Iterables.elementsEqual
is enough to compare 2 List
s.
Iterables.elementsEqual
is used in more general scenarios, It accepts more general types: Iterable
. That is, you could even compare a List
with a Set
. (by iterate order, it is important)
Sure ArrayList
and LinkedList
define equals pretty good, you could call equals directly. While when you use a not well defined List, Iterables.elementsEqual
is the best choice. One thing should be noticed: Iterables.elementsEqual
does not accept null
To convert List to array: Iterables.toArray
is easer.
For unit test, I recommend add empty list to your test case.
Based on Guy Daher's answer.
I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.
I would do nil check if statement:
class CustomView: UIView
{
override func draw(_ rect: CGRect)
{
super.draw(rect)
if let context = UIGraphicsGetCurrentContext()
{
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
When static variable is declared in a header file is its scope limited to .h file or across all units.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.
As such, a static variable declared in a header file is like a static variable in each individual source file.
Since declaring a variable static
this way means internal linkage, every translation unit #include
ing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.
I would like to know what is the difference between static variables in a header file vs declared in a class.
In a class declaration, static
means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static
(or "class") variable, it's the same value for all objects. You could think of it as a "class global".
Also generally static variable is initialized in .cpp file when declared in a class right ?
Yes, one (and only one) translation unit must initialize the class variable.
So that does mean static variable scope is limited to 2 compilation units ?
As I said:
static
means completely different things depending on context.Global static
limits scope to the translation unit. Class static
means global to all instances.
I hope this helps.
PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static
in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )
Since May 23, 2018 update, when you're using a firebase dependency, you must include the firebase-core
dependency, too.
If adding it, you still having the error, try to update the gradle plugin in your gradle-wrapper.properties
to 4.5 version:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
and resync the project.
If you want to dump all collections, run this command:
mongodump -d {DB_NAME} -o /tmp
It will generate all collections data in json
and bson
extensions into /tmp/{DB_NAME}
directory
Using http.createServer
is very low-level and really not useful for creating web applications as-is.
A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express
.
When you have, you can create a basic application to handle your form:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
You can make your form point to it using:
<form action="http://127.0.0.1:8080/myaction" method="post">
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html
). You could use Express to also serve static content, like index.html
, using the express.static
middleware.
Yet another easy solution can be found at the link pasted here. This one easy to grasp and seems to be effective for most of the similar problems. It is for SQL Server though but the concept used is more than acceptable.
Here are the relevant portions from the linked page:
Consider this data:
EMPLOYEE_ID ATTENDANCE_DATE
A001 2011-01-01
A001 2011-01-01
A002 2011-01-01
A002 2011-01-01
A002 2011-01-01
A003 2011-01-01
So how can we delete those duplicate data?
First, insert an identity column in that table by using the following code:
ALTER TABLE dbo.ATTENDANCE ADD AUTOID INT IDENTITY(1,1)
Use the following code to resolve it:
DELETE FROM dbo.ATTENDANCE WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
FROM dbo.ATTENDANCE GROUP BY EMPLOYEE_ID,ATTENDANCE_DATE)
const isEmpty = (value) => (
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
)
module.exports = isEmpty;
Not directly targeting the OP's scenario, but since I have been struggling with this, I'd like to drop these ex. methods that make it easier to execute raw SQL with the DbContext
:
public static class DbContextCommandExtensions
{
public static async Task<int> ExecuteNonQueryAsync(this DbContext context, string rawSql,
params object[] parameters)
{
var conn = context.Database.GetDbConnection();
using (var command = conn.CreateCommand())
{
command.CommandText = rawSql;
if (parameters != null)
foreach (var p in parameters)
command.Parameters.Add(p);
await conn.OpenAsync();
return await command.ExecuteNonQueryAsync();
}
}
public static async Task<T> ExecuteScalarAsync<T>(this DbContext context, string rawSql,
params object[] parameters)
{
var conn = context.Database.GetDbConnection();
using (var command = conn.CreateCommand())
{
command.CommandText = rawSql;
if (parameters != null)
foreach (var p in parameters)
command.Parameters.Add(p);
await conn.OpenAsync();
return (T)await command.ExecuteScalarAsync();
}
}
}
Use @ViewChildren
from @angular/core
to get a reference to the components
template
<div *ngFor="let v of views">
<customcomponent #cmp></customcomponent>
</div>
component
import { ViewChildren, QueryList } from '@angular/core';
/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
If you want the information in the form to be processed by the PHP page, then you HAVE to make a call to that PHP page. To avoid a redirection or refresh in this process, submit the form info via AJAX. Perhaps use jQuery dialog to display the results, or your custom animation.
sync and async file reading way:
//fs module to read file in sync and async way
var fs = require('fs'),
filePath = './sample_files/sample_css.css';
// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
});*/
//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);
Node Cheat Available at read_file.
I used a non-portable approach to retrieve the UNIX PID from the Process
object that is very simple to follow.
STEP 1:
Use some Reflection API calls to identify the Process
implementation class on the target server JRE (remember that Process
is an abstract class). If your UNIX implementation is like mine, you will see an implementation class that has a property named pid
that contains the PID of the process. Here is the logging code that I used.
//--------------------------------------------------------------------
// Jim Tough - 2014-11-04
// This temporary Reflection code is used to log the name of the
// class that implements the abstract Process class on the target
// JRE, all of its 'Fields' (properties and methods) and the value
// of each field.
//
// I only care about how this behaves on our UNIX servers, so I'll
// deploy a snapshot release of this code to a QA server, run it once,
// then check the logs.
//
// TODO Remove this logging code before building final release!
final Class<?> clazz = process.getClass();
logger.info("Concrete implementation of " + Process.class.getName() +
" is: " + clazz.getName());
// Array of all fields in this class, regardless of access level
final Field[] allFields = clazz.getDeclaredFields();
for (Field field : allFields) {
field.setAccessible(true); // allows access to non-public fields
Class<?> fieldClass = field.getType();
StringBuilder sb = new StringBuilder(field.getName());
sb.append(" | type: ");
sb.append(fieldClass.getName());
sb.append(" | value: [");
Object fieldValue = null;
try {
fieldValue = field.get(process);
sb.append(fieldValue);
sb.append("]");
} catch (Exception e) {
logger.error("Unable to get value for [" +
field.getName() + "]", e);
}
logger.info(sb.toString());
}
//--------------------------------------------------------------------
STEP 2:
Based on the implementation class and field name that you obtained from the Reflection logging, write some code to pickpocket the Process
implementation class and retrieve the PID from it using the Reflection API. The code below works for me on my flavour of UNIX. You may have to adjust the EXPECTED_IMPL_CLASS_NAME
and EXPECTED_PID_FIELD_NAME
constants to make it work for you.
/**
* Get the process id (PID) associated with a {@code Process}
* @param process {@code Process}, or null
* @return Integer containing the PID of the process; null if the
* PID could not be retrieved or if a null parameter was supplied
*/
Integer retrievePID(final Process process) {
if (process == null) {
return null;
}
//--------------------------------------------------------------------
// Jim Tough - 2014-11-04
// NON PORTABLE CODE WARNING!
// The code in this block works on the company UNIX servers, but may
// not work on *any* UNIX server. Definitely will not work on any
// Windows Server instances.
final String EXPECTED_IMPL_CLASS_NAME = "java.lang.UNIXProcess";
final String EXPECTED_PID_FIELD_NAME = "pid";
final Class<? extends Process> processImplClass = process.getClass();
if (processImplClass.getName().equals(EXPECTED_IMPL_CLASS_NAME)) {
try {
Field f = processImplClass.getDeclaredField(
EXPECTED_PID_FIELD_NAME);
f.setAccessible(true); // allows access to non-public fields
int pid = f.getInt(process);
return pid;
} catch (Exception e) {
logger.warn("Unable to get PID", e);
}
} else {
logger.warn(Process.class.getName() + " implementation was not " +
EXPECTED_IMPL_CLASS_NAME + " - cannot retrieve PID" +
" | actual type was: " + processImplClass.getName());
}
//--------------------------------------------------------------------
return null; // If PID was not retrievable, just return null
}
.hero-image {
background-image: url("photographer.jpg"); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
}
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
It seems strange that you would write arrays without commas (is that a MATLAB syntax?)
Have you tried going through NumPy's documentation on multi-dimensional arrays?
It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])
It has also been answered already...
From the documentation for MATLAB users:
You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:
mat("1 2 3; 4 5 6")
or
matrix("[1 2 3; 4 5 6]")
Please give it a try and tell me how it goes.
Provided that the remote repository is origin, and that you're interested in master:
git fetch origin
git reset --hard origin/master
This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.
All your local commits not common to the remote will be gone.
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
What worked for me was to activate the option for less secure apps (I am using VB.NET)
Public Shared Sub enviaDB(ByRef body As String, ByRef file_location As String)
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient("smtp.gmail.com")
mail.From = New MailAddress("[email protected]")
mail.[To].Add("[email protected]")
mail.Subject = "subject"
mail.Body = body
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(file_location)
mail.Attachments.Add(attachment)
SmtpServer.Port = 587
SmtpServer.Credentials = New System.Net.NetworkCredential("user", "password")
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
End Sub
So log in to your account and then go to google.com/settings/security/lesssecureapps
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
this code works on my proyect and i can select the listview item and checkbox
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true" >
<TextView
android:id="@+id/label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4" />
<CheckBox
android:id="@+id/check"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:focusable="false"
android:text="" >
</CheckBox>
</LinearLayout>
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
Why is $observe different than $watch?
The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.
$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}"
, the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.
See $observe & $set in compile.js
There's no way to use CSS for this purpose. My advice is to include a javascript code where you assign or change the css class applied to the inputs. Something like that :
function change_input() {_x000D_
$('#id_input1')_x000D_
.toggleClass('class_disabled')_x000D_
.toggleClass('class_enabled');_x000D_
_x000D_
$('.class_disabled').attr('disabled', '');_x000D_
$('.class_enabled').removeAttr('disabled', '');_x000D_
}
_x000D_
.class_disabled { background-color : #FF0000; }_x000D_
.class_enabled { background-color : #00FF00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<form> _x000D_
Input: <input id="id_input1" class="class_enabled" /> _x000D_
<input type="button" value="Toggle" onclick="change_input()";/> _x000D_
</form>
_x000D_
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work. Not sure why even the best answer didnt see this.
date("Y-m-d H:i:s"); // This should do it.
heres a DOM solution
myInput=document.getElementById("myinput");
oldHtml=myInput.outerHTML;
text=myInput.value;
newHtml=oldHtml.replace("password","text");
myInput.outerHTML=newHtml;
myInput=document.getElementById("myinput");
myInput.value=text;
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
You can decompile your .apk files and download online.
You can link libraries from cdn (Content delivery network):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
Or link libraries locally, add css files in the css folder and jquery in js folder. You have to keep both folders in the laravel public folder then you can link like below:
<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>
or else
{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}
If you link js files and css files locally (like in the last two examples) you need to add js
and css
files to the js
and css
folders which are in public\js
or public\css
not in resources\assets
.
Below code will fix root = tk.Tk()
to its size before it was called:
root.resizable(False, False)
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// Do something.
break;
case 5:
case 6:
case 7:
case 8:
// Do something.
break;
default:
break;
}
If you don't like the succession of cases, simply go for if/else if/else
statements.
I tried several approaches.
# BY {dplyr}
data.table(ID = c(rep("A", 5), rep("B",5)),
Quarter = c(1:5, 1:5),
value = rnorm(10)) -> df1
df1 %<>% dplyr::mutate(ID = as.factor(ID),
Quarter = as.character(Quarter))
# check classes
dplyr::glimpse(df1)
# Observations: 10
# Variables: 3
# $ ID (fctr) A, A, A, A, A, B, B, B, B, B
# $ Quarter (chr) "1", "2", "3", "4", "5", "1", "2", "3", "4", "5"
# $ value (dbl) -0.07676732, 0.25376110, 2.47192852, 0.84929175, -0.13567312, -0.94224435, 0.80213218, -0.89652819...
, or otherwise
# from list to data.table using data.table::setDT
list(ID = as.factor(c(rep("A", 5), rep("B",5))),
Quarter = as.character(c(1:5, 1:5)),
value = rnorm(10)) %>% setDT(list.df) -> df2
class(df2)
# [1] "data.table" "data.frame"
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
Find the C file and Makefile implementation in below to meet your requirements
foo.c
main ()
{
int a = MAKE_DEFINE;
printf ("MAKE_DEFINE value:%d\n", a);
}
Makefile
all:
gcc -DMAKE_DEFINE=11 foo.c
The new for-each
loop is just a short hand for the older loop. The new loop is easier to use for arrays and some iterators, but not as flexible, so the old loop has to be using in some situations, like counting from 0 to 9.
If you wanna use Javascript then you can use getElementsByName()
method to select the input
fields and to change the placeholder
for each one... see the below code...
document.getElementsByName('Email')[0].placeholder='new text for email';
document.getElementsByName('First Name')[0].placeholder='new text for fname';
document.getElementsByName('Last Name')[0].placeholder='new text for lname';
Otherwise use jQuery:
$('input:text').attr('placeholder','Some New Text');
Update:
Example from Microsoft:
Original
This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.
First I edited <src>\.vs\config\applicationhost.config
and made this change: <section name="access" overrideModeDefault="Allow" />
This allows me to edit <system.webServer>
in web.config
and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.
For production follow a guide like this to set up the IIS:
https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb
web.config:
<security>
<access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>
API Controller:
[RequireSpecificCert]
public class ValuesController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
return Ok("It works!");
}
}
Attribute:
public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
X509Certificate2 cert = actionContext.Request.GetClientCertificate();
if (cert == null)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate Required"
};
}
else
{
X509Chain chain = new X509Chain();
//Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
chain.ChainPolicy = new X509ChainPolicy()
{
RevocationMode = X509RevocationMode.NoCheck,
};
try
{
var chainBuilt = chain.Build(cert);
Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));
var validCert = CheckCertificate(chain, cert);
if (chainBuilt == false || validCert == false)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate not valid"
};
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
base.OnAuthorization(actionContext);
}
}
private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
{
var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);
var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);
//Check that the certificate have been issued by a specific Root Certificate
var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));
//Check that the certificate thumbprint matches our expected thumbprint
var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);
return validRoot && validCert;
}
}
Can then call the API with client certification like this, tested from another web project.
[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{
public IHttpActionResult Get()
{
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(GetClientCert());
handler.UseProxy = false;
var client = new HttpClient(handler);
var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return Ok(resultString);
}
private static X509Certificate GetClientCert()
{
X509Store store = null;
try
{
store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certificateSerialNumber= "?81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);
//Does not work for some reason, could be culture related
//var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);
//if (certs.Count == 1)
//{
// var cert = certs[0];
// return cert;
//}
var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));
return cert;
}
finally
{
store?.Close();
}
}
}
Others mentioned django-phonenumber-field
. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT
setting to "E164"
, "INTERNATIONAL"
, "NATIONAL"
, or "RFC3966"
, however you want it displayed. See the GitHub source.
For Bootstrap 3, there is
placement: 'auto right'
which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:
$('.infopoint').popover({
trigger:'hover',
animation: false,
placement: 'auto right'
});
Managing Java versions on Mac OSX is a nightmare. I recently switched over to using JDK 1.7, deleting JDK 6 from my MacBook entirely (I also had traces of JDK 5 - this laptop has been updated a few times).
Here's what I did to move to JDK 7.
1) download the latest from Oracle (http://www.oracle.com/technetwork/java/javase/downloads/index.html) and install it.
2) Remove (using rm - if you've got backups, you can revert if you make a mistake) all the JDK6 and JRE6 files.
At this stage, you should see:
% ls /Library/Java/JavaVirtualMachines/
jdk1.7.0_nn.jdk
(and nothing else)
3) In the folder /Library/Java/Extensions/, you'll need to remove all the old jar files, the ones that correspond to other releases of Java. If you don't, you'll get the infamous message about the wrong version of tools.jar (see Builds failing after upgrading to Java7, Missing Tools.jar and bad class versions). It is not enough to rename the jar files, because Java will open every jar in that folder - I moved mine into a sub-directory. It's safe to remove them once you know everything else works.
I haven't found I need to set JAVA_HOME for simple things.
Note: I just tried running IntelliJ and it will not start unless you have Apple's JDK 6 installed (see http://youtrack.jetbrains.com/issue/IDEA-93710). Same is true for Eclipse. Netbeans works fine.
Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.
On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.
As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.
The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.
The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.
The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
I had got the same error. Because of security reasons, I could not see option for allowing Apps downloaded from Anywhere in System preference-> Security Tab.
I removed the extended attribute from Zip file by below command.
xattr -d com.apple.quarantine [Zip file path]
And then got below error:- org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: javax/annotation/PostConstruct
Resolved it by uninstalling all different versions of java and installed just 1.8.0_231.
Worked finally.
This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
These are taken from my open source library, aFileChooser.
Sometimes the issue is with the version of the Java installed. I was facing a similar issue when trying to start Spring Tool Suite on my Ubuntu 16.04. I had java 9 installed on my machine. I changed it to java 8. And it started working.
Let's break this down:
The error says
Cannot invoke an expression whose type lacks a call signature.
The code:
The problem is in this line public toggleBody: string;
&
it's relation to these lines:
...
return this.toggleBody(true);
...
return this.toggleBody(false);
Your saying toggleBody
is a string
but then your treating it like something that has a call signature
(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc. In JS just function tho.). You need to change the declaration to be public toggleBody: (arg: boolean) => boolean;
.
Extra Details:
"invoke" means your calling or applying a function.
"an expression" in Javascript is basically something that produces a value, so this.toggleBody()
counts as an expression.
"type" is declared on this line public toggleBody: string
"lacks a call signature" this is because your trying to call something this.toggleBody()
that doesn't have signature(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc.) that can be called. You said this.toggleBody
is something that acts like a string.
In other words the error is saying
Cannot call an expression (this.toggleBody) because it's type (:string) lacks a call signature (bc it has a string signature.)
Stan's answer was the best one. But it also have a problem, when you use the controller with a Tab Bar and change the controller's title, you could change the Tab Bar's title too.So the best answer is change the view_controller.navigationItem.title only and use the view_controller.navigationItem.title in the function. Answer is here:(With ARC and add them into view's viewDidLoad)
static NSString * back_button_title=@"Back"; //or whatever u want
if (![view_controller.navigationItem.title isEqualToString:back_button_title]){
UILabel* custom_title_view = [[UILabel alloc] initWithFrame:CGRectZero];
custom_title_view.text = view_controller.navigationItem.title; // original title
custom_title_view.font = [UIFont boldSystemFontOfSize:20];
custom_title_view.backgroundColor = [UIColor clearColor];
custom_title_view.textColor = [UIColor whiteColor];
custom_title_view.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
custom_title_view.shadowOffset = CGSizeMake(0, -1);
[custom_title_view sizeToFit];
view_controller.navigationItem.titleView = custom_title_view;
view_controller.navigationItem.title = back_button_title;
}
In myself use, I make it a function like this, just have the feature with one line code in the viewDidLoad.
+ (void)makeSubViewHaveBackButton:(UIViewController*) view_controller{
static NSString * back_button_title=@"Back"; //or whatever u want
if (![view_controller.navigationItem.title isEqualToString:back_button_title]){
UILabel* custom_title_view = [[UILabel alloc] initWithFrame:CGRectZero];
custom_title_view.text = view_controller.navigationItem.title; // original title
custom_title_view.font = [UIFont boldSystemFontOfSize:20];
custom_title_view.backgroundColor = [UIColor clearColor];
custom_title_view.textColor = [UIColor whiteColor];
custom_title_view.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
custom_title_view.shadowOffset = CGSizeMake(0, -1);
[custom_title_view sizeToFit];
view_controller.navigationItem.titleView = custom_title_view;
view_controller.navigationItem.title = back_button_title;
}
}
A better way, use getParent()
from File
Class..
String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path
File file = new File(a);
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
http://developer.android.com/reference/java/io/File.html#getParent%28%29
Java does not support multiple inheritance.
There are a few workarounds I can think of:
The first is aggregation: make a class that takes those two activities as fields.
The second is to use interfaces.
The third is to rethink your design: does it make sense for a Preferences
class to be both a PreferenceActivity
and an AbstractBillingActivity
?
I prefix this reply with "you shouldn't use a regular expression to parse XML -- it's only going to result in edge cases that don't work right, and a forever-increasing-in-complexity regex while you try to fix it."
That being said, you need to proceed by matching the string and grabbing the group you want:
if (m.matches())
{
String result = m.group(1);
// do something with result
}
if you are running mongo for first time you might wanna set the path first
mongod --dbpath <path to the directory>
You can use a TextFormField
instead of TextField
, and use the initialValue
property. for example
TextFormField(initialValue: "I am smart")
Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the with
syntax).
with open('fileName', 'r') as f:
for line in f:
if 'str' in line:
break
The CLSID you describe is for the Microsoft.Office.Interop.Excel.ApplicationClass. This class basically launches excel.exe through InprocServer32. If you don't have it installed then it will return the error message you received above.
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
Personally everything that is based uppon Eclipse or NetBeans is an overkill, the GUI is crap and the performance is soooo slow compared to other alternatives.
If you're willing to pay I would suggest Zend IDE (version 5.5, not 6 because it's based on Eclipse) and EditPlus for a more lightweight yet powerfull code editor.
If you're looking for free alternatives, or if you code in other languages other than PHP, OpenKomodo is a really nice IDE with almost all the features (no SVN neither CVS) that you require, the only con I see about OpenKomodo is that sometimes it messes my code indentation, but then again I don't use it on a very regular basis.
As for a free lightweight alternative: Notepad++. =)
@EboMike: I didn't know that Resources.getIdentifier()
existed.
In my projects I used the following code to do that:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
It would be used like this for getting the value of R.drawable.icon
resource integer value
int resID = getResId("icon", R.drawable.class); // or other resource class
I just found a blog post saying that Resources.getIdentifier()
is slower than using reflection like I did. Check it out.
It sounds like Maven is using the JRE, not the JDK. Perhaps you installed Maven before installing the JDK?
Check the settings files. There are three in total, system, user, and project. It's most likely in the installation configuration ($M2_HOME/conf/settings.xml) or, possibly, the per-user configuration (${user.dir}/.m2/settings.xml).
CREATE OR REPLACE PROCEDURE ADDEMP
(xml IN CLOB)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
SELECT
ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
FROM TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;
COMMIT;
END;
This solution does not require jQuery.
const RADIO_NAME = "radioName";
const radios = Array.from(document.getElementsByName(RADIO_NAME));
const checkedRadio = radios.filter(e=>e.checked);
This uses jQuery:
const radios = Array.from($(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked);
jQuery adds an extra layer of abstraction that isn't needed here.
You could also use:
const radios = Array.from(document.querySelectorAll(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked)[0];
But getElementsByName
is simple and clear enough.
I had a similar issue, but it was related to the element not being visible in the viewport. I took a screenshot and realized the browser window was too narrow and the element couldn't be seen. I did one of these and it worked:
driver.maximize_window()
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
a simple way to do this:
try {
list.get( index );
}
catch ( IndexOutOfBoundsException e ) {
if(list.isEmpty() || index >= list.size()){
// Adding new item to list.
}
}
if your SQL query is this
SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'
then rawQuery will be
String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"}
db.rawQuery(query, selectionArgs);
As usual in Angular, you can rely on dependency injection:
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Add DatePipe
to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe
:
providers: [DatePipe,...]
Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate
function directly.
import { formatDate } from '@angular/common';
class MyService {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'yyyy-MM-dd', this.locale);
}
}
Before Angular 5: Be warned though that the DatePipe
was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).
If you're using older Angular versions, you should add the Intl
polyfill to your project to avoid any problem.
See this related question for a more detailed answer.
The best way is using the transparent color code
android:background="#00000000"
use the color code #00000000 for making any thing transparent
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
Just set the body as the following
var reqBody = "username="+username+"&password="+password+"&grant_type=password";
then
fetch('url', {
method: 'POST',
headers: {
//'Authorization': 'Bearer token',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: reqBody
}).then((response) => response.json())
.then((responseData) => {
console.log(JSON.stringify(responseData));
}).catch(err=>{console.log(err)})
Dir.new('/home/user/foldername').each { |file| puts file }
UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.
Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.
You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.
You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
To see of the curent time is greater or equal to 14:08:10 do this:
if (time() >= strtotime("14:08:10")) {
echo "ok";
}
Depending on your input sources, make sure to account for timezone.
See PHP time() and PHP strtotime()
I use TortoiseMerge, which is included in TortoiseSVN program
And we have talked about File Diff tools in this thread, not dedicated to XML though
https://stackoverflow.com/questions/1830962/file-differencing-software-on-windows
The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.
Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator *
- it always matches the longest possible string.
The trick then is to limit what it's allowed to match in the first place. Instead of .*
you seem to be looking for
[^>]*
which still matches as many of something as possible; but the something is not just .
"any character", but instead "any character which isn't >
".
Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.
Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.
For example, a regular expression with a trailing context after the wildcard like .*?><br/>
will jump over any nested >
until it finds the trailing context (here, ><br/>
) even if that requires straddling multiple >
instances and newlines if you let it, where [^>]*><br/>
(or even [^\n>]*><br/>
if you have to explicitly disallow newline) obviously can't and won't do that.
Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">
, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.
The 2 domains mydomain.com
and subdomain.mydomain.com
can only share cookies if the domain is explicitly named in the Set-Cookie
header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)
For instance, if you sent the following header from subdomain.mydomain.com
, then the cookie won't be sent for requests to mydomain.com
:
Set-Cookie: name=value
However if you use the following, it will be usable on both domains:
Set-Cookie: name=value; domain=mydomain.com
This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com
.
In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com
) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).
However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.
In summary, if you set a cookie like the second example above from mydomain.com
, it would be accessible by subdomain.mydomain.com
, and vice versa. This can also be used to allow sub1.mydomain.com
and sub2.mydomain.com
to share cookies.
See also:
It sounds like you need to make use of advanced where clauses.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
Try this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
Same problem here when using <button onclick="">submit</button>
. Then solved by using <input type="button" onclick="">
I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[@name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')
As you probably use a drawable selector for your android:button
property you need to add android:constantSize="true"
and/or specify a default drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize="true">
<item android:drawable="@drawable/check_on" android:state_checked="true"/>
<item android:drawable="@drawable/check_off"/>
</selector>
After that you need to specify android:paddingLeft
attribute in your checkbox xml.
Cons:
In the layout editor you will the text going under the checkbox with api 16 and below, in that case you can fix it by creating you custom checkbox class like suggested but for api level 16.
Rationale:
it is a bug as StateListDrawable#getIntrinsicWidth()
call is used internally in CompoundButton
but it may return < 0
value if there is no current state and no constant size is used.
As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.
Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.
A possible solution is to wrap the static in a proxy with an interface which can be mocked
public interface IFileProxy {
void Delete(string path);
}
public class FileProxy : IFileProxy {
public void Delete(string path) {
System.IO.File.Delete(path);
}
}
public class MyClass {
private IFileProxy _fileProxy;
public MyClass(IFileProxy fileProxy) {
_fileProxy = fileProxy;
}
public void DoSomethingAndDeleteFile(string path) {
// Do Something with file
// ...
// Delete
System.IO.File.Delete(path);
}
public void DoSomethingAndDeleteFileUsingProxy(string path) {
// Do Something with file
// ...
// Delete
_fileProxy.Delete(path);
}
}
The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)
Another possibility is to have a 'static proxy' with different implementations of the interface behind it
public static class FileServices {
static FileServices() {
Reset();
}
internal static IFileProxy FileProxy { private get; set; }
public static void Reset(){
FileProxy = new FileProxy();
}
public static void Delete(string path) {
FileProxy.Delete(path);
}
}
Our method now becomes
public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
// Do Something with file
// ...
// Delete
FileServices.Delete(path);
}
For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).
Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...
I know this doesn't address the exact case of the OP, but for others coming from Google don't forget to try display: block;
based on the element type. I had the image in an <i>
, but it wasn't appearing...
A lot of the solutions offered here do not seem to work anymore. I'm currently on a chromebook and wanted to view an HTML5 banner. This seems impossible now through Google Drive or other apps (as mentioned in previous comments).
The method I ended up using to view the HTML5 was the following:
There may well an easier way, but this way is pretty good too. Hope it helps and worked well for me.
Another reason for this error could be incorrect or non-existent database name.
Forcing the TCP/IP connection (by providing 127.0.0.1
instead of localhost
or .
) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.
So, here is the checklist:
I have defined this function:
function format() {
var args = arguments;
if (args.length <= 1) {
return args;
}
var result = args[0];
for (var i = 1; i < args.length; i++) {
result = result.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), args[i]);
}
return result;
}
And can be called like c#:
var text = format("hello {0}, your age is {1}.", "John", 29);
Result:
hello John, your age is 29.
for Kotlin users:
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
// do your logic
}
}
there are a lot of methods that you can override though
In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.
/workspace/android-support-v7-appcompat
being a common one.
In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.
To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.
<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>
That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
}
Fast and clean way using LINQ
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
verified on VS2013
None of the answers so far explains how to download the various variants of that font so that you can serve them from your own website (WWW server).
While this might seem like a minor issue from the technical perspective, it is a big issue from the legal perspective, at least if you intend to present your pages to any EU citizen (or even, if you do that by accident). This is even true for companies which reside in the US (or any country outside the EU).
If anybody is interested why this is, I'll update this answer and give some more details here, but at the moment, I don't want to waste too much space off-topic.
Having said this:
I've downloaded all versions (regular, outlined, rounded, sharp, two-tone) of that font following two very easy steps (it was @Aj334's answer to his own question which put me on the right track) (example: "outlined" variant):
Get the CSS from the Google CDN by directly letting your browser fetch the CSS URL, i.e. copy the following URL into your browser's location bar:
https://fonts.googleapis.com/css?family=Material+Icons+Outlined
This will return a page which looks like this (at least in Firefox 70.0.1 at the time of writing this):
/* fallback */
@font-face {
font-family: 'Material Icons Outlined';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2) format('woff2');
}
.material-icons-outlined {
font-family: 'Material Icons Outlined';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-moz-font-feature-settings: 'liga';
-moz-osx-font-smoothing: grayscale;
}
Find the line starting with src:
in the above code, and let your browser fetch the URL contained in that line, i.e. copy the following URL into your browser's location bar:
https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2
Now the browser will download that .woff2
file and offer to save it locally (at least, Firefox did).
Two final remarks:
Of course, you can download the other variants of that font using the same method. In the first step, just replace the character sequence Outlined
in the URL by the character sequences Round
(yes, really, although here it's called "Rounded" in the left navigation menu), Sharp
or Two+Tone
, respectively. The result page will look nearly the same each time, but the URL in the src:
line of course is different for each variant.
Finally, in step 1, you even can use that URL:
https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp
This will return the CSS for all variants in one page, which then contains five src:
lines, each one with another URL designating where the respective font is located.
just go into XML file and give id to your webView then in java paste these line:
public class Main extends Activity {
private WebView mWebview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_layout_file_name);
mWebview = (WebView)findViewById(R.id.id_you_gave _to_your_wenview_in_xml);
mWebview.loadUrl("http://www.google.com");
}
}
From Ubuntu 18.4 (Bionic Beaver) it is advisable to use apt instead of apt-get since it has much better structural form.
sudo apt install libxml2-dev libxslt1-dev python-dev
If you're happy with a possibly older version of lxml
altogether though, you could try
sudo apt install python-lxml
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, lims=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (xmin, xmax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
if lims is None:
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, lims=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (ymin, ymax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
if lims is None:
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
Ok, call me paranoid but I suggest:
final android.view.ViewParent parent = view.getParent ();
if (parent instanceof android.view.ViewManager)
{
final android.view.ViewManager viewManager = (android.view.ViewManager) parent;
viewManager.removeView (view);
} // if
casting without instanceof
just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView
is part of the ViewManager
interface. And one should not cast to a concrete class when a perfectly suitable interface is available.
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
When you do : f.readlines()
you already read all the file so f.tell()
will show you that you are in the end of the file, and doing f.next()
will result in a StopIteration
error.
Alternative of what you want to do is:
filne = "D:/testtube/testdkanimfilternode.txt"
with open(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a
# StopIteration if the last line is also a match.
break
like so:
long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };
var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
Console.Write(String.Format("{0}\t", arr[row,col]));
Console.WriteLine();
}
Using Bash Parameter Expansion:
orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:
SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',')
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;
In registration/login.html
(nested within templates
folder) if you insert the following line, the page will render like Django's original admin login page:
{% include "admin/login.html" %}
Note: The file should contain above lines only.
I would also vote for Mosty Mostacho's solution with minor modification to his query code:
SELECT a.i, a.j, (
SELECT count(*) from test b where a.j >= b.j AND a.i = b.i
) AS row_number FROM test a
Which will give the same result:
+------+------+------------+
| i | j | row_number |
+------+------+------------+
| 1 | 11 | 1 |
| 1 | 12 | 2 |
| 1 | 13 | 3 |
| 2 | 21 | 1 |
| 2 | 22 | 2 |
| 2 | 23 | 3 |
| 3 | 31 | 1 |
| 3 | 32 | 2 |
| 3 | 33 | 3 |
| 4 | 14 | 1 |
+------+------+------------+
for the table:
+------+------+
| i | j |
+------+------+
| 1 | 11 |
| 1 | 12 |
| 1 | 13 |
| 2 | 21 |
| 2 | 22 |
| 2 | 23 |
| 3 | 31 |
| 3 | 32 |
| 3 | 33 |
| 4 | 14 |
+------+------+
With the only difference that the query doesn't use JOIN and GROUP BY, relying on nested select instead.
It's worth mentioning the -p
flag here ("p" for pretend).
If you add this to the command it will simply do a "test" run and show you what files will be deleted without actually deleting them.
$ rails d controller welcome -p
remove app/controllers/welcome_controller.rb
invoke erb
remove app/views/welcome
invoke test_unit
remove test/controllers/welcome_controller_test.rb
invoke helper
remove app/helpers/welcome_helper.rb
invoke test_unit
remove test/helpers/welcome_helper_test.rb
invoke assets
invoke coffee
remove app/assets/javascripts/welcome.js.coffee
invoke scss
remove app/assets/stylesheets/welcome.css.scss
If you're happy with it, run the command again without the -p
flag.
The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:
entry: {
outputone: './source/fileone.jsx',
outputtwo: './source/filetwo.jsx'
},
output: {
path: path.resolve(__dirname, './wwwroot/js/dist'),
filename: '[name].js'
},
This will generate 2 files: outputone.js und outputtwo.js in the target folder.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:index.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
what's wrong with:
int myInt = myFloat;
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)
The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.
-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees
DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;
DECLARE @PageDetails TABLE
(
<<IdentityColumn of Table>> int,
rownum int,
[PageNumber] int
)
INSERT INTO @PageDetails values(0, 0, 0)
;WITH CTE AS
(
SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
)
Insert into @PageDetails
SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0
--SELECT * FROM @PageDetails
-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>
I have written my own that you can use. This one works has sqlite, is thread safe and is in C++ for UNIX.
You should be able to pick it apart and use the C compatible code.
try with shortcutjs.bat to create a shortcut:
call shortcutjs.bat -linkfile mybat3.lnk -target "%cd%\Ascii2All.bat" -iconlocation "%SystemRoot%\System32\SHELL32.dll,77"
you can use the -iconlocation switch to point to a icon .
$(document).ready(function() {_x000D_
$('#YourID option[value="3"]').attr("selected", "selected");_x000D_
$('#YourID option:selected').attr("selected",null);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
<option value="1">A</option>_x000D_
<option value="2">B</option>_x000D_
<option value="3">C</option>_x000D_
<option value="4">D</option>_x000D_
</select>
_x000D_
I came across the same issue as well. Not sure why this is working but it indeed works: Try add ENGINE INNODB after your create query.
mysql> create table course
-> (course_id varchar(7),
-> title varchar (50),
-> dept_name varchar(20),
-> credits numeric(2,0),
-> primary key(course_id),
-> foreign key (dept_name) references department) ENGINE INNODB;
Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.
ie:
IF(@Trans_type = 'subscr_signup')
set @tmpType = 'premium'
ELSE iF(@Trans_type = 'subscr_cancel')
set @tmpType = 'basic'
If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:
#logo { float: left; margin: 0 10px 10px 20px; } #content { margin: 10px 0 0 10px; }
or whatever margin you want.
The file .bashrc
is read when you start an interactive shell. This is the file that you should update. E.g:
export PATH=$PATH:/opt/ActiveTcl-8.5/bin
Restart the shell for the changes to take effect or source it, i.e.:
source .bashrc
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
Sorry if I've missed the point, but wouldn't the following do what you want on it's own?
SELECT distinct idCustomer FROM reservations
WHERE DATEPART(hour, insertDate) >= 2
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
Try these:
window.location.href = 'http://www.google.com';
window.location.assign("http://www.w3schools.com");
window.location = 'http://www.google.com';
For more see this link: other ways to reload the page with JavaScript
Assuming you must have two tables for the two employee types for some reason, I'll extend on vmarquez's answer:
Schema:
employees_ce (id, name)
employees_sn (id, name)
deductions (id, parentId, parentType, name)
Data in deductions:
deductions table
id parentId parentType name
1 1 ce gold
2 1 sn silver
3 2 sn wood
...
This would allow you to have deductions point to any other table in your schema. This kind of relation isn't supported by database-level constraints, IIRC so you'll have to make sure your App manages the constraint properly (which makes it more cumbersome if you have several different Apps/services hitting the same database).
You can change Apaches httpd.conf by clicking (in xampp control panel) apache/conf/httpd.conf
and adjust the entries for DocumentRoot
and the corresponding Directory
entry.
Just Ctrl+F for "htdocs" and change the entries to your new path.
See screenshot:
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">