I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
On Ubuntu 18.04 , I tried a trick that I used to reactivate the file watching by ionic/node, and it works also here. This could be useful for those who don't have access to system conf files.
CHOKIDAR_USEPOLLING=1 npm start
$ mkdir <YOURPROJECT>
Create a new project
$ cd <YOURPROJECT>
Change directory to that project
$ virtualenv <NEWVIRTUALENV>
Creating new virtualenv
$ source <NEWVIRTUALENV>/bin/activate
Activating that new virtualenv
One of the alternatives to Python's conditional expression
"yes" if boolean else "no"
is the following:
{True:"yes", False:"no"}[boolean]
which has the following nice extension:
{True:"yes", False:"no", None:"maybe"}[boolean_or_none]
The shortest alternative remains:
("no", "yes")[boolean]
but there is no alternative to
yes() if boolean else no()
if you want to avoid the evaluation of yes()
and no()
, because in
(no(), yes())[boolean] # bad
both no()
and yes()
are evaluated.
You can try this:
on Server:
adding new group to /etc/group
like
(example)
mygroup:1001:michael,nir
create new git repository:
mkdir /srv/git
cd /srv/git
mkdir project_dir
cd project_dir
git --bare init (initial git repository )
chgrp -R mygroup objects/ refs/ (change owner of directory )
chmod -R g+w objects/ refs/ (give permission write)
on Client:
mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master
(Thanks Josh Lindsey for client side)
after Client, do on Server this commands:
cd /srv/git/project_dir
chmod -R g+w objects/ refs/
If got this error after git pull:
There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream new origin/<branch>
try:
git push -u origin master
It will help.
The characters are exactly as documented - \b
equates to a character code of 0x08
and \r
equates to 0x0d
. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
Union type is in my mind best option in this case:
interface Employee{
id: number;
name: string;
salary: number | null;
}
// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };
EDIT : For this to work as expected, you should enable the strictNullChecks
in tsconfig
.
The plain javascript code sample which answers your question literally:
return location.search.indexOf('q=')>=0;
The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:
var queryString=location.search;
var params=queryString.substring(1).split('&');
for(var i=0; i<params.length; i++){
var pair=params[i].split('=');
if(decodeURIComponent(pair[0])=='q' && pair[1])
return true;
}
return false;
This library works like a charm, easy to integrate and use. https://github.com/dm77/barcodescanner
This solution worked to me:
<summary>Tootsie roll tiramisu macaroon wafer carrot cake. 
Danish topping sugar plum tart bonbon caramels cake.</summary>
You will have the text in two lines.
This worked to me using the XmlReader.Read method.
Just incase you are working with a FirebaseRecyclerAdapter this post works as a charm https://stackoverflow.com/a/39058636/6507009
I've found the proper way to return XML to a client in ASP.NET. I think if I point out the wrong ways, it will make the right way more understandable.
Incorrect:
Response.Write(doc.ToString());
Incorrect:
Response.Write(doc.InnerXml);
Incorrect:
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.OutputStream);
Correct:
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
//using the encoding of the text-writer
//(which comes from response.contentEncoding)
Do not use Response.OutputStream
Do use Response.Output
Both are streams, but Output
is a TextWriter. When an XmlDocument
saves itself to a TextWriter, it will use the encoding specified by that TextWriter. The XmlDocument will automatically change the xml declaration node to match the encoding used by the TextWriter. e.g. in this case the XML declaration node:
<?xml version="1.0" encoding="ISO-8859-1"?>
would become
<?xml version="1.0" encoding="UTF-8"?>
This is because the TextWriter has been set to UTF-8. (More on this in a moment). As the TextWriter is fed character data, it will encode it with the byte sequences appropriate for its set encoding.
Incorrect:
doc.Save(Response.OutputStream);
In this example the document is incorrectly saved to the OutputStream, which performs no encoding change, and may not match the response's content-encoding or the XML declaration node's specified encoding.
Correct
doc.Save(Response.Output);
The XML document is correctly saved to a TextWriter object, ensuring the encoding is properly handled.
The encoding given to the client in the header:
Response.ContentEncoding = ...
must match the XML document's encoding:
<?xml version="1.0" encoding="..."?>
must match the actual encoding present in the byte sequences sent to the client. To make all three of these things agree, set the single line:
Response.ContentEncoding = System.Text.Encoding.UTF8;
When the encoding is set on the Response object, it sets the same encoding on the TextWriter. The encoding set of the TextWriter causes the XmlDocument to change the xml declaration:
<?xml version="1.0" encoding="UTF-8"?>
when the document is Saved:
doc.Save(someTextWriter);
You do not want to save the document to a binary stream, or write a string:
Incorrect:
doc.Save(Response.OutputStream);
Here the XML is incorrectly saved to a binary stream. The final byte encoding sequence won't match the XML declaration, or the web-server response's content-encoding.
Incorrect:
Response.Write(doc.ToString());
Response.Write(doc.InnerXml);
Here the XML is incorrectly converted to a string, which does not have an encoding. The XML declaration node is not updated to reflect the encoding of the response, and the response is not properly encoded to match the response's encoding. Also, storing the XML in an intermediate string wastes memory.
You don't want to save the XML to a string, or stuff the XML into a string and response.Write
a string, because that:
- doesn't follow the encoding specified
- doesn't set the XML declaration node to match
- wastes memory
Do use doc.Save(Response.Output);
Do not use doc.Save(Response.OutputStream);
Do not use Response.Write(doc.ToString());
Do not use 'Response.Write(doc.InnerXml);`
The Response's ContentType must be set to "text/xml"
. If not, the client will not know you are sending it XML.
Response.Clear(); //Optional: if we've sent anything before
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
//using the encoding of the text-writer
//(which comes from response.contentEncoding)
Response.End(); //Optional: will end processing
Rob Kennedy had the good point that I failed to include the start-to-finish example.
GetPatronInformation.ashx:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Xml;
using System.IO;
using System.Data.Common;
//Why a "Handler" and not a full ASP.NET form?
//Because many people online critisized my original solution
//that involved the aspx (and cutting out all the HTML in the front file),
//noting the overhead of a full viewstate build-up/tear-down and processing,
//when it's not a web-form at all. (It's a pure processing.)
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//GetXmlToShow will look for parameters from the context
XmlDocument doc = GetXmlToShow(context);
//Don't forget to set a valid xml type.
//If you leave the default "text/html", the browser will refuse to display it correctly
context.Response.ContentType = "text/xml";
//We'd like UTF-8.
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
//context.Response.ContentEncoding = System.Text.Encoding.UnicodeEncoding; //But no reason you couldn't use UTF-16:
//context.Response.ContentEncoding = System.Text.Encoding.UTF32; //Or UTF-32
//context.Response.ContentEncoding = new System.Text.Encoding(500); //Or EBCDIC (500 is the code page for IBM EBCDIC International)
//context.Response.ContentEncoding = System.Text.Encoding.ASCII; //Or ASCII
//context.Response.ContentEncoding = new System.Text.Encoding(28591); //Or ISO8859-1
//context.Response.ContentEncoding = new System.Text.Encoding(1252); //Or Windows-1252 (a version of ISO8859-1, but with 18 useful characters where they were empty spaces)
//Tell the client don't cache it (it's too volatile)
//Commenting out NoCache allows the browser to cache the results (so they can view the XML source)
//But leaves the possiblity that the browser might not request a fresh copy
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//And now we tell the browser that it expires immediately, and the cached copy you have should be refreshed
context.Response.Expires = -1;
context.Response.Cache.SetAllowResponseInBrowserHistory(true); //"works around an Internet Explorer bug"
doc.Save(context.Response.Output); //doc saves itself to the textwriter, using the encoding of the text-writer (which comes from response.contentEncoding)
#region Notes
/*
* 1. Use Response.Output, and NOT Response.OutputStream.
* Both are streams, but Output is a TextWriter.
* When an XmlDocument saves itself to a TextWriter, it will use the encoding
* specified by the TextWriter. The XmlDocument will automatically change any
* XML declaration node, i.e.:
* <?xml version="1.0" encoding="ISO-8859-1"?>
* to match the encoding used by the Response.Output's encoding setting
* 2. The Response.Output TextWriter's encoding settings comes from the
* Response.ContentEncoding value.
* 3. Use doc.Save, not Response.Write(doc.ToString()) or Response.Write(doc.InnerXml)
* 3. You DON'T want to save the XML to a string, or stuff the XML into a string
* and response.Write that, because that
* - doesn't follow the encoding specified
* - wastes memory
*
* To sum up: by Saving to a TextWriter: the XML Declaration node, the XML contents,
* and the HTML Response content-encoding will all match.
*/
#endregion Notes
}
private XmlDocument GetXmlToShow(HttpContext context)
{
//Use context.Request to get the account number they want to return
//GET /GetPatronInformation.ashx?accountNumber=619
//Or since this is sample code, pull XML out of your rear:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Patron><Name>Rob Kennedy</Name></Patron>");
return doc;
}
public bool IsReusable { get { return false; } }
}
For chart.js V2 (beta), use:
var options = {
scales: {
yAxes: [{
display: true,
ticks: {
suggestedMin: 0, // minimum will be 0, unless there is a lower value.
// OR //
beginAtZero: true // minimum value will be 0.
}
}]
}
};
See chart.js documentation on linear axes configuration for more details.
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
public enum MyEnum
{
ONE(1),
TWO(2);
private int value;
private MyEnum(int val){
value = val;
}
public int getValue(){
return value;
}
}
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
While you can call exit()
(and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main()
:
int main()
{
// do whatever your program does
} // function returns and exits program
When you call exit()
, objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.
When I received this error I believe it was a bug, however you should keep in mind that if you do a separate query with a SELECT statement and the same WHERE clause, then you can grab the primary ID's from that SELECT: SELECT CONCAT(primary_id, ',')
) statement and insert them into the failed UPDATE query with conditions -> "WHERE [primary_id] IN ([list of comma-separated primary ID's from the SELECT statement)" which allows you to alleviate any issues being caused by the original (failed) query's WHERE clause.
For me, personally, when I was using quotes for the values in the "WHERE ____ IN ([values here])", only 10 of the 300 expected entries were being affected which, in my opinion, seems like a bug.
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.
How many types do you plan to deal with?
UPDATE:
If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):
package generics;
public interface XmlGenerator<T>
{
String getXml(T value);
}
And the concrete implementation XmlGeneratorImpl:
package generics;
public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
private Class<T> valueType;
private static final int DEFAULT_CAPACITY = 1024;
public static void main(String [] args)
{
Integer x = 42;
String y = "foobar";
XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);
System.out.println("integer: " + intXmlGenerator.getXml(x));
System.out.println("string : " + stringXmlGenerator.getXml(y));
}
public XmlGeneratorImpl(Class<T> clazz)
{
this.valueType = clazz;
}
public String getXml(T value)
{
StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);
appendTag(builder);
builder.append(value);
appendTag(builder, false);
return builder.toString();
}
private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }
private void appendTag(StringBuilder builder, boolean isClosing)
{
String valueTypeName = valueType.getName();
builder.append("<").append(valueTypeName);
if (isClosing)
{
builder.append("/");
}
builder.append(">");
}
}
If I run this, I get the following result:
integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>
I don't know if this is what you had in mind.
The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.
The second one corresponds to a lifecycle hook of Angular2 components:
Quoted from official angular's website:
ngOnChanges
is called when an input or output binding value changesngOnInit
is called after the firstngOnChanges
So you should use ngOnInit
if initialization processing relies on bindings of the component (for example component parameters defined with @Input
), otherwise the constructor would be enough...
you can compile the ui files like this
pyuic4 -x helloworld.ui -o helloworld.py
Adding the why this occurs and more possible cause. A lot of interfaces still do not understand ES6 Javascript syntax/features, hence there is need for Es6 to be compiled to ES5 whenever it is used in any file or project. The possible reasons for the SyntaxError: Cannot use import statement outside a module
error is you are trying to run the file independently, you are yet to install and set up an Es6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file. If you will want to continue without a compiler the best possible solution is to use ES5 syntax which in your case would be var ms = require(./ms.js);
this can later be updated as appropriate or better still setup your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.
self.navigationController.isMovingFromParentViewController is not working anymore on iOS8 and 9 I use :
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (self.navigationController.topViewController != self)
{
// Is Popping
}
}
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
f = open(file_to_open)
print(f.read())
You could refer to column alias but you need to define it using CROSS/OUTER APPLY
:
SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;
Pros:
WHERE/GROUP BY/ORDER BY
The official csv
documentation recommends open
ing the file with newline=''
on all platforms to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
...
The CSV writer terminates each line with the lineterminator
of the dialect, which is \r\n
for the default excel
dialect on all platforms.
On Windows, always open your files in binary mode ("rb"
or "wb"
), before passing them to csv.reader
or csv.writer
.
Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n
separating records. If that separator is written in text mode, the Python runtime replaces the \n
with \r\n
, hence the \r\r\n
observed in the file.
See this previous answer.
If you happen to use CRA with default yarn
package manager use the following. Worked for me.
yarn remove node-sass
yarn add [email protected]
Adding one more code with decode and encode for reference
import base64
def encode(key, string):
encoded_chars = []
for i in range(len(string)):
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) + ord(key_c) % 128)
encoded_chars.append(encoded_c)
encoded_string = "".join(encoded_chars)
arr2 = bytes(encoded_string, 'utf-8')
return base64.urlsafe_b64encode(arr2)
def decode(key, string):
encoded_chars = []
string = base64.urlsafe_b64decode(string)
string = string.decode('utf-8')
for i in range(len(string)):
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) - ord(key_c) % 128)
encoded_chars.append(encoded_c)
encoded_string = "".join(encoded_chars)
return encoded_string
def main():
answer = str(input("EorD"))
if(answer in ['E']):
#ENCODE
file = open("D:\enc.txt")
line = file.read().replace("\n", " NEWLINEHERE ")
file.close()
text = encode("4114458",line)
fnew = open("D:\\new.txt","w+")
fnew.write(text.decode('utf-8'))
fnew.close()
else:
#DECODE
file = open("D:\\new.txt",'r+')
eline = file.read().replace("NEWLINEHERE","\n")
file.close()
print(eline)
eline = eline.encode('utf-8')
dtext=decode("4114458",eline)
print(dtext)
fnew = open("D:\\newde.txt","w+")
fnew.write(dtext)
fnew.close
if __name__ == '__main__':
main()
The Best way to wait without freezing your main thread is using the Task.Delay function.
So your code will look like this
var t = Task.Run(async delegate
{
dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
dataGridView1.Refresh();
await Task.Delay(1000);
});
This is how I do it without any js.
I used the icon glyphicon-triangle-right but it works with any other icon, what it does is that it applies a 90 degrees rotation to the icon when the panel is open or not. I'm using Bootstrap 3.3.5 for this one.
CSS Code
h4.panel-title a {
display: block;
}
h4.panel-title a.collapsed .glyphicon-triangle-right {
color: #ada9a9 !important;
transform: rotate(0deg);
}
h4.panel-title a .glyphicon-triangle-right {
color: #515e64 !important;
transform: rotate(90deg);
}
This is the HTML structure taken from the Bootstrap example
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Proven Expertise
<span class="glyphicon glyphicon-triangle-right pull-right" aria-hidden="true"></span>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
</div>
You asked for differences, but you can’t quite compare those two.
Note that <meta http-equiv="content-language" content="es">
is obsolete and removed in HTML5. It was used to specify “a document-wide default language”, with its http-equiv
attribute making it a pragma directive (which simulates an HTTP response header like Content-Language
that hasn’t been sent from the server, since it cannot override a real one).
Regarding <meta name="language" content="Spanish">
, you hardly find any reliable information. It’s non-standard and was probably invented as a SEO makeshift.
However, the HTML5 W3C Recommendation encourages authors to use the lang
attribute on html
root elements (attribute values must be valid BCP 47 language tags):
<!DOCTYPE html>
<html lang="es-ES">
<head>
…
Anyway, if you want to specify the content language to instruct search engine robots, you should consider this quote from Google Search Console Help on multilingual sites:
Google uses only the visible content of your page to determine its language. We don’t use any code-level language information such as
lang
attributes.
head or tail can do it as well:
head -c X
Prints the first X bytes (not necessarily characters if it's a UTF-16 file) of the file. tail will do the same, except for the last X bytes.
This (and cut) are portable.
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
You would probably also want this:
import sys
print(sys.path)
Or as a one liner from the terminal:
python -c "import sys; print('\n'.join(sys.path))"
Caveat: If you have multiple versions of Python installed you should use a corresponding command python2
or python3
.
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
If you just want to run some code when an element becomes visible in the viewport:
function onVisible(element, callback) {
new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.intersectionRatio > 0) {
callback(element);
observer.disconnect();
}
});
}).observe(element);
}
When the element has become visible the intersection observer calls callback
and then destroys itself with .disconnect()
.
Use it like this:
onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));
Update 2018...
card
has replaced the well
.
Bootstrap 4
<div class="card card-body bg-light">
Well
</div>
or, as two DIVs...
<div class="card bg-light">
<div class="card-body">
...
</div>
</div>
(Note: in Bootstrap 4 Alpha, these were known as card-block
instead of card-body
and bg-faded
instead of bg-light
)
The compiler warnings happen on stderr
, not stdout
, which is why you don't see them when you just redirect make
somewhere else. Instead, try this if you're using Bash:
$ make &> results.txt
The &
means "redirect stdout and stderr to this location". Other shells often have similar constructs.
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
This worked for me. Special thanks to all the posts above. This should return a collection of all your models.
models = []
Dir.glob("#{Rails.root}/app/models/**/*.rb") do |model_path|
temp = model_path.split(/\/models\//)
models.push temp.last.gsub(/\.rb$/, '').camelize.constantize rescue nil
end
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int @this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST
:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);
If you want to check if provided domain from email address is valid, use something like:
/*
* Check for valid MX record for given email domain
*/
if(!function_exists('check_email_domain')){
function check_email_domain($email) {
//Get host name from email and check if it is valid
$email_host = explode("@", $email);
//Add a dot to the end of the host name to make a fully qualified domain name and get last array element because an escaped @ is allowed in the local part (RFC 5322)
$host = end($email_host) . ".";
//Convert to ascii (http://us.php.net/manual/en/function.idn-to-ascii.php)
return checkdnsrr(idn_to_ascii($host), "MX"); //(bool)
}
}
This is handy way to filter a lot of invalid email addresses, along with standart email validation, because valid email format does not mean valid email.
Note that idn_to_ascii()
(or his sister function idn_to_utf8()
) function may not be available in your PHP installation, it requires extensions PECL intl >= 1.0.2 and PECL idn >= 0.1.
Also keep in mind that IPv4 or IPv6 as domain part in email (for example user@[IPv6:2001:db8::1]
) cannot be validated, only named hosts can.
See more here.
There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md
An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole
First of all, if you want to use HTML inside the content you need to set the HTML option to true:
$('.danger').popover({ html : true});
Then you have two options to set the content for a Popover
Using data-content: You need to escape the HTML content, something like this:
<a class='danger' data-placement='above'
data-content="<div>This is your div content</div>"
title="Title" href='#'>Click</a>
You can either escape the HTML manually or use a function. I don't know about PHP but in Rails we use *html_safe*.
Using a JS function: If you do this, you have several options. The easiest I think is to put your div content hidden wherever you want and then write a function to pass its content to popover. Something like this:
$(document).ready(function(){
$('.danger').popover({
html : true,
content: function() {
return $('#popover_content_wrapper').html();
}
});
});
And then your HTML looks like this:
<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_content_wrapper" style="display: none">
<div>This is your div content</div>
</div>
Hope it helps!
PS: I've had some troubles when using popover and not setting the title attribute... so, remember to always set the title.
This applies to all languages:
You want to have an event/listener model. You create a listener to wait for a particular event. The event would be created (or signaled) in your worker thread. This will block the thread until the signal is received instead of constantly polling to see if a condition is met, like the solution you currently have.
Your situation is one of the most common causes for deadlocks- make sure you signal the other thread regardless of errors that may have occurred. Example- if your application throws an exception- and never calls the method to signal the other that things have completed. This will make it so the other thread never 'wakes up'.
I suggest that you look into the concepts of using events and event handlers to better understand this paradigm before implementing your case.
Alternatively you can use a blocking function call using a mutex- which will cause the thread to wait for the resource to be free. To do this you need good thread synchronization- such as:
Thread-A Locks lock-a
Run thread-B
Thread-B waits for lock-a
Thread-A unlocks lock-a (causing Thread-B to continue)
Thread-A waits for lock-b
Thread-B completes and unlocks lock-b
You can use the environment variable NUMBER_OF_PROCESSORS
for the total number of processors:
echo %NUMBER_OF_PROCESSORS%
I would recommend using MyBatis. It is a thin layer on top of JDBC, it is very easy to map objects to tables and still use plain SQL, everything is under your control.
By mysql 8 and later version, you cannot add a user by granting privileges. it means with this query:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
IDENTIFIED BY 'type-root-password-here'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
mysql will return this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'written password' at line 1
this means you don't have a root user for % domain. so you need to first insert the user and then grant privileges like this:
mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'your password';
Query OK, 0 rows affected (0.11 sec)
mysql> GRANT ALL ON *.* TO 'root'@'%';
Query OK, 0 rows affected (0.15 sec)
mysql> FLUSH PRIVILEGES;
Dont forget to replace passwords with your specific passwords.
I found two links of performance compare among several ways of converting string
to int
.
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
A couple of distinctions that weren't touched on here:
Compare:
exec('ls', $out);
var_dump($out);
// Look an array
$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it
Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you'll need to post-process the input into some other form, so in that case use shell_exec.
It's also worth pointing out that shell_exec is an alias for the backtic operator, for those used to *nix.
$out = `ls`;
var_dump($out);
exec also supports an additional parameter that will provide the return code from the executed command:
exec('ls', $out, $status);
if (0 === $status) {
var_dump($out);
} else {
echo "Command failed with status: $status";
}
As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec.
This solution meets the following criteria
As far as I'm aware, this criteria cannot be met without Javascript (unfortunately).
This solution uses jQuery, but could also be easily converted to vanilla JS:
function fixedHeader(){_x000D_
$(this).width($("#wrapper").width());_x000D_
$("#header-filler").height($("#header-fixed").outerHeight());_x000D_
}_x000D_
_x000D_
$(window).resize(function() {_x000D_
fixedHeader();_x000D_
});_x000D_
_x000D_
fixedHeader();
_x000D_
#header-fixed{_x000D_
position: fixed;_x000D_
background-color: white;_x000D_
top: 0;_x000D_
}_x000D_
#header-filler{_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="wrapper">_x000D_
<div id="header-fixed">_x000D_
This is a nifty header! works even when resizing the window causing a line break_x000D_
</div>_x000D_
<div id="header-filler"></div>_x000D_
_x000D_
[start fluff]<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
[end fluff]_x000D_
_x000D_
</div>
_x000D_
class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}
To connect to a new server, you click on home + add new connection. Put IP or webserver URL in new connection.
Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).
As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.
Using the ping
method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.
You should be pinging something that isn't there, and using the -w
flag so that it fails after that amount of time, not pinging something that is there (like localhost) -n
times. This allows you to handle time less than a second, and I think it's slightly more accurate.
e.g.
(test that 1.1.1.1 isn't taken)
ECHO Waiting 15 seconds
PING 1.1.1.1 -n 1 -w 15000 > NUL
or
PING -n 15 -w 1000 127.1 >NUL
As the plural in getElementsByName()
implies, does it always return list of elements that have this name. So when you have an input element with that name:
<input type="text" name="Tue">
And it is the first one with that name, you have to use document.getElementsByName('Tue')[0]
to get the first element of the list of elements with this name.
Beside that are properties case sensitive and the correct spelling of the value property is .value
.
I'm using Visual Studio 2017.
It will publish, complete with setup file to the location you specified.
Hope this helps
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
You can see if object has shape or not
def check_array(x):
try:
x.shape
return True
except:
return False
Based on William McBrine's answer, here is a solution for fixed-length strings which is 9% faster for my use case:
import itertools
import struct
def make_strxor(size):
def strxor(a, b, izip=itertools.izip, pack=struct.pack, unpack=struct.unpack, fmt='%dB' % size):
return pack(fmt, *(a ^ b for a, b in izip(unpack(fmt, a), unpack(fmt, b))))
return strxor
strxor_3 = make_strxor(3)
print repr(strxor_3('foo', 'bar'))
Swift 4 and Constraints
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
Update 2010-2011:
zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.
As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config
again.
But that is just me.
Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.
Original answer.
The following:
C:\prog\git>git config --global core.editor C:/prog/git/npp.sh
C:/prog/git/npp.sh:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh
script.
(As Franky comments: "Remember to save your .sh
file with Unix style line endings or receive mysterious error messages!")
More details on the SO question How can I set up an editor to work with Git on Windows?
Note the '-multiInst
' option, for ensuring a new instance of notepad++ for each call from Git.
Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:
git
is passing it acygwin
path andnpp
doesn't know what to do with it
So the script in that case would be:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"
Multiple lines for readability:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
-nosession -noPlugin "$(cygpath -w "$*")"
With "$(cygpath -w "$*")"
being the important part here.
Val commented (and then deleted) that you should not use -notabbar
option:
It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since
-notab
becomes the default setting and you mustSettings>Preferences>General>TabBar> Hide>uncheck
every time you start notepad after rebase. This is hell. You recommended the hell.
So use rather:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"
That is:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
-noPlugin "$(cygpath -w "$*")"
If you want to place the script 'npp.sh
' in a path with spaces (as in
'c:\program files\...
',), you have three options:
Either try to quote the path (single or double quotes), as in:
git config --global core.editor 'C:/program files/git/npp.sh'
or try the shortname notation (not fool-proofed):
git config --global core.editor C:/progra~1/git/npp.sh
or (my favorite) place 'npp.sh
' in a directory part of your %PATH%
environment variable. You would not have then to specify any path for the script.
git config --global core.editor npp.sh
Steiny reports in the comments having to do:
git config --global core.editor '"C:/Program Files (x86)/Git/scripts/npp.sh"'
Actually the last one is not weird. Code is setting the timezone for working instead of working2.
SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss");
working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).
Fixing this error gives:
24:00:00
00:00:00
01:00:00
In your tsconfig.json
file set the parameter "noImplicitAny": false
under compilerOptions
to get rid of this error.
If you are, sometimes, expecting null you could use something like this:
var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)
In your repository use null-able datetime.
public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}
One solution is to implement an OnScrollListener
and make changes (like adding items, etc.) to the ListAdapter
at a convenient state in its onScroll
method.
The following ListActivity
shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.
public class Test extends ListActivity implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
}
}
You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).
Though it is marked as resolved here my KOTLIN RESOLUTION
fun log(properties: Map<String, Any>) {
val propertyPairsList = properties.map { Pair(it.key, it.value) }
val bundle = bundleOf(*propertyPairsList.toTypedArray())
}
bundleOf has vararg parameter
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
Well, I'd expect it's this line that's throwing the exception:
var documentRow = _dsACL.Documents.First(o => o.ID == id)
First()
will throw an exception if it can't find any matching elements. Given that you're testing for null immediately afterwards, it sounds like you want FirstOrDefault()
, which returns the default value for the element type (which is null for reference types) if no matching items are found:
var documentRow = _dsACL.Documents.FirstOrDefault(o => o.ID == id)
Other options to consider in some situations are Single()
(when you believe there's exactly one matching element) and SingleOrDefault()
(when you believe there's exactly one or zero matching elements). I suspect that FirstOrDefault
is the best option in this particular case, but it's worth knowing about the others anyway.
On the other hand, it looks like you might actually be better off with a join here in the first place. If you didn't care that it would do all matches (rather than just the first) you could use:
var query = from target in _lstAcl.Documents
join source in _dsAcl.Document
where source.ID.ToString() equals target.ID
select new { source, target };
foreach (var pair in query)
{
target.Read = source.Read;
target.ReadRule = source.ReadRule;
// etc
}
That's simpler and more efficient IMO.
Even if you do decide to keep the loop, I have a couple of suggestions:
if
. You don't need it, as if Count is zero the for loop body will never executeUse exclusive upper bounds in for loops - they're more idiomatic in C#:
for (i = 0; i < _lstAcl.Documents.Count; i++)
Eliminate common subexpressions:
var target = _lstAcl.Documents[i];
// Now use target for the rest of the loop body
Where possible use foreach
instead of for
to start with:
foreach (var target in _lstAcl.Documents)
This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s
by a factor of 4. [because A = WH => (2W)(2H)=4A]
There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.
# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
gives
Notice how the size increases very quickly. If instead we have
# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
gives
Now the apparent size of the markers increases roughly linearly in an intuitive fashion.
As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.
Hope this helps!
Edit: (In response to comment from @Emma)
It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.
However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n
bigger we would increase the area by a factor n
not the radius so the apparent size scales linearly with the area.
Edit to visualize the comment by @TomaszGandor:
This is what it looks like for different functions of the marker size:
x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()
I think you've answered your own question: try not to go beyond the 70 Mb limit, however it really depends on many things: what iOS version you're using (not SDK), how many applications running in background, what exact memory you're using etc.
Just avoid the instant memory splashes (e.g. you're using 40 Mb of RAM, and then allocating 80 Mb's more for some short computation). In this case iOS would kill your application immediately.
You should also consider lazy loading of assets (load them only when you really need and not beforehand).
Well, I got it. One way is to override the QWidget::closeEvent
(QCloseEvent *event)
method in your class definition and add your code into that function. Example:
class foo : public QMainWindow
{
Q_OBJECT
private:
void closeEvent(QCloseEvent *bar);
// ...
};
void foo::closeEvent(QCloseEvent *bar)
{
// Do something
bar->accept();
}
I'm using
Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"
to format a column
So I guess
Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"
would do the trick for you.
More: NumberFormat function.
I have had a difficulty with the EF when the connection the server is stopped or paused, and I raised the same question. So for completeness to the above answers here is the code.
/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
You can create an extension method similar to ToDictionary() with the difference being that it allows duplicates. Something like:
public static Dictionary<TKey, TElement> SafeToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer = null)
{
var dictionary = new Dictionary<TKey, TElement>(comparer);
if (source == null)
{
return dictionary;
}
foreach (TSource element in source)
{
dictionary[keySelector(element)] = elementSelector(element);
}
return dictionary;
}
In this case, if there are duplicates, then the last value wins.
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
I got this problem, and tried many ways to solve it. Finally, it turned out that make clean
and make
again solved it. The reason is:
I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean
saved the day.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
To achieve this feat, define a outer linear layout with a weightSum={amount of weight to distribute}
.
it defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.Another example would be set weightSum=2, and if the two children set layout_weight=1
then each would get 50% of the available space.
WeightSum is dependent on the amount of children in the parent layout.
i know this is way too late. but i had the same requirement. i solved like this
<android.support.v7.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardUseCompatPadding="true"
app:cardElevation="4dp"
app:cardCornerRadius="3dp" >
<!-- put whatever you want -->
</android.support.v7.widget.CardView>
you need to add dependency:
compile 'com.android.support:cardview-v7:25.0.1'
Other way to get current Controller name in View
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
Try the following code:
For PHP 5.4.0 and above:
$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);
For PHP Version < 5.4.0
$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);
Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.
Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.
Using Multiple Peoples help from multiple Threads..
I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..
Here's my Encoding & Decoding methods..
// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;
// Text To Hex
public static String textToHex(String text)
{
byte[] buf = null;
buf = text.getBytes(encodingType);
char[] HEX_CHARS = "0123456789abcdef".toCharArray();
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
// Hex To Text
public static String hexToText(String hex)
{
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
String st = new String(data, encodingType);
return st;
}
Maybe these two examples illustrate you the difference between a deadlock and a livelock:
Java-Example for a deadlock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
}
public static void doB() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
}
}
Sample output:
Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2
Java-Example for a livelock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LivelockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(LivelockSample::doA, "Thread A");
Thread threadB = new Thread(LivelockSample::doB, "Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
public static void doB() {
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
}
Sample output:
Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...
Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.
One solution is to use a background image centered within an element sized to the cropped dimensions.
.center-cropped {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-position: center center;_x000D_
background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
style="background-image: url('http://placehold.it/200x200');">_x000D_
</div>
_x000D_
img
tagThis version retains the img
tag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.
.center-cropped {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-position: center center;_x000D_
background-repeat: no-repeat;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
/* Set the image to fill its parent and make transparent */_x000D_
.center-cropped img {_x000D_
min-height: 100%;_x000D_
min-width: 100%;_x000D_
/* IE 8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
/* IE 5-7 */_x000D_
filter: alpha(opacity=0);_x000D_
/* modern browsers */_x000D_
opacity: 0;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
style="background-image: url('http://placehold.it/200x200');">_x000D_
<img src="http://placehold.it/200x200" />_x000D_
</div>
_x000D_
object-fit
/-position
The CSS3 Images specification defines the object-fit
and object-position
properties which together allow for greater control over the scale and position of the image content of an img
element. With these, it will be possible to achieve the desired effect:
.center-cropped {_x000D_
object-fit: none; /* Do not scale the image */_x000D_
object-position: center; /* Center the image within the element */_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<img class="center-cropped" src="http://placehold.it/200x200" />
_x000D_
Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.
Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.
In pycharm 2019.2, you can simply do this to run all tests:
For a higher integration of pytest into pycharm, see https://www.jetbrains.com/help/pycharm/pytest.html
If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder. You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.
Sub GetSubFolders()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Set f = fso.GetFolder("D:\Proj\")
For Each sf In f.SubFolders
'Code inside
Next
End Sub
I tried sudo apt install nginx-full. You will get all the required packages.
You need to unblock the pop up windows for your browser and the code could work.
chrome://settings/contentExceptions#popups
You have to use the equal sign in the formula box
=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
This is an older question, but if you are using event delegation this is what caused it for me.
After removing .delegate-two
it stopped executing twice. I believe this happens if both delegates are present on the same page.
$('.delegate-one, .delegate-two').on('click', '.button', function() {
/* CODE */
});
First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.
To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar()
method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.
If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:
I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
You can use FusedLocationProvider
For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
...
...
...
implementation 'com.google.android.gms:play-services-location:17.0.0'
}
Permissions in Manifest
Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_ID
)
Then you can use the FusedLocationProvider Client to get the updated location in your desired place.
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
var location: Location? = task.result
if (location == null) {
requestNewLocationData()
} else {
findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
}
}
You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:
private fun requestNewLocationData() {
var mLocationRequest = LocationRequest()
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mLocationRequest.interval = 0
mLocationRequest.fastestInterval = 0
mLocationRequest.numUpdates = 1
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
)
}
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
Dim a As Range, b As Range
Set a = Selection
For Each b In a.Rows
MsgBox b.Address
Next
If you try:
PS > Test("ABC", "GHI") ("DEF")
you get:
$arg1 value: ABC GHI
$arg2 value: DEF
So you see that the parentheses separates the parameters
If you try:
PS > $var = "C"
PS > Test ("AB" + $var) "DEF"
you get:
$arg1 value: ABC
$arg2 value: DEF
Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.
KISS : Keep it simple, stupid
Way A: Implement an own SortableBindingList class when like to use DataBinding and sorting.
Way B: Use a List<string> sorting works also but does not work with DataBinding.
case...when
behaves a bit unexpectedly when handling classes. This is due to the fact that it uses the ===
operator.
That operator works as expected with literals, but not with classes:
1 === 1 # => true
Fixnum === Fixnum # => false
This means that if you want to do a case ... when
over an object's class, this will not work:
obj = 'hello'
case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string or number')
end
Will print "It is not a string or number".
Fortunately, this is easily solved. The ===
operator has been defined so that it returns true
if you use it with a class and supply an instance of that class as the second operand:
Fixnum === 1 # => true
In short, the code above can be fixed by removing the .class
:
obj = 'hello'
case obj # was case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string or number')
end
I hit this problem today while looking for an answer, and this was the first appearing page, so I figured it would be useful to others in my same situation.
For a very simple version of touch
which would be mostly used to create a 0 byte file in the current directory, an alternative would be creating a touch.bat
file and either adding it to the %Path%
or copying it to the C:\Windows\System32
directory, like so:
touch.bat
@echo off
powershell New-Item %* -ItemType file
Creating a single file
C:\Users\YourName\Desktop>touch a.txt Directory: C:\Users\YourName\Desktop Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2020-10-14 10:28 PM 0 a.txt
Creating multiple files
C:\Users\YourName\Desktop>touch "b.txt,c.txt" Directory: C:\Users\YourName\Desktop Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2020-10-14 10:52 PM 0 b.txt -a---- 2020-10-14 10:52 PM 0 c.txt
Also
New-Item : The file 'C:\Users\YourName\Desktop\a.txt' already exists.
C:\Users\YourName\Desktop>touch d.txt,e.txt,f.txt C:\Users\YourName\Desktop>touch "g.txt, 'name with spaces.txt'"
l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
You can also use DateTime class:
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
Result:
1 second(s)
You can try this extension
public static bool IsSubClassOfGenericClass(this Type type, Type genericClass,Type t)
{
return type.IsSubclassOf(genericClass.MakeGenericType(new[] { t }));
}
You can just use the pd.Timestamp constructor. The following diagram may be useful for this and related questions.
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
Like you said, a jar is a zip file (not a special type, but just a plain old zip), so either library could be made to work. The reasoning is that the average person, seeing a *.zip extension, tends to unzip it. Since the app server wants it unzipped, a simple rename keeps people from unzipping it simply out of habit. Likewise, *.war file also should remain uncompressed.
java.util.jar basically just adds additional functionality to java.util.zip with very little extra overhead. Let the java.util.jar be a helper in posting, etc... and use it.
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
This is what I've tried and it works fine in ff, chrome and ie8:
/* set width for the <fb:like> tag */
.fb-button {
width:51px;
}
/* set width for the iframe below, to hide the count label*/
.fb-button iframe{
width:45px!important;
}
I had the same issue in Windows
and it worked since my proxy configuration in settings.xml
file was changed
So locate and edit the file inside the \conf
folder, for example : C:\Program Files\apache-maven-3.2.5\conf
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>jorgesys</username>
<password>supercalifragilisticoespialidoso</password>
<host>proxyjorgesys</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
80
to 8080
/program files
you can make a copy, edit the file and replace the file located into /program files
folder.Quite a painful problem for me too. Just spent about an hour trying to build and re-build - no joy. In the end I had to do this:
I guess it's a bunch of jargon about arm6 , arm7 as it looked like my project was valid for both, at least the settings seemed to say so ) , my guess is this is a cynical way to bamboozle us with the technicalities, which we don't understand, so we just take the easy option and target the latest iOS ( good for Apple with more people being up-to-date ) ....
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
Thanks so much Jason Pan for suggesting that method. The thread1 if statement is not atomic, so that while that statement executes, it's possible for thread2 to intrude on thread1, allowing non-reachable code to be reached. I've organized ideas from the prior posts into a complete demonstration program (below) that I ran with Python 2.7.
With some thoughtful analysis I'm sure we could gain further insight, but for now I think it's important to demonstrate what happens when non-atomic behavior meets threading.
# ThreadTest01.py - Demonstrates that if non-atomic actions on
# global variables are protected, task can intrude on each other.
from threading import Thread
import time
# global variable
a = 0; NN = 100
def thread1(threadname):
while True:
if a % 2 and not a % 2:
print("unreachable.")
# end of thread1
def thread2(threadname):
global a
for _ in range(NN):
a += 1
time.sleep(0.1)
# end of thread2
thread1 = Thread(target=thread1, args=("Thread1",))
thread2 = Thread(target=thread2, args=("Thread2",))
thread1.start()
thread2.start()
thread2.join()
# end of ThreadTest01.py
As predicted, in running the example, the "unreachable" code sometimes is actually reached, producing output.
Just to add, when I inserted a lock acquire/release pair into thread1 I found that the probability of having the "unreachable" message print was greatly reduced. To see the message I reduced the sleep time to 0.01 sec and increased NN to 1000.
With a lock acquire/release pair in thread1 I didn't expect to see the message at all, but it's there. After I inserted a lock acquire/release pair also into thread2, the message no longer appeared. In hind signt, the increment statement in thread2 probably also is non-atomic.
Using regular ng-view
module you cannot have more than one dynamic template.
However, this project enables you to do so (look for ui-router
).
MVC 4 example...
Note that you do not always have to pass parameter named ID
var message = model.UserName + " - thanks for taking yourtime to register on our glorious site. ";
return RedirectToAction("ThankYou", "Account", new { whatever = message });
And,
public ActionResult ThankYou(string whatever) {
ViewBag.message = whatever;
return View();
}
Of course you can assign string to model fields instead of using ViewBag if that is your preference.
I don't know why but animating only the visibility
property is not working on any browser.
What you can do is animate the opacity
property in such a way that the browser doesn't have enough frames to fade in or out the text.
Example:
span {_x000D_
opacity: 0;_x000D_
animation: blinking 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinking {_x000D_
from,_x000D_
49.9% {_x000D_
opacity: 0;_x000D_
}_x000D_
50%,_x000D_
to {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<span>I'm blinking text</span>
_x000D_
You need to convert your script to a shell function:
#!/bin/bash
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
# . ~/bin/myprog.sh
#
function myprog() {
A=$1
B=$2
echo "aaa ${A} bbb ${B} ccc"
cd /proc
}
The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.
By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.
Path In Android Studio in mac:
Android Studio -> Preferences -> Editor -> Inspections
Expand Android -> Expand Lint -> Expand Correctness
Uncheck the checkbox for Using system app permission
Click on "APPLY" -> "OK"
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
Java 8 Stream API
can be used for the purpose,
ArrayList<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("A");
list1.add("D");
list1.add("G");
ArrayList<String> list2 = new ArrayList<>();
list2.add("B");
list2.add("D");
list2.add("E");
list2.add("G");
List<String> noDup = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
noDup.forEach(System.out::println);
En passant, it shouldn't be forgetten that distinct()
makes use of hashCode()
.
It seems that your question is quite answered, but i have an approach that may simplify you case:
I had a similar issue trying to return string data from mysql, even configuring both database and php to return strings formatted to utf-8. The only way i got the error was actually returning them from the database.
Finally, sailing through the web i found a really easy way to deal with it:
Giving that you can save all those types of string data in your mysql in different formats and collations, what you only need to do is, right at your php connection file, set the collation to utf-8, like this:
$connection = new mysqli($server, $user, $pass, $db);
$connection->set_charset("utf8");
Wich means that first you save the data in any format or collation and you convert it only at the return to your php file.
Hope it was helpful!
It can also be done using backtracking by maintaining a visited array.
void foo(vector<vector<int> > &s,vector<int> &data,int go,int k,vector<int> &vis,int tot)
{
vis[go]=1;
data.push_back(go);
if(data.size()==k)
{
s.push_back(data);
vis[go]=0;
data.pop_back();
return;
}
for(int i=go+1;i<=tot;++i)
{
if(!vis[i])
{
foo(s,data,i,k,vis,tot);
}
}
vis[go]=0;
data.pop_back();
}
vector<vector<int> > Solution::combine(int n, int k) {
vector<int> data;
vector<int> vis(n+1,0);
vector<vector<int> > sol;
for(int i=1;i<=n;++i)
{
for(int i=1;i<=n;++i) vis[i]=0;
foo(sol,data,i,k,vis,n);
}
return sol;
}
If you're looking for the simplest way to check for a database object's existence before removing it, here's one way (example uses a SPROC, just like your example above but could be modified for tables, indexes, etc...):
IF (OBJECT_ID('MyProcedure') IS NOT NULL)
DROP PROCEDURE MyProcedure
GO
This is quick and elegant, but you need to make sure you have unique object names across all object types since it does not take that into account.
I Hope this helps!
I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.
Check the NPM docs for install
With the
--production
flag (or when the NODE_ENV environment variable is set to production), npm will not install modules listed in devDependencies."The
--only={prod[uction]|dev[elopment]}
argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV."
Have you tried
npm install --only=dev
If you are worried that your package.json might be incorrect, best thing to do is this. Create a new folder, and run:
npm init --yes
Then:
npm install --save-dev brunch@^2.0.4
npm install --save-dev cssnano-brunch@^1.1.5
npm install --save-dev javascript-brunch@^1.8.0
npm install --save-dev sass-brunch@^1.9.2
npm install --save-dev uglify-js-brunch@^1.7.8
npm install jquery@^2.1.4 --save
And you should be good to go! Otherwise, will keep posting other options.
Check your npm configuration:
npm config list
npm gets its config settings from the command line, environment variables, and npmrc files. So check environment variables, and the npmrc file.
Still failing?
Ok, create a new folder, ideally somewhere else on your filesystem. ie. not in same folder hierarchy. For instance, C:\myNewFolder - the closer to the base C: drive the better.
Then run:
npm init --yes
Now run:
npm install underscore --save
and finally:
npm install mocha --save-dev
Does everything work as expected?
What I am trying to do is understand whether your problem is global, or something local to the previous folder and dependencies.
To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.
In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline
would not work.
I was just having the same issue and suggest you use Jupyter Notebook for the visualization.
Run this from the branch where you want the file to end up:
git checkout otherbranch myfile.txt
General formulas:
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
Some notes (from comments):
myfile.txt
and mydir
an alternative:
git show commit_id:path/to/file > path/to/file
test
is a non-destructive and
, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz
conditional jump.
This one did it for me:
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#form1').append(input);
is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)
used the Firefox firebug to check whether the element was inserted.
Hidden elements do get posted back in the form collection, only read-only fields are discarded.
Michel
I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream
:
Client:
Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data
// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data
// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data
// Send the exit message
dOut.writeByte(-1);
dOut.flush();
dOut.close();
Server:
Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());
boolean done = false;
while(!done) {
byte messageType = dIn.readByte();
switch(messageType)
{
case 1: // Type A
System.out.println("Message A: " + dIn.readUTF());
break;
case 2: // Type B
System.out.println("Message B: " + dIn.readUTF());
break;
case 3: // Type C
System.out.println("Message C [1]: " + dIn.readUTF());
System.out.println("Message C [2]: " + dIn.readUTF());
break;
default:
done = true;
}
}
dIn.close();
Obviously, you can send all kinds of data, not just bytes and strings (UTF).
Note that writeUTF
writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535
bytes to send. This makes it possible for readUTF
to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.
Quick 'n dirty, regex-free, low-robustness chop-chop technique
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)
Use the <apply> task.
It executes a command once for each file. Specify the files by means of filesets or any other resource. <apply> is built-in; no additional dependency needed; no custom task implementation needed.
It's also possible to run the command only once, appending all files as arguments in one go. Use the parallel attribute to switch the behaviour.
Sorry for being late a year.
You can turn off this rule if you wish to skip that test.
Insert:
radix: false
Under the "rules
" property in the tslint.json
file.
It's not recommended to do that if you don't understand this exception.
One way is this:
select id, name, priority from table a
order by case when name='core' then -1 else priority end asc, priority asc
If possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.
To set the @value
field you can use Springs ReflectionTestUtils
- it has a method setField
to set private fields.
@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)
If you run mysql --verbose --help | less
it will tell you about line 11 which .cnf
files it will look for.
You can also do mysql --print-defaults
to show you how the configuration values it will use. This can also be useful in identifying just which config file it is loading.
From jQuery Docs:
const height = $(window).height();
const scrollTop = $(window).scrollTop();
http://api.jquery.com/scrollTop/
http://api.jquery.com/height/
"blue_box"
is null -- are you positive whatever it is with "id='blue'"
exists when this is being run?
try console.log(document.getElementById("blue"))
in chrome or FF with firebug. Your script might be running before the 'blue'
element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload
).
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
Map.values()
:
HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
new HashMap<String, HashMap<SomeInnerKeyType, String>>();
...
for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
ComboBox cb = new ComboBox();
for(String s : h.values())
{
cb.items.add(s);
}
}
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
@media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main
method, though it would help if you posted the code that caused the error and the context in which the code was run.
This might have happened if the user tried to run a .class
file or a .jar
file that has no main
method - in Java, the main
method is the entry point to begin executing the program.
Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.
To fix this problem, a new programmer must either add the midding method (assuming still that it's main
that's missing) or change the method call to the name of a method that does exist.
Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html
px
? PixelsAll of these answers seem to be incorrect. Contrary to intuition, in CSS the px
is not pixels. At least, not in the simple physical sense.
Read this article from the W3C, EM, PX, PT, CM, IN…, about how px
is a "magical" unit invented for CSS. The meaning of px
varies by hardware and resolution. (That article is fresh, last updated 2014-10.)
My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.
To quote that article:
The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.
To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.
Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.
That article gives some guidance about using pt
vs px
vs em
, to answer this Question.
You need to turn off the compiler optimisation.
If you are interested in a particular variable in gdb, you can delare the variable as "volatile" and recompile the code. This will make the compiler turn off compiler optimization for that variable.
volatile int quantity = 0;
Use this:
0?[1-9]|1[012]
To test a pattern as 07/2018 use this:
/^(0?[1-9]|1[012])\/([2-9][0-9]{3})$/
(Date range between 01/2000 to 12/9999 )
You can create a .timer
systemd unit file to control the execution of your .service
unit file.
So for example, to wait for 1 minute after boot-up before starting your foo.service
, create a foo.timer
file in the same directory with the contents:
[Timer]
OnBootSec=1min
It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):
systemctl disable foo.service
systemctl enable foo.timer
You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers
New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let's you change several app attributes.
The main point I want to make is that renaming an app isn't always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if your app needs friendly naming.
As an example I want to name my polls app 'Feedback from users'. It goes like this:
Create a apps.py
file in the polls
directory:
from django.apps import AppConfig
class PollsConfig(AppConfig):
name = 'polls'
verbose_name = "Feedback from users"
Add the default app config to your polls/__init__.py
:
default_app_config = 'polls.apps.PollsConfig'
For more app configuration: https://docs.djangoproject.com/en/1.7/ref/applications/
CompressFormat is too slow...
Try ByteBuffer.
???Bitmap to byte???
width = bitmap.getWidth();
height = bitmap.getHeight();
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();
???byte to bitmap???
Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);
Also make sure you have all @Before
-, @After
- and whatever-JUnit-annotated methods declared as public
. I had mine declared as private
which caused the issue.
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
File.ReadLines()
returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines()
returns an array of strings.
If you want to use an array of strings you need to call the correct function.
You could use Jim solution, just use ReadAllLines()
or you could change your return type.
This would also work:
System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
You can use any generic collection which implements IEnumerable. IList for an example.
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
You can also pad the characters left by including a number following the X
, such as this: string.format("0x{0:X8}", string_to_modify)
, which yields "0x00000C20"
.
If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):
mokey 0 /home/jj33 > nslookup example.ad Server: 172.16.2.10 Address: 172.16.2.10#53 Non-authoritative answer: Name: example.ad Address: 172.16.6.2 Name: example.ad Address: 172.16.141.160 Name: example.ad Address: 172.16.7.9 Name: example.ad Address: 172.19.1.14 Name: example.ad Address: 172.19.1.3 Name: example.ad Address: 172.19.1.11 Name: example.ad Address: 172.16.3.2
Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.
I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.
Yet another approach to the same problem. As it is not recommended to store any kind of credential within the source code, we decided to set the passwords for the key store and key alias in a separate properties file as follows:
key.store.password=[STORE PASSWORD]
key.alias.password=[KEY PASSWORD]
If you use git, you can create a text file called, for example, secure.properties. You should make sure to exclude it from your repository (if using git, adding it to the .gitignore file). Then, you would need to create a signing configuration, like some of the other answers indicate. The only difference is in how you would load the credentials:
android {
...
signingConfigs {
...
release {
storeFile file('[PATH TO]/your_keystore_file.jks')
keyAlias "your_key_alias"
File propsFile = file("[PATH TO]/secure.properties");
if (propsFile.exists()) {
Properties props = new Properties();
props.load(new FileInputStream(propsFile))
storePassword props.getProperty('key.store.password')
keyPassword props.getProperty('key.alias.password')
}
}
...
}
buildTypes {
...
release {
signingConfig signingConfigs.release
runProguard true
proguardFile file('proguard-rules.txt')
}
...
}
}
Never forget to assign the signingConfig to the release build type manually (for some reason I sometimes assume it will be used automatically). Also, it is not mandatory to enable proguard, but it is recommendable.
We like this approach better than using environment variables or requesting user input because it can be done from the IDE, by switching to the realease build type and running the app, rather than having to use the command line.
This is what worked for me
find . -type f -name "*.svg" -exec bash -c 'rsvg-convert -h 1000 $0 > $0.png' {} \;
rename 's/svg\.png/png/' *
This will loop all the files in your current folder and sub folder and look for .svg
files and will convert it to png with transparent background.
Make sure you have installed the librsvg and rename util
brew install librsvg
brew install rename
The major difference between == and equals() is
1) == is used to compare primitives.
For example :
String string1 = "Ravi";
String string2 = "Ravi";
String string3 = new String("Ravi");
String string4 = new String("Prakash");
System.out.println(string1 == string2); // true because same reference in string pool
System.out.println(string1 == string3); // false
2) equals() is used to compare objects. For example :
System.out.println(string1.equals(string2)); // true equals() comparison of values in the objects
System.out.println(string1.equals(string3)); // true
System.out.println(string1.equals(string4)); // false
For me, running the ad-hoc network on Windows 8.1, it was two things:
Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.
I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.
When posting an HTML checkbox to the server, it has a string value of 'on' or ''.
Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.
One way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts.
Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.
public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)
dim strThisCheckedValue
if (i_strChecked_TorF = "T") then
strThisCheckedValue = " checked "
i_strChecked_TorF = "on"
else
strThisCheckedValue = ""
i_strChecked_TorF = ""
end if
MakeDummyReadonlyCheckbox = "<input type='hidden' id='" & i_strName & "' name='" & i_strName & "' " & _
"value='" & i_strChecked_TorF & "'>" & _
"<input type='checkbox' disabled id='" & i_strName & "Dummy' name='" & i_strName & "Dummy' " & _
strThisCheckedValue & ">"
end function
public function GetCheckbox(i_objCheckbox)
select case trim(i_objCheckbox)
case ""
GetCheckbox = "F"
case else
GetCheckbox = "T"
end select
end function
At the top of an ASP page you can pickup the persisted value...
strDataValue = GetCheckbox(Request.Form("chkTest"))
and when you want to output your checkbox you can do this...
response.write MakeDummyReadonlyCheckbox("chkTest", strDataValue)
I have tested this and it works just fine. It also does not rely upon JavaScript.
How about this, it will read each line to a variable and that can be used subsequently ! say myscript output is redirected to a file called myscript_output
awk '{while ( (getline var < "myscript_output") >0){print var;} close ("myscript_output");}'
You are trying to join Person_Fear.PersonID
onto Person_Fear.FearID
- This doesn't really make sense. You probably want something like:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
INNER JOIN Fears
ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID
This joins Persons
onto Fears
via the intermediate table Person_Fear
. Because the join between Persons
and Person_Fear
is a LEFT JOIN
, you will get all Persons
records.
Alternatively:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID
Sometimes I use a boolean variable. Naive, if you want, but I find it quite flexible and comfortable to read. Testing a variable may avoid testing again complex conditions and may also collect results from several tests in inner loops.
x_loop_must_break = False
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
x_loop_must_break = True
break
if x_loop_must_break: break
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status
is undefined when it is returned.
Effectively, your code works as follows:
function doSomething(someargums) {
return status;
}
var response = doSomething();
And then some time later, your AJAX request is completing; but it's already too late
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
Where you previously may have had
var response = doSomething();
alert(response);
You should do:
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
alert(txtBack);
})
});
};
Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).
Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.
It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.
Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.
I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.
Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).
After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
Try this
$(function() {
$('#clickMe').click(function(event) {
var mytext = $('#myText').val();
$('<div id="dialog">'+mytext+'</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#dialog").remove();
}
});
}); //close click
});
And in HTML
<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>
A simple solution that worked for me is to close the Terminal and restart it.
Remove Duplicates
public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}
//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dTable;
}
Here Links below
http://www.dotnetspider.com/resources/4535-Remove-duplicate-records-from-table.aspx
http://www.dotnetspark.com/kb/94-remove-duplicate-rows-value-from-datatable.aspx
For remove duplicates in column
http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html
If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".
Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations. Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"
The subprocess
module is the preferred way of running other programs from Python -- much more flexible and nicer to use than os.system
.
import subprocess
#subprocess.check_output(['ls', '-l']) # All that is technically needed...
print(subprocess.check_output(['ls', '-l']))
UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";
UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";
UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];
lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];
[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];
username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;
[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];
[alt show];
If you're sure the server is correct, sed -i 1d ~/.ssh/known_hosts
will delete line 1 of your local ~/.ssh/known_hosts
. The new correct key will be added to the file the next time you connect.
test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
ls.append(key)
print(ls[0])
Conventional way of appending the keys to a statically defined list and then indexing it for same
I found a simple way
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
I just stumbled across one more advantage for DATETIME2
: it avoids a bug in the Python adodbapi
module, which blows up if a standard library datetime
value is passed which has non-zero microseconds for a DATETIME
column but works fine if the column is defined as DATETIME2
.
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");
The path to the SDK is:
C:\Users\USERNAME\AppData\Local\Android\sdk
This can be used in Eclipse after you replace USERNAME with your Windows user name.
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
Android Studio debug.keystore file path depend on environment variable ANDROID_SDK_HOME.
If ANDROID_SDK_HOME defined, then file placed in SDK's subfolder named .android .
When not defined, then keystore placed at user home path in same subfolder:
- %HOMEPATH%\.android\ on Windows
- $HOME/.android/ on Linux
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path
to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.
Please refer to the below example. I'm here showing only one component.
login.component.html
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
cssProperty:any;
constructor(private sanitizer: DomSanitizer) {
console.log(window.innerWidth);
console.log(window.innerHeight);
this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
}
ngOnInit() {
}
}
login.component.ts
<div class="home">
<div class="container" [style]="cssProperty">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">Please login</div>
<div class="card-footer">Login</div>
</div>
</div>
</div>
login.component.css
.card {
max-width: 400px;
}
.card .card-body {
min-height: 150px;
}
.home {
background-color: rgba(171, 172, 173, 0.575);
}
On rails 4.2.2, go to application.rb
and use config.time_zone='city'
(e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).
It should work just fine. It worked for me.