I faced the same problem. I found two solutions: (1) Editing the jar file manually:
Open the jar file with WinRar (or similar tools). Go to Meta-info > services , and edit "org.apache.hadoop.fs.FileSystem" by appending:
org.apache.hadoop.fs.LocalFileSystem
(2) Changing the order of my dependencies as follow
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
From a posting by Matz:
(1) ++ and -- are NOT reserved operator in Ruby.
(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
matz.
you can use sort() in C++ STL. sort() function Syntax :
sort(array_name, array_name+size)
So you use sort(v, v+2000);
I think this will handle it better:
my_dict = {0: "c", 1: "d", 2: "e", 3: "f"}
def validate(x, y, z):
for ele in [x, y, z]:
if ele in my_dict.keys():
return my_dict[ele]
Output:
print validate(0, 8, 9)
c
print validate(9, 8, 9)
None
print validate(9, 8, 2)
e
Add the following 2 lines
var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);
If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"
Try this:
$("#message span").text("hello world!");
See it in your code!
function Errormessage(txt) {
var m = $("#message");
// set text before displaying message
m.children("span").text(txt);
// bind close listener
m.children("a.close-notify").click(function(){
m.fadeOut("slow");
});
// display message
m.fadeIn("slow");
}
This will ensure that the content gets save when you lose focus of the textarea
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
Well, getting full path is not possible but we can have a temporary path.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
If you declare it like
int x;
in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).
The correct way to approach this is to have the header file say
extern int x; /* declared in foo.c */
and then in foo.c you can say
int x; /* exported in foo.h */
THen you can include your header file in as many places as you like.
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
This answer by Martin R seems to be correct because it accounts for Unicode.
However at the time of the post (Swift 1) his code doesn't compile in Swift 2.0 (Xcode 7), because they removed advance()
function. Updated version is below:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
if let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
return Range(nsRange, in: self)
}
}
You should always end threads by checking a flag in the run()
loop (if any).
Your thread should look like this:
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean execute;
@Override
public void run() {
this.execute = true;
while (this.execute) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
this.execute = false;
}
}
}
public void stopExecuting() {
this.execute = false;
}
}
Then you can end the thread by calling thread.stopExecuting()
. That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep).
You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.
To avoid waiting for 15 seconds, you can split up the sleep like this:
...
try {
LOGGER.debug("Sleeping...");
for (int i = 0; (i < 150) && this.execute; i++) {
Thread.sleep((long) 100);
}
LOGGER.debug("Processing");
} catch (InterruptedException e) {
...
If you use shared_ptr
(only shared_ptr, not unique_ptr), you don't have to have the base class destructor virtual:
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){ // not virtual
cout << "Base Destructor called\n";
}
};
class Derived: public Base
{
public:
Derived(){
cout << "Derived constructor called\n";
}
~Derived(){
cout << "Derived destructor called\n";
}
};
int main()
{
shared_ptr<Base> b(new Derived());
}
output:
Base Constructor Called
Derived constructor called
Derived destructor called
Base Destructor called
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
This is a full working example :
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public void callWebService(String soapAction, String soapEnvBody) throws IOException {
// Create a StringEntity for the SOAP XML.
String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
StringEntity stringEntity = new StringEntity(body, "UTF-8");
stringEntity.setChunked(true);
// Request parameters and other properties.
HttpPost httpPost = new HttpPost("http://example.com?soapservice");
httpPost.setEntity(stringEntity);
httpPost.addHeader("Accept", "text/xml");
httpPost.addHeader("SOAPAction", soapAction);
// Execute and get the response.
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String strResponse = null;
if (entity != null) {
strResponse = EntityUtils.toString(entity);
}
}
Well the hardest part probably is selecting the second "column" since I wouldn't know of an easy way to treat multiple spaces as one. For the rest it's easy. Use bash substitutions.
# cat bla.txt
something1: +12.0 (some unnecessary trailing data (this must go))
something2: +15.5 (some more unnecessary trailing data)
something4: +9.0 (some other unnecessary data)
something1: +13.5 (blah blah blah)
# cat bla.sh
OLDIFS=$IFS
IFS=$'\n'
for i in $(cat bla.txt); do
i=$(echo "$i" | awk '{print $2}')
u="${u:+$u, }$i"
done
IFS=$OLDIFS
echo "$u"
# bash ./bla.sh
+12.0, +15.5, +9.0, +13.5
There are several good points made here, but multiple return points can be unreadable as well, if the method is very lengthy. That being said, if you're going to use multiple return points just make sure that your method is short, otherwise the readability bonus of multiple return points may be lost.
An output reg foo
is just shorthand for output foo_wire; reg foo; assign foo_wire = foo
. It's handy when you plan to register that output anyway. I don't think input reg
is meaningful for module
(perhaps task
). input wire
and output wire
are the same as input
and output
: it's just more explicit.
All do not work for me on eloquent collections, laravel eloquent collections use the key from the items I think which causes merging issues, you need to get the first collection back as an array, put that into a fresh collection and then push the others into the new collection;
public function getFixturesAttribute()
{
$fixtures = collect( $this->homeFixtures->all() );
$this->awayFixtures->each( function( $fixture ) use ( $fixtures ) {
$fixtures->push( $fixture );
});
return $fixtures;
}
There is no error in the code, but the error is thrown due to the following:
- Please check whether you have given Read-write permission to MS-Access database file.
- The Database file where it is stored (say in Folder1) is read-only..?
suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files
all most all c drive files been set read-only so changing this permission solves this Problem.
If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:
{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}
Details for this tag here and more about dates according to the given format here
Example:
<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>
You can use a named vector.
With base R (maybe somewhat clunky):
x = data.frame(q = 1, w = 2, e = 3)
rename_vec <- c(q = "A", e = "B")
names(x) <- ifelse(is.na(rename_vec[names(x)]), names(x), rename_vec[names(x)])
x
#> A w B
#> 1 1 2 3
Or a dplyr
option with !!!
:
library(dplyr)
rename_vec <- c(A = "q", B = "e") # the names are just the other way round than in the base R way!
x %>% rename(!!!rename_vec)
#> A w B
#> 1 1 2 3
The latter works because the 'big-bang' operator !!!
is forcing evaluation of a list or a vector.
?`!!`
!!! forces-splice a list of objects. The elements of the list are spliced in place, meaning that they each become one single argument.
This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx
I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.
Don't expect sprintf (or any other function with varargs) to automatically cast anything. The compiler doesn't try to read the format string and do the cast for you; at runtime, sprintf has no meta-information available to determine what is on the stack; it just pops bytes and interprets them as given by the format string. sprintf(myvar, "%0", 0); immediately segfaults.
So: The format strings and the other arguments must match!
As a newbie, I faced the same 'problem'.
In newbie terms :
when you call plot()
, the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R.
However, some commands, like identify()
, act on open/active graph windows.
When identify()
cannot find an open/active graph window, it gives this error message.
However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify()
etc.
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.
template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
struct ftor {
bool operator()( T const &l, T const &r )
{ return comp( l, r ); }
};
public:
typedef std::set< T, ftor > t;
};
// usage
bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!
Wow, I think that was worth the trouble!
Along with the points made by others, the $=
selector is the "ends with" selector. You will want the *=
(contains) selector, like so:
$('a').each(function() {
if ($(this).is('[href*="?"')) {
alert("Contains questionmark");
}
});
As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:
$('a[href*="?"]').each(function() {
alert("Contains questionmark");
});
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
I don't know if this solves your problem but instead of:
$("#tbIntervalos").find("td").attr("id", horaInicial);
you can just do:
$("#tbIntervalos td#" + horaInicial);
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("somParam", "someValue")
.build();
Request request = new Request.Builder()
.url(BASE_URL + route)
.post(requestBody)
.build();
This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,
class Myclass {
int a;
class SubClass {
int b;
}
}
With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,
MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String
Now you can pass this String across activities as a StringExtra with the activity intent.
Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);
Then in the receiving activity, create the original object from the string representation.
String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object
It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.
UPDATE
While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.
setBackground()
is the right method to use. Did you repaint after you changed it? If you change it before you make the panel (or its containing frame) visible it should work
Divide and Conquer involves three steps at each level of recursion:
Dynamic Programming involves the following four steps:
1. Characterise the structure of optimal solutions.
2. Recursively define the values of optimal solutions.
3. Compute the value of optimal solutions.
4. Construct an Optimal Solution from computed information.
For easier understanding, lets see divide and conquer as a brute force solution and its optimisation as dynamic programming.
N.B. divide and conquer algorithms with overlapping subproblems can only be optimised with dp.
Here are two solutions:
Select count(columnname) as countofNotNulls, count(isnull(columnname,1))-count(columnname) AS Countofnulls from table name
OR
Select count(columnname) as countofNotNulls, count(*)-count(columnname) AS Countofnulls from table name
That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.
For example:
$ cat t.c
#include <stdio.h>
int main()
{
printf("hello\n");
return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0
0x400534
is the address of main
in my case. 0x400408
is also a valid function address in a.out
, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init
. You can see the layout of your executable with readelf -a your_exe
.)
Other times when addr2line
will fail is if you're including a library that has no debug information.
Well I came to this post because I wanted to reinstall some app I liked much. If this is your case, just go to Google Play, and look for My Apps, the tab All, and you will find a way to reinstall some app you liked. I faced a problem that I could not find by search one app, but it was there in My apps so I could reinstall in my new mobile ;)
As AraK said, the c++ streams interface will always work portably.
std::size_t s = 1024; std::cout << s; // or any other kind of stream like stringstream!
If you want C stdio, there is no portable answer to this for certain cases of "portable." And it gets ugly since as you've seen, picking the wrong format flags may yield a compiler warning or give incorrect output.
C99 tried to solve this problem with inttypes.h formats like "%"PRIdMAX"\n". But just as with "%zu", not everyone supports c99 (like MSVS prior to 2013). There are "msinttypes.h" files floating around to deal with this.
If you cast to a different type, depending on flags you may get a compiler warning for truncation or a change of sign. If you go this route pick a larger relevant fixed size type. One of unsigned long long and "%llu" or unsigned long "%lu" should work, but llu may also slow things down in a 32bit world as excessively large. (Edit - my mac issues a warning in 64 bit for %llu not matching size_t, even though %lu, %llu, and size_t are all the same size. And %lu and %llu are not the same size on my MSVS2012. So you may need to cast + use a format that matches.)
For that matter, you can go with fixed size types, such as int64_t. But wait! Now we're back to c99/c++11, and older MSVS fails again. Plus you also have casts (e.g. map.size() is not a fixed size type)!
You can use a 3rd party header or library such as boost. If you're not already using one, you may not want to inflate your project that way. If you're willing to add one just for this issue, why not use c++ streams, or conditional compilation?
So you're down to c++ streams, conditional compilation, 3rd party frameworks, or something sort of portable that happens to work for you.
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Another (somewhat silly) option is to exploit the naturally recursive nature of JSON.stringify
, and pass it a replacer function which runs on each nested object during the stringification process:
const input = [{
'title': "some title",
'channel_id': '123we',
'options': [{
'channel_id': 'abc',
'image': 'http://asdasd.com/all-inclusive-block-img.jpg',
'title': 'All-Inclusive',
'options': [{
'channel_id': 'dsa2',
'title': 'Some Recommends',
'options': [{
'image': 'http://www.asdasd.com',
'title': 'Sandals',
'id': '1',
'content': {}
}]
}]
}]
}];
console.log(findNestedObj(input, 'id', '1'));
function findNestedObj(entireObj, keyToFind, valToFind) {
let foundObj;
JSON.stringify(entireObj, (_, nestedValue) => {
if (nestedValue && nestedValue[keyToFind] === valToFind) {
foundObj = nestedValue;
}
return nestedValue;
});
return foundObj;
};
_x000D_
I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).
<html>
<head>
<title>Ultan.me - Unset</title>
<script type="text/javascript">
function setTitle( text ) {
document.title = text;
}
</script>
<!-- other head info -->
</head>
<?php
// Make the call to the DB to get the title text. See OP post for example
$title_text = "Ultan.me - DB Title";
// Use body onload to set the title of the page
print "<body onload=\"setTitle( '$title_text' )\" >";
// Rest of your code here
print "<p>Either use php to print stuff</p>";
?>
<p>or just drop in and out of php</p>
<?php
// close the html page
print "</body></html>";
?>
I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session.
session_unset();
session_destroy();
Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:
GridLines="None"
CellSpacing="-1"
First off, see How Big can a Python Array Get? and Numpy, problem with long arrays
Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:
You can significantly speed up Git on Windows by running three commands to set some config options:
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256
Notes:
core.preloadindex
does filesystem operations in parallel to hide latency (update: enabled by default in Git 2.1)
core.fscache
fixes UAC issues so you don't need to run Git as administrator (update: enabled by default in Git for Windows 2.8)
gc.auto
minimizes the number of files in .git/
In addition to flup's answer you might also want to run the following to set JAVA_HOME and PATH:
sudo apt-get install oracle-java7-set-default
More information at: http://www.ubuntuupdates.org/package/webupd8_java/precise/main/base/oracle-java7-set-default
Just use the already built-in Contains() method:
using System.Linq;
//...
string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
//...
}
There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.
Just understand the difference between width:auto; and width:100%; Width:auto; will (AUTO)MATICALLY calculate the width in order to fit the exact given with of the wrapping div including the padding. Width 100% expands the width and adds the padding.
You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode
Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup
from setuptools
, not distutils
.
Yep. That should be right.
I don't think so. pyc
files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py
files leaving .pyc
files, but it wouldn't be recommended.
I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?
After much pain, and great assistance from @vitr et al above, i decided to try
and that worked.
ENV LISTEN_PORT=""
ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}
e.g.
docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image
and
docker run --rm -p 8080:80 -d my-image
both set the port correctly in my container
see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html
In my case that happened when uninstalling AspNet 5 RC1 Update 1 to update it for .Net Core 1.0 RC2. so I installed Visual Studio 2015 update 2, selected Microsoft Web Developer tools and everything went back to normal.
Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.
The solution that fixed mine was that I had inadvertently applied different keys to Encryption and Decryption methods.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
As using ListRow.Add
can be a huge bottle neck, we should only use it if it can’t be avoided.
If performance is important to you, use this function here to resize the table, which is quite faster than adding rows the recommended way.
Be aware that this will overwrite data below your table if there is any!
This function is based on the accepted answer of Chris Neilsen
Public Sub AddRowToTable(ByRef tableName As String, ByRef data As Variant)
Dim tableLO As ListObject
Dim tableRange As Range
Dim newRow As Range
Set tableLO = Range(tableName).ListObject
tableLO.AutoFilter.ShowAllData
If (tableLO.ListRows.Count = 0) Then
Set newRow = tableLO.ListRows.Add(AlwaysInsert:=True).Range
Else
Set tableRange = tableLO.Range
tableLO.Resize tableRange.Resize(tableRange.Rows.Count + 1, tableRange.Columns.Count)
Set newRow = tableLO.ListRows(tableLO.ListRows.Count).Range
End If
If TypeName(data) = "Range" Then
newRow = data.Value
Else
newRow = data
End If
End Sub
jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:
$('#comanda').hide();
One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):
$('#comanda').hide('fast');
In case you want to do something just after the element hid, you must provide a callback as a parameter too:
$('#comanda').hide('fast', function() {
alert('It is hidden now!');
});
You should try TextPad, it can read a file of that size.
It's free to evaluate (you can evaluate indefinitely)
Use htmlparser2, its way faster and pretty straightforward. Consult this usage example:
https://www.npmjs.org/package/htmlparser2#usage
And the live demo here:
Yes, you're looking for the ReDim
statement, which dynamically allocates the required amount of space in the array.
The following statement
Dim MyArray()
declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.
But you can use the ReDim
statement to resize the array:
ReDim MyArray(0 To 3)
And if you need to resize the array while preserving its contents, you can use the Preserve
keyword along with the ReDim
statement:
ReDim Preserve MyArray(0 To 3)
But do note that both ReDim
and particularly ReDim Preserve
have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.
However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim
at all. Just declare the array with explicit dimensions:
Dim MyArray(0 To 3)
There's a better way to handle it using Native MongoDB code in Mongoose.
exports.getUsers = function(req, res, next) {
var usersProjection = {
__v: false,
_id: false
};
User.find({}, usersProjection, function (err, users) {
if (err) return next(err);
res.json(users);
});
}
http://docs.mongodb.org/manual/reference/method/db.collection.find/
Note:
var usersProjection
The list of objects listed here will not be returned / printed.
Use position: relative on the parent element.
Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggeredrequest.method
, which will be "GET"
in this case, hence the app.get()
call.request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
You can close files not csv.writer object, it should be:
f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.
Here is information about all of the isolation levels at your disposal, as well as table hints.
I actually had the same problem with a completely new repository. I had even tried creating one with git checkout -b master
, but it would not create the branch. I then realized if I made some changes and committed them, git created my master branch.
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
You may be used to MySQL's syntax: Microsoft SQL @
is the same as the MySQL's ?
I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.
In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):
If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.
Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.
Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.
The last thing to close the puzzle is how will the Observable class know who is interested?
So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o)
internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.
It might be that in the interview they did not ask you explicitly about the java.util.Observer
and java.util.Observable
but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).
UPDATE
In response to your comment, the actual java.util.Observable
class offers the following facilities:
Maintaining a list of java.util.Observer
instances. New instances interested in being notified can be added through addObserver(Observer o)
, and removed through deleteObserver(Observer o)
.
Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable
has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged()
. So you just call it when you changed something to the Observable
and you want the rest of the Observers
to eventually know about it.
Notifying all observers that the specific Observable
has changed state. This is done through notifyObservers()
. This checks if the object has actually changed (i.e. a call to setChanged()
was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object
argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer
instances and calls the update(Observable o, Object arg)
method for each of them. This tells the Observer
which was the Observable object that changed (you could be observing more than one), and the extra Object arg
to potentially carry some extra information (passed through notifyObservers()
.
For the benefit of others like me who tried to follow the good advice here when accessing AWS CloudFront but failed, the trick is to add -servername domain.name..
.
I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.
array = []
array.append(temp[0])
Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.
ListView has the Item click listener callback. You should set the onItemClickListener
in the ListView
. Callback contains AdapterView
and position
as parameter. Which can give you the ListEntry
.
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = entry.getMessage();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
I have extended cletus proposed answer to working code example.
ExecutorService
(pes) accepts Producer
tasks.ExecutorService
(ces) accepts Consumer
tasks.Producer
and Consumer
shares BlockingQueue
.Producer
tasks generates different numbers.Consumer
tasks can consume number generated by Producer
Code:
import java.util.concurrent.*;
public class ProducerConsumerWithES {
public static void main(String args[]){
BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();
ExecutorService pes = Executors.newFixedThreadPool(2);
ExecutorService ces = Executors.newFixedThreadPool(2);
pes.submit(new Producer(sharedQueue,1));
pes.submit(new Producer(sharedQueue,2));
ces.submit(new Consumer(sharedQueue,1));
ces.submit(new Consumer(sharedQueue,2));
// shutdown should happen somewhere along with awaitTermination
/ * https://stackoverflow.com/questions/36644043/how-to-properly-shutdown-java-executorservice/36644320#36644320 */
pes.shutdown();
ces.shutdown();
}
}
class Producer implements Runnable {
private final BlockingQueue<Integer> sharedQueue;
private int threadNo;
public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) {
this.threadNo = threadNo;
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for(int i=1; i<= 5; i++){
try {
int number = i+(10*threadNo);
System.out.println("Produced:" + number + ":by thread:"+ threadNo);
sharedQueue.put(number);
} catch (Exception err) {
err.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private final BlockingQueue<Integer> sharedQueue;
private int threadNo;
public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) {
this.sharedQueue = sharedQueue;
this.threadNo = threadNo;
}
@Override
public void run() {
while(true){
try {
int num = sharedQueue.take();
System.out.println("Consumed: "+ num + ":by thread:"+threadNo);
} catch (Exception err) {
err.printStackTrace();
}
}
}
}
output:
Produced:11:by thread:1
Produced:21:by thread:2
Produced:22:by thread:2
Consumed: 11:by thread:1
Produced:12:by thread:1
Consumed: 22:by thread:1
Consumed: 21:by thread:2
Produced:23:by thread:2
Consumed: 12:by thread:1
Produced:13:by thread:1
Consumed: 23:by thread:2
Produced:24:by thread:2
Consumed: 13:by thread:1
Produced:14:by thread:1
Consumed: 24:by thread:2
Produced:25:by thread:2
Consumed: 14:by thread:1
Produced:15:by thread:1
Consumed: 25:by thread:2
Consumed: 15:by thread:1
Note. If you don't need multiple Producers and Consumers, keep single Producer and Consumer. I have added multiple Producers and Consumers to showcase capabilities of BlockingQueue among multiple Producers and Consumers.
JavaScript
function playAudio(url) {
new Audio(url).play();
}
HTML
<img src="image.png" onclick="playAudio('mysound.mp3')">
Supported in most modern browsers and easy to embed into HTML elements.
Note:
=""
is a blank cell) without a need to use data
twice. The solution for goolge-spreadhseet: =ARRAYFORMULA(SUM(IFERROR(IF(data="",0,1),1)))
. For excel ={SUM(IFERROR(IF(data="",0,1),1))}
should work (press Ctrl+Shift+Enter in the formula).I bet the problem is being shown in this line
SqlDataReader dr3 = com2.ExecuteReader();
I suggest that you execute the first reader and do a dr.Close();
and the iterate historicos
, with another loop, performing the com2.ExecuteReader()
.
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
conecta();
sql = "SELECT * FROM historico_verificacao_email WHERE nm_email = '" + email + "' ORDER BY dt_verificacao_email DESC, hr_verificacao_email DESC";
com = new SqlCommand(sql, conexao);
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
//System.Windows.Forms.MessageBox.Show(dados_historico[1]);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
dr.Close();
sql = "SELECT COUNT(e.cd_historico_verificacao_email) QT FROM emails_lidos e WHERE e.cd_historico_verificacao_email = '" + dr["cd_historico_verificacao_email"].ToString() + "'";
tipo_sql = "seleção";
com2 = new SqlCommand(sql, conexao);
for(int i = 0 ; i < historicos.Count() ; i++)
{
SqlDataReader dr3 = com2.ExecuteReader();
while (dr3.Read())
{
historicos[i][4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}
dr3.Close();
}
}
return historicos;
I still use the <center> tag sometimes because nothing in CSS works as well. Examples of trying to use a <div> trick and failing:
<div style="text-align: center;">This div is centered, but it's a simple example.</div>_x000D_
<br />_x000D_
<div style="text-align: center;"><table border="1"><tr><td><div style="text-align: center;"> didn't center correctly.</td></tr></table></div>_x000D_
<br />_x000D_
<div style="text-align: center;margin-left:auto;margin-right:auto"><table border="1"><tr><td><div style="text-align: center;margin-left:auto;margin-right:auto"> still didn't center either</td></tr></table></div>_x000D_
<br />_x000D_
<center><table border="1"><tr><td>Actually Centered with <center> tag</td></tr></table></center>
_x000D_
<center> gets results. To use CSS instead, you sometimes have to put CSS in several places and mess with it to get it to center right. To answer your question, CSS has become a religion with believers and followers who shunned <center> <b> <i> <u> as blasphemy, unholy, and much too simple for the sake of their own job security. And if they try to take your <table> away from you, ask them what the CSS equivalent of the colspan or rowspan attribute is.
It is not the abstract or bookish truth, but the lived truth that counts.
-- Zen
Microsoft also release the Microsoft Visual Studio 2015 Installer Projects Extension This is the same extension as the 2013 version but for Visual Studio 2015
&& x.DateTimeValueColumn <= DateTime.Now
This is supported so long as your schema is correct
&& x.DateTimeValueColumn.Value.Date <=DateTime.Now
You can use
DELETE from Table WHERE Date > CONVERT(VARCHAR, GETDATE(), 101);
I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:
public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {
// Vars
private LayoutInflater mInflater;
public GenericArrayAdapter(Context context, ArrayList<T> objects) {
super(context, 0, objects);
init(context);
}
// Headers
public abstract void drawText(TextView textView, T object);
private void init(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
drawText(vh.textView, getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
private ViewHolder(View rootView) {
textView = (TextView) rootView.findViewById(android.R.id.text1);
}
}
}
and here your adapter (example):
public class SizeArrayAdapter extends GenericArrayAdapter<Size> {
public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
super(context, objects);
}
@Override public void drawText(TextView textView, Size object) {
textView.setText(object.getName());
}
}
and finally, how to initialize it:
ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);
I've created a Gist with TextView layout gravity customizable ArrayAdapter:
First of all, you should be using json.loads
, not json.dumps
. loads
converts JSON source text to a Python value, while dumps
goes the other way.
After you fix that, based on the JSON snippet at the top of your question, readable_json
will be a list, and so readable_json['firstName']
is meaningless. The correct way to get the 'firstName'
field of every element of a list is to eliminate the playerstuff = readable_json['firstName']
line and change for i in playerstuff:
to for i in readable_json:
.
You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect
. You could then make a rule like this:
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to Category">
<match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="category.aspx?cid={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
you can use this one.
<div id="test"></div>
you java script code should be like that.
setInterval(function(){
$('#test').load('test.php');
},5000);
Yes (although it's a nasty hack). You can use a heredoc thus:
#!/bin/sh
# do valuable stuff here
touch /tmp/a
# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF
What's this doing ? A heredoc
feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with
echo <<EOF
...
EOF
and it'll take all the code contained between the two EOFs and feed them to echo
(echo
doesn't read from stdin so it all gets thrown away).
Note that with the above you can put anything in the heredoc
. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).
This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */
For me, The problem was solved after I close Visual Studio and Open it again
If you have a newer distro with a newer systemd
(systemd
version 236 or newer), you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
.
Long story:
In newer versions of systemd
there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
. The file:path
option is documented in the most recent systemd.exec
man page.
This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).
1 You can use a drawable
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item1"
android:icon="@drawable/my_item_drawable"
android:title="@string/menu_item1"
android:showAsAction="ifRoom" />
</menu>
2 Create a style for the action bar and use a custom background:
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/background</item>
<item name="android:backgroundStacked">@drawable/background</item>
<item name="android:backgroundSplit">@drawable/split_background</item>
</style>
</resources>
3 Style again android:actionBarDivider
The android documentation is very usefull for that.
Only one row code:
private static bool primeNumberTest(int i)
{
return i > 3 ? ( (Enumerable.Range(2, (i / 2) + 1).Where(x => (i % x == 0))).Count() > 0 ? false : true ) : i == 2 || i == 3 ? true : false;
}
"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."
Article at MSDN
deny = * means deny everyone
deny = ? means deny unauthenticated users
In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.
According to the docs, here is no difference in your 2 rule sets.
I was looking into the explanation " If you only override hashCode then when you call myMap.put(first,someValue)
it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(first,someOtherValue)
it should replace first with second as per the Map Documentation because they are equal (according to our definition)." :
I think 2nd time when we are adding in myMap
then it should be the 'second' object like myMap.put(second,someOtherValue)
Finalize
protected
, not public
or private
so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize
methodDispose
IDisposable
on every type that has a finalizerDispose
method. In other words, avoid using an object after the Dispose
method has been called on it.Dispose
on all IDisposable
types once you are done with themDispose
to be called multiple times without raising errors.Dispose
method using the GC.SuppressFinalize
methodDispose
methodsDispose/Finalized Pattern
Dispose
and Finalize
when working with unmanaged resources. The Finalize
implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose
method explicitly.Finalize
method as well as Dispose
method. Additionally call the Dispose
method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose
method.A few technically correct specific answers already provided but in general, it can be anywhere on the runtime classpath, i.e. wherever classes are sought by the JVM.
This could be the /src dir in Eclipse or the WEB-INF/classes directory in your deployed app, but it's best to be aware of the classpath concept and why the file is placed in it, don't just treat WEB-INF/classes as a "magic" directory.
Just because I haven't seen it here, if you are on MacOS or Linux, I suggest you add this to your PATH (in your bashrc etc):
node_modules/.bin
With this relative path entry, if you are sitting in the root folder of any node project, you can run any command line tool (eslint, gulp, etc. etc.) without worrying about "global installs" or npm run
etc.
Once I did this, I've never installed a module globally.
Check out the contents of your array with
echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';
Very old question but here's the solution. Here you have a working snippet using jquery
. It makes use of a temporary auxiliary select
into which the selected option from the main select is copied, such that one can assess the true width which the main select
should have.
$('select').change(function(){_x000D_
var text = $(this).find('option:selected').text()_x000D_
var $aux = $('<select/>').append($('<option/>').text(text))_x000D_
$(this).after($aux)_x000D_
$(this).width($aux.width())_x000D_
$aux.remove()_x000D_
}).change()
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option>ABC</option>_x000D_
<option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
</select>
_x000D_
Alternatively, you can give the "full location" to the database in your queries a la:
SELECT photo_id FROM [my database name].photogallery;
If using one more often than others, use USE
. Even if you do, you can still use the database.table
syntax.
For some reason when you try to check for a jquery DOM element it won't work properly. So rewriting the function would do the trick:
function isObjectInArray(array,obj){
for(var i = 0; i < array.length; i++) {
if($(obj).is(array[i])) {
return i;
}
}
return -1;
}
You're looking for itertools.compress
:
>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] #winner
100000 loops, best of 3: 1.98 us per loop
>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil)) #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop
>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil)) #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
100 loops, best of 3: 7.65 ms per loop
Don't use filter
as a variable name, it is a built-in function.
It's an argument passed to your success function:
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
The full signature is success(data, textStatus, XMLHttpRequest)
, but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)
JavaScript Minifier gives a good API you can use programatically:
curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw
Or by uploading a file and redirecting to a new file:
curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js
Hope that helps.
final
can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change
final
can also make a method not "overrideable"
public final String toString() { return "NULL"; }
final
can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed
finally
is used in a try/catch statement to execute code "always"
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable
finalize
is called when an object is garbage collected. You rarely need to override it. An example:
protected void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
You can use reduce() - A functional way.
words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})
returns:
{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.
This will simply solve your problem.
I've got this working after doing the following:
Note: This doesn't give me the runtime exceptions either, it works.
Sounds like you want a mirror of the remote repository:
git clone --mirror url://to/remote.git local.git
That command creates a bare repository. If you don't want a bare repository, things get more complicated.
You can do something like this, sharing my working code snippet
Make sure query is like this
DELETE FROM tableName WHERE KEY__NAME = 'parameterToMatch'
public void removeSingleFeedback(InputFeedback itemToDelete) {
//Open the database
SQLiteDatabase database = this.getWritableDatabase();
//Execute sql query to remove from database
//NOTE: When removing by String in SQL, value must be enclosed with ''
database.execSQL("DELETE FROM " + TABLE_FEEDBACKS + " WHERE "
+ KEY_CUSTMER_NAME + "= '" + itemToDelete.getStrCustName() + "'" +
" AND " + KEY_DESIGNATION + "= '" + itemToDelete.getStrCustDesignation() + "'" +
" AND " + KEY_EMAIL + "= '" + itemToDelete.getStrCustEmail() + "'" +
" AND " + KEY_CONTACT_NO + "= '" + itemToDelete.getStrCustContactNo() + "'" +
" AND " + KEY_MOBILE_NO + "= '" + itemToDelete.getStrCustMobile() + "'" +
" AND " + KEY_CLUSTER_NAME + "= '" + itemToDelete.getStrClusterName() + "'" +
" AND " + KEY_PRODUCT_NAME + "= '" + itemToDelete.getStrProductName() + "'" +
" AND " + KEY_INSTALL_VERSION + "= '" + itemToDelete.getStrInstalledVersion() + "'" +
" AND " + KEY_REQUIREMENTS + "= '" + itemToDelete.getStrRequirements() + "'" +
" AND " + KEY_CHALLENGES + "= '" + itemToDelete.getStrChallenges() + "'" +
" AND " + KEY_EXPANSION + "= '" + itemToDelete.getStrFutureExpansion() + "'" +
" AND " + KEY_COMMENTS + "= '" + itemToDelete.getStrComments() + "'"
);
//Close the database
database.close();
}
The simplest solution I have found is to change the background color programmatically. This does not require dealing with any 9-patch images:
((EditText) findViewById(R.id.id_nick_name)).getBackground()
.setColorFilter(Color.<your-desi??red-color>, PorterDuff.Mode.MULTIPLY);
Source: another answer
There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html
It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.
You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder
object that contains an exportWAV
method, and a forceDownload
method.
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
A good thing to remember are these simple rules, and they apply to both parameters and return types...
There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int*
and returning &i
would have been equally incorrect. You would be better off in that case doing this...
void func1(int& oValue)
{
oValue = 1;
}
Doing so would directly change the value of your passed in parameter. Whereas this code...
void func1(int oValue)
{
oValue = 1;
}
would not. It would just change the value of oValue
local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue
, and not oValue
itself.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
I'd highly recommend jQuery. It then becomes as simple as:
$('#mydiv').addClass('newclass');
You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();
The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.
$('div').addClass('newclass');
$('.oldclass').addClass('newclass');
The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.
Try this one
UPDATE employee
set EMPLOYEE.MAIDEN_NAME =
(SELECT ADD1
FROM EMPS
WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00'
AND EMPLOYEE.EMP_CODE <='ZZ';
You can use
moment(date,"currentFormat").format("requiredFormat");
This should be used when date is not ISO Format as it'll tell moment what our current format is.
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
Math.Floor() :
It gives the largest integer less than or equal to the given number.
Math.Floor(3.45) =3
Math.Floor(-3.45) =-4
Math.Truncate():
It removes the decimal places of the number and replace with zero
Math.Truncate(3.45)=3
Math.Truncate(-3.45)=-3
Also from above examples we can see that floor and truncate are same for positive numbers.
As explained above, you can use the Firebase default push id.
If you want something numeric you can do something based on the timestamp to avoid collisions
f.e. something based on date,hour,second,ms, and some random int at the end
01612061353136799031
Which translates to:
016-12-06 13:53:13:679 9031
It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.
You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.
(https://firebase.google.com/docs/database/android/read-and-write)
I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:
// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);
// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);
function mapDOM(element, json) {
var treeObject = {};
// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element,"text/xml");
} else { // Microsoft strikes again
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}
//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object["content"] = [];
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].nodeType == 3) {
object["content"].push(nodeList[i].nodeValue);
} else {
object["content"].push({});
treeHTML(nodeList[i], object["content"][object["content"].length -1]);
}
}
}
}
if (element.attributes != null) {
if (element.attributes.length) {
object["attributes"] = {};
for (var i = 0; i < element.attributes.length; i++) {
object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
}
}
}
}
treeHTML(element, treeObject);
return (json) ? JSON.stringify(treeObject) : treeObject;
}
Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).
?It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify()
which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.
It can take either a DOM element or a string
containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser()
will choke in certain situations as it is set to "text/xml"
or whether it just doesn't provide error handling. Unfortunately "text/html"
has poor browser support).
You can easily change the range of this function by passing a different value as element
. Whatever value you pass will be the root of your JSON map.
It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:
http://www.youtube.com/watch?v=y1c7WFMMkZ4
When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.
What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.
flex
and inline-flex
both apply flex layout to children of the container. Container with display:flex
behaves like a block-level element itself, while display:inline-flex
makes the container behaves like an inline element.
[HttpPost]
public ActionResult SaveComments(int id, string comments){
var actions = new Actions(User.Identity.Name);
var status = actions.SaveComments(id, comments);
return Content(status);
}
If it's a string that you trust meaning that you have checked it before hand then the following would also work.
$date = new DateTime('2015-03-27');
Assuming you want to replace the newlines with something so that something like this:
the quick brown fox\r\n
jumped over the lazy dog\r\n
doesn't end up like this:
the quick brown foxjumped over the lazy dog
I'd do something like this:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.
It is possible to do with CSS only by selecting active and focus pseudo element of the button.
button:active{
background:olive;
}
button:focus{
background:olive;
}
See codepen: http://codepen.io/fennefoss/pen/Bpqdqx
You could also write a simple jQuery click function which changes the background color.
HTML:
<button class="js-click">Click me!</button>
CSS:
button {
background: none;
}
JavaScript:
$( ".js-click" ).click(function() {
$( ".js-click" ).css('background', 'green');
});
Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG
First of all, check out my post on retained Fragments. It might help.
Now to answer your questions:
Does the fragment also retain its
viewstate, or will this be recreated on configuration change - what exactly is "retained"?
Yes, the Fragment
's state will be retained across the configuration change. Specifically, "retained" means that the fragment will not be destroyed on configuration changes. That is, the Fragment
will be retained even if the configuration change causes the underlying Activity
to be destroyed.
Will the fragment be destroyed when the user leaves the activity?
Just like Activity
s, Fragment
s may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy the Fragment
s once you leave the Activity
. If you leave the Activity
(i.e. by pressing the home button), the Fragment
s may or may not be destroyed. If you leave the Activity
by pressing the back button (thus, calling finish()
and effectively destroying the Activity
), all of the Activity
s attached Fragment
s will also be destroyed.
Why doesn't it work with fragments on the back stack?
There are probably multiple reasons why it's not supported, but the most obvious reason to me is that the Activity
holds a reference to the FragmentManager
, and the FragmentManager
manages the backstack. That is, no matter if you choose to retain your Fragment
s or not, the Activity
(and thus the FragmentManager
's backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.
Which are the use cases where it makes sense to use this method?
Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread
or AsyncTask
, managing its operation. See my blog post on this topic for more information.
In general, I would treat it similarly to using onConfigurationChanged
with an Activity
... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.
An application bundle (a .app
file) is actually a bunch of directories. Instead of using open
and the .app
name, you can actually move in to it and start the actual binary. For instance:
$ cd /Applications/LittleSnapper.app/
$ ls
Contents
$ cd Contents/MacOS/
$ ./LittleSnapper
That is the actual binary that might accept arguments (or not, in LittleSnapper
's case).
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")
z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)
w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis
It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.
Also check out http://www.sagekey.com/installation_access.aspx for great installation scripts for Ms Access. Also if you need to integrate images into your application check out DBPix at ammara.com
You can install nano in powershell via choco - It's a low friction way to get text editing capabilities into powershell:
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco install nano
nano myfile.txt
Best part is it becomes part of the path, and stays working across reboots etc :)
Assuming you wanted to overwrite the previous value of the object referred to by a
, then a member function would have to be invoked.
Complex a, b, c;
// ...
a = b.add(c);
In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and copy the resultant value from the temporary object into the existing object a
.
However, in Java, operator=
doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named Complex
, assignment means to copy a reference to an existing value.
Consider instead:
b.set(1, 0); // initialize to real number '1'
a = b;
b.set(2, 0);
assert( !a.equals(b) ); // this assertion will fail
In C++, this copies the value, so the comparison will result not-equal. In Java, operator=
performs reference copy, so a
and b
are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.
The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+
would likely deal with values and objects, but operator=
is already implemented to deal with references.
In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex
, operator=
and operator==
are both working on values -- copying values and comparing values respectively.
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
To pause for 0.8 of a second:
Sub main()
startTime = Timer
Do
Loop Until Timer - startTime >= 0.8
End Sub
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
I have resolved the same problem using the below code:
String query = "SELECT violationDate, COUNT(*) as date " +
"FROM challan " +
"WHERE challanType = '" + type + "' GROUP BY violationDate";
Here violationDate and date are two columns of the result table. date column will return occurrence.
cr.getInt(1)
As explained @Yaroslav Stavnichiy if a service is marked as transactional spring tries to handle transaction itself. If any exception occurs then a rollback operation performed. If in your scenario ServiceUser.method() is not performing any transactional operation you can use @Transactional.TxType annotation. 'NEVER' option is used to manage that method outside transactional context.
Transactional.TxType reference doc is here.
Simply set the logo's style to display:hidden
and call fadeIn
, instead of first calling hide
:
$(document).ready(function() {
$('#logo').fadeIn("normal");
});
<img src="logo.jpg" style="display:none"/>
A CharSequence
is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence
is an umbrella for various types of text strings. Here are some of the common ones:
String
(immutable text with no styling spans)StringBuilder
(mutable text with no styling spans)SpannableString
(immutable text with styling spans)SpannableStringBuilder
(mutable text with styling spans)(You can read more about the differences between these here.)
If you have a CharSequence
object, then it is actually an object of one of the classes that implement CharSequence
. For example:
CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();
The benefit of having a general umbrella type like CharSequence
is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence
as a parameter, I could pass in a String
or a SpannableStringBuilder
and it would handle either one.
public int getLength(CharSequence text) {
return text.length();
}
You could say that a String
is just one kind of CharSequence
. However, unlike CharSequence
, it is an actual class, so you can make objects from it. So you could do this:
String myString = new String();
but you can't do this:
CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated
Since CharSequence
is just a list of rules that String
conforms to, you could do this:
CharSequence myString = new String();
That means that any time a method asks for a CharSequence
, it is fine to give it a String
.
String myString = "hello";
getLength(myString); // OK
// ...
public int getLength(CharSequence text) {
return text.length();
}
However, the opposite is not true. If the method takes a String
parameter, you can't pass it something that is only generally known to be a CharSequence
, because it might actually be a SpannableString
or some other kind of CharSequence
.
CharSequence myString = "hello";
getLength(myString); // error
// ...
public int getLength(String text) {
return text.length();
}
List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
if(s.equals(value)){
//do something
}
}
or
for (int i = 0; i < arrayList.size(); i++) {
if(arrayList.get(i).equals(value)){
//do something
}
}
But be carefull ArrayList can hold null values. So comparation should be
value.equals(arrayList.get(i))
when you are sure that value is not null or you should check if given element is null.
I faced same issue when I ran following commands
vagrant init
vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'base' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'base' (v0) for provider: virtualbox
default: Downloading: base
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.
Couldn't open file /home/...../base
I corrected with
>vagrant init laravel/homestead
>Vagrant up
It worked for me.
Happy coding
.find_all()
returns list of all found elements, so:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
output = input_tag[0]['value']
or use .find()
method which returns only one (first) found element:
input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']
Another simpler way is while you are editing a file - tabe ~/.vim/colors/
ENTER
Will open all the themes in a new tab within vim window.
You may come back to the file you were editing using - CTRL + W + W
ENTER
Note: Above will work ONLY IF YOU HAVE a .vim/colors
directory within your home directory for current $USER
(I have 70+ themes)
[user@host ~]$ ls -l ~/.vim/colors | wc -l
72
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* @param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* @param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* @param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* @param conn
* - the connection to use for the script
* @param reader
* - the source of the script
* @throws SQLException
* if any SQL errors occur
* @throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
Well this is simple answer you want.
MaterialApp(
debugShowCheckedModeBanner: false
)
But if you want to go deep with app (Want a release apk (which don't have debug banner) and if you are using android studio then go to
Run -> Flutter Run 'main.dart' in Relese mode
I found I was missing the WebApplications folder on my local PC, did not install with Visual Studio 2017 like it had when I was using 2012.
I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.
-- Loan Outstanding
select 'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
from
(
select
sum(laod.dr) as Unit,
sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
from loan_account_opening as lao
inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
where lao.organization = 3
union
select
sum(lr.installment)*-1 as Unit,
sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
from loan_recovery as lr
inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
where lo.organization = 3
) as t3
You can query sqlite_master
SELECT sql FROM sqlite_master WHERE name='foo';
which will return a create table
SQL statement, for example:
$ sqlite3 mydb.sqlite
sqlite> create table foo (id int primary key, name varchar(10));
sqlite> select sql from sqlite_master where name='foo';
CREATE TABLE foo (id int primary key, name varchar(10))
sqlite> .schema foo
CREATE TABLE foo (id int primary key, name varchar(10));
sqlite> pragma table_info(foo)
0|id|int|0||1
1|name|varchar(10)|0||0
I had similar issue. In my case it helped to have Yarn installed and first execute the command
yarn
and then execute the command
yarn start
That could work for you too if the project that you cloned have the yarn.lock file. Hope it helps!
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
Thanks a bundle, guys. You are great.
I used Chuff's answer and modified it a little to do what I wanted.
I have 2 worksheets in the same workbook.
On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message
Then I inserted a new blank column next to the phone number
On worksheet 2 I have two columns: phone number, name of person
Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.
Then just copy the formula down the whole column until last sms It worked beautifully.
=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)
The Why
java.util.logging has a root logger that defaults to Level.INFO
, and a ConsoleHandler attached to it that also defaults to Level.INFO
.
FINE
is lower than INFO
, so fine messages are not displayed by default.
Solution 1
Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal()
, and hook your own ConsoleLogger to it.
Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.
public static final Logger applog = Logger.getGlobal();
...
// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );
// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2
Solution 2
Alternatively, you may lower the root logger's bar.
You can set them by code:
Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler
Or with logging configuration file, if you are using it:
.level = FINE
java.util.logging.ConsoleHandler.level = FINE
By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.
Update
S3 now offers a fully-managed SFTP Gateway Service for S3 that integrates with IAM and can be administered using aws-cli.
There are theoretical and practical reasons why this isn't a perfect solution, but it does work...
You can install an FTP/SFTP service (such as proftpd) on a linux server, either in EC2 or in your own data center... then mount a bucket into the filesystem where the ftp server is configured to chroot, using s3fs.
I have a client that serves content out of S3, and the content is provided to them by a 3rd party who only supports ftp pushes... so, with some hesitation (due to the impedance mismatch between S3 and an actual filesystem) but lacking the time to write a proper FTP/S3 gateway server software package (which I still intend to do one of these days), I proposed and deployed this solution for them several months ago and they have not reported any problems with the system.
As a bonus, since proftpd can chroot each user into their own home directory and "pretend" (as far as the user can tell) that files owned by the proftpd user are actually owned by the logged in user, this segregates each ftp user into a "subdirectory" of the bucket, and makes the other users' files inaccessible.
There is a problem with the default configuration, however.
Once you start to get a few tens or hundreds of files, the problem will manifest itself when you pull a directory listing, because ProFTPd will attempt to read the .ftpaccess
files over, and over, and over again, and for each file in the directory, .ftpaccess
is checked to see if the user should be allowed to view it.
You can disable this behavior in ProFTPd, but I would suggest that the most correct configuration is to configure additional options -o enable_noobj_cache -o stat_cache_expire=30
in s3fs:
-o stat_cache_expire
(default is no expire)specify expire time(seconds) for entries in the stat cache
Without this option, you'll make fewer requests to S3, but you also will not always reliably discover changes made to objects if external processes or other instances of s3fs are also modifying the objects in the bucket. The value "30" in my system was selected somewhat arbitrarily.
-o enable_noobj_cache
(default is disable)enable cache entries for the object which does not exist. s3fs always has to check whether file(or sub directory) exists under object(path) when s3fs does some command, since s3fs has recognized a directory which does not exist and has files or subdirectories under itself. It increases ListBucket request and makes performance bad. You can specify this option for performance, s3fs memorizes in stat cache that the object (file or directory) does not exist.
This option allows s3fs to remember that .ftpaccess
wasn't there.
Unrelated to the performance issues that can arise with ProFTPd, which are resolved by the above changes, you also need to enable -o enable_content_md5
in s3fs.
-o enable_content_md5
(default is disable)verifying uploaded data without multipart by content-md5 header. Enable to send "Content-MD5" header when uploading a object without multipart posting. If this option is enabled, it has some influences on a performance of s3fs when uploading small object. Because s3fs always checks MD5 when uploading large object, this option does not affect on large object.
This is an option which never should have been an option -- it should always be enabled, because not doing this bypasses a critical integrity check for only a negligible performance benefit. When an object is uploaded to S3 with a Content-MD5:
header, S3 will validate the checksum and reject the object if it's corrupted in transit. However unlikely that might be, it seems short-sighted to disable this safety check.
Quotes are from the man page of s3fs. Grammatical errors are in the original text.
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
Normally, mutt sets the From:
header based on the from
configuration variable you set in ~/.muttrc
:
set from="Fubar <foo@bar>"
If this is not set, mutt
uses the EMAIL
environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):
EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"
However, if you want to be able to edit the From:
header while composing, you need to configure mutt
to allow you to edit headers first. This involves adding the following line in your ~/.muttrc
:
set edit_headers=yes
After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From:
header.
Found in a google discussion group. Works for me.
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$compile(element)($rootScope);
});
Use command line and not python.
TLDR; On Windows, do:
python -m pip --version
OR
py -m pip --version
Details:
On Windows, ~> (open windows terminal)
Start (or Windows Key) > type "cmd" Press Enter
You should see a screen that looks like this
To check to see if pip is installed.
python -m pip --version
if pip is installed, go ahead and use it. for example:
Z:\>python -m pip install selenium
if not installed, install pip, and you may need to
add its path to the environment variables. (basic - windows)
add path to environment variables (basic+advanced)
if python is NOT installed you will get a result similar to the one below
Install python. add its path to environment variables.
UPDATE: for newer versions of python replace "python" with py - see @gimmegimme's comment and link https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture
property to change the culture of an AppDomain.
For versions prior to 4.5 you have to use reflection to manipulate the culture of an AppDomain. There is a private static field on CultureInfo
(m_userDefaultCulture
in .NET 2.0 mscorlib, s_userDefaultCulture
in .NET 4.0 mscorlib) that controls what CurrentCulture
returns if a thread has not set that property on itself.
This does not change the native thread locale and it is probably not a good idea to ship code that changes the culture this way. It may be useful for testing though.
You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.
here you go.
<img src="https://i.imgur.com/7KpCS0Y.jpg" onclick="window.open(this.src)">
var ref = new Firebase('https://your.firebaseio.com/');
Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
Movie movie = dataSnapshot.getValue(Movie.class);
if (movie.getLead().equals('Jack Nicholson')) {
console.log(movieSnapshot.getKey());
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
The following is applicable for docker-compose 3.x Set environment variables inside the container
method - 1 Straight method
web:
environment:
- DEBUG=1
POSTGRES_PASSWORD: 'postgres'
POSTGRES_USER: 'postgres'
method - 2 The “.env” file
Create a .env file in the same location as the docker-compose.yml
$ cat .env
TAG=v1.5
POSTGRES_PASSWORD: 'postgres'
and your compose file will be like
$ cat docker-compose.yml
version: '3'
services:
web:
image: "webapp:${TAG}"
postgres_password: "${POSTGRES_PASSWORD}"
You are using USCOUNTER
in a subshell, that's why the variable is not showing in the main shell.
Instead of cat FILE | while ...
, do just a while ... done < $FILE
. This way, you avoid the common problem of I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?:
while read country _; do
if [ "US" = "$country" ]; then
USCOUNTER=$(expr $USCOUNTER + 1)
echo "US counter $USCOUNTER"
fi
done < "$FILE"
Note I also replaced the `` expression with a $().
I also replaced while read line; do country=$(echo "$line" | cut -d' ' -f1)
with while read country _
. This allows you to say while read var1 var2 ... varN
where var1
contains the first word in the line, $var2
and so on, until $varN
containing the remaining content.
Be careful, with COUNT
your first item in the bag must not be null. Else you can use the function COUNT_STAR
to count all rows.
In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.
For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).
Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.
If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:
// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
var modal = $('#modal'), modalBody = $('#modal .modal-body');
modal
.on('show.bs.modal', function () {
modalBody.load(e.currentTarget.href)
})
.modal();
e.preventDefault();
});
This is how you can use the self inside the block:
//calling of the block
NSString *returnedText= checkIfOutsideMethodIsCalled(self);
NSString* (^checkIfOutsideMethodIsCalled)(*)=^NSString*(id obj)
{
[obj MethodNameYouWantToCall]; // this is how it will call the object
return @"Called";
};
In 2020 you can listen state changes with useEffect hook like this
export function MyComponent(props) {
const [myState, setMystate] = useState('initialState')
useEffect(() => {
console.log(myState, '- Has changed')
},[myState]) // <-- here put the parameter to listen
}
Another approach is using UnboundID. Its api is very readable and shorter
Create a Ldap Connection
public static LDAPConnection getConnection() throws LDAPException {
// host, port, username and password
return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}
Get filter result
public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
SearchResult searchResult;
if (connection.isConnected()) {
searchResult = connection.search(baseDN, SearchScope.ONE, filter);
return searchResult.getSearchEntries();
}
return null;
}
Get all Oragnization Units and Containers
String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";
LDAPConnection connection = getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);
Get a specific Organization Unit
String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";
String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);
LDAPConnection connection = getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);
Get all users under an Organizational Unit
String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";
LDAPConnection connection = getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);
Get a specific user under an Organization Unit
String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";
String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);
LDAPConnection connection = getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);
Display result
for (SearchResultEntry e : results) {
System.out.println("name: " + e.getAttributeValue("name"));
}
This works at the moment (Oct. 2016), but I can't guarantee how long it will last:
https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]
Use Resizemode with 'cover' or 'contain' and set the height and with of the Image.
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Can do this, But not really necessary
Jason Lee got the answer. When installing xCode I preferred keeping previous installations rather than replacing them. So I have these in my installation Folder
So /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Contain different sdks. (Replace Xcode.app with correct number) copy previous sdks to
/Applications/Xcode 3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Here is my folder after I copied one.
Now restart xCode and you can set previous versions of sdks as base sdk.
Refering Apple Documentaion
To use a particular SDK for an Xcode project, make two selections in your project’s build settings.
Choose a deployment target.
This identifies the earliest OS version on which your software can run.
Choose a base SDK
Your software can use features available in OS versions up to and including the one corresponding to the base SDK. By default , Xcode sets this to the newest OS supported by Xcode.
For example you can use iOS 7 as base sdk and set iOS 6 as deployment target. Run on iOS 6 simulator to test how it works on iOS 6. Install simulator if not available with list of simulators.
Additionaly You can unconditionally use features upto iOS 6. And Conditionally you can support new features of iOS 7 for new updated devices while supporting previous versions.
This can be done using Weakly Linked Classes ,Weakly Linked Methods, Functions, and Symbols
Suppose in Xcode you set the deployment target (minimum required version) to iOS6 and the target SDK (maximum allowed version) to iOS7. During compilation, the compiler would weakly link any interfaces that were introduced in iOS7 while strongly linking earlier interfaces. This would allow your application to continue running on iOS6 but still take advantage of newer features when they are available.
You can simply run
kubectl delete all --all --all-namespaces
The first all
means the common resource kinds (pods, replicasets, deployments, ...)
kubectl get all == kubectl get pods,rs,deployments, ...
The second --all
means to select all resources of the selected kinds
Note that all
does not include:
In order to clean up perfectly,
In Swift use
mapView.showAnnotations(annotationArray, animated: true)
In Objective c
[mapView showAnnotations:annotationArray animated:YES];
To expand on others' answers, here is a compact solution that doesn't expose/add any new variables. It doesn't cover all bases, but it should suit most people who just want a single page app to remain functional (despite no data persistence after reload).
(function(){
try {
localStorage.setItem('_storage_test', 'test');
localStorage.removeItem('_storage_test');
} catch (exc){
var tmp_storage = {};
var p = '__unique__'; // Prefix all keys to avoid matching built-ins
Storage.prototype.setItem = function(k, v){
tmp_storage[p + k] = v;
};
Storage.prototype.getItem = function(k){
return tmp_storage[p + k] === undefined ? null : tmp_storage[p + k];
};
Storage.prototype.removeItem = function(k){
delete tmp_storage[p + k];
};
Storage.prototype.clear = function(){
tmp_storage = {};
};
}
})();
The ONLY thing that worked for me was html.
And I found it to be the far easier to do than any of the programmatic approaches.
The following code changes the text color based on a parameter passed by a caller.
enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
QTextCursor cursor = ui->messages->textCursor();
QString alertHtml = "<font color=\"DeepPink\">";
QString notifyHtml = "<font color=\"Lime\">";
QString infoHtml = "<font color=\"Aqua\">";
QString endHtml = "</font><br>";
switch(level)
{
case msg_alert: line = alertHtml % line; break;
case msg_notify: line = notifyHtml % line; break;
case msg_info: line = infoHtml % line; break;
default: line = infoHtml % line; break;
}
line = line % endHtml;
ui->messages->insertHtml(line);
cursor.movePosition(QTextCursor::End);
ui->messages->setTextCursor(cursor);
}
To understand this question, you must first understand what SHA256 is. SHA256 is a Cryptographic Hash Function. A Cryptographic Hash Function is a one-way function, whose output is cryptographically secure. This means it is easy to compute a hash (equivalent to encrypting data), but hard to get the original input using the hash (equivalent to decrypting the data). Since using a Cryptographic hash function means decrypting is computationally infeasible, so therefore you cannot perform decryption with SHA256.
What you want to use is a two-way function, but more specifically, a Block Cipher. A function that allows for both encryption and decryption of data. The functions mcrypt_encrypt
and mcrypt_decrypt
by default use the Blowfish algorithm. PHP's use of mcrypt can be found in this manual. A list of cipher definitions to select the cipher mcrypt uses also exists. A wiki on Blowfish can be found at Wikipedia. A block cipher encrypts the input in blocks of known size and position with a known key, so that the data can later be decrypted using the key. This is what SHA256 cannot provide you.
$key = 'ThisIsTheCipherKey';
$ciphertext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, 'This is plaintext.', MCRYPT_MODE_CFB);
$plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $encrypted, MCRYPT_MODE_CFB);
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
It seems to based on advertisement data, particularly the manufacturer data:
4C00 02 15 585CDE931B0142CC9A1325009BEDC65E 0000 0000 C5
<company identifier (2 bytes)> <type (1 byte)> <data length (1 byte)>
<uuid (16 bytes)> <major (2 bytes)> <minor (2 bytes)> <RSSI @ 1m>
I have this node.js script working on Linux with the sample AirLocate app example.
As of rails 5
you can also use rails
instead of rake
Rails 3 - 4
# < rails-5.0
rake db:migrate:up VERSION=20160920130051
Rails 5
# >= rails-5.0
rake db:migrate:up VERSION=20160920130051
# or
rails db:migrate:up VERSION=20160920130051
After installing pytorch, I got a similar error when I used:
import torch
Removing NumPy didn't help (I actually renamed NumPy, so I reverted back after it didn't work). The following commands worked for me:
sudo pip install numpy --upgrade
sudo easy_install numpy
If unwanted files were added to the staging area but not yet committed, then a simple reset will do the job:
$ git reset HEAD file
# Or everything
$ git reset HEAD .
To only remove unstaged changes in the current working directory, use:
git checkout -- .
I solved this error using the bellow i get it from here
ionic cordova run browser
will load those native plugins that support browser
platform.
We can access super class elements by using super keyword
Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.
class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
Here is an article that takes a different approach to resizing. It will attempt to load the largest possible bitmap into memory based on available memory in the process and then perform the transforms.
http://bricolsoftconsulting.com/2012/12/07/handling-large-images-on-android/
This is working for me using this Bootsrap Datetimepiker, it returns the value as it is shown in the datepicker input, e.g. 2019-04-11
$('#myDateTimePicker').on('click,focusout', function (){
var myDate = $("#myDateTimePicker").val();
//console.log(myDate);
//alert(myDate);
});
Given List<MyType1> internalUsers
and List<MyType2> externalUsers
, based on the shared key of an email address...
For C# 7.0+:
var matches = (
from i in internalUsers
join e in externalUsers
on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
select (internalUser:i, externalUser:e)
).ToList();
Which gives you matches
as a List<(MyType1, MyType2)>
.
From there you can compare them if you wish:
var internal_in_external = matches.Select(m => m.internalUser).ToList();
var external_in_internal = matches.Select(m => m.externalUser).ToList();
var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();
internal_in_external
and internal_notIn_external
will be of type List<MyType1>
.
external_in_internal
and external_notIn_internal
will be of type List<MyType2>
For versions of C# prior to 7.0:
var matches = (
from i in internalUsers
join e in externalUsers
on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
select new Tuple<MyType1, MyType2>(i, e)
).ToList();
Which gives you matches
as a List<Tuple<MyType1, MyType2>>
.
From there you can compare them if you wish:
var internal_in_external = matches.Select(m => m.Item1).ToList();
var external_in_internal = matches.Select(m => m.Item2).ToList();
var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();
internal_in_external
and internal_notIn_external
will be of type List<MyType1>
.
external_in_internal
and external_notIn_internal
will be of type List<MyType2>
Answer from here, works in both phantomjs and in email-embedded HTML:
Lorem ipsum <sup style="font-size: 8px; line-height: 0; vertical-align: 3px">®</sup>
_x000D_
Simply use SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);
The result is: Sat, 28 Dec 2013
The default constructor is taking "the default" Locale, so be careful using it when you need a specific pattern.
public SimpleDateFormat(String pattern) {
this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
Call sys.exit
.
head
takes the first lines from a file, and the -n
parameter can be used to specify how many lines should be extracted:
line=$(head -n 1 filename)
I had the problem when I wrote "if - fi" statement in one line:
if [ -f ~/.git-completion.bash ]; then . ~/.git-completion.bash fi
Write multiline solved my problem:
if [ -f ~/.git-completion.bash ]; then
. ~/.git-completion.bash
fi
l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
def Test(l):
global count
if len(l)==0:
return count
count=l.count("feto")
for i in l:
if type(i) is list:
count+=Test(i)
return count
print(Test(l2))
this will recursive count or search for the item in the list even if it in list of lists