Use fabs() instead of abs(), it's the same but for floats instead of integers.
Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.
This error is from google security... This Can Be Resolved by Enabling Less Secure .
Go To This Link : "https://www.google.com/settings/security/lesssecureapps" and Make "TURN ON" then your application runs For Sure.
Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:
const res_data = JSON.parse(body);
There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.
The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.
Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.
public function updtitle()
{
$data = array(
'table_name' => 'your_table_name_to_update', // pass the real table name
'id' => $this->input->post('id'),
'title' => $this->input->post('title')
);
$this->load->model('Updmodel'); // load the model first
if($this->Updmodel->upddata($data)) // call the method from the model
{
// update successful
}
else
{
// update not successful
}
}
public function upddata($data) {
extract($data);
$this->db->where('emp_no', $id);
$this->db->update($table_name, array('title' => $title));
return true;
}
The active record query is similar to
"update $table_name set title='$title' where emp_no=$id"
If you know the (maximum) number of rows and columns beforehand, you can use resize()
to initialize a vector of vectors and then modify (and access) elements with operator[]
. Example:
int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;
std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));
// Read from matrix.
int value = matrix[1][2];
// Save to matrix.
matrix[3][1] = 5;
Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column]
.
The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.
SELECT country.name, country.headofstate
FROM country
WHERE country.headofstate LIKE 'A%' AND
country.id in (SELECT country_id FROM city WHERE population > 100000)
Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?
I had the same issue after migrating to a new environment and it was simply that the server didn't run mod_rewrite
a quick sudo a2enmod rewrite
then sudo systemctl restart apache2
and problem solved...
Thanks @fanis who pointed that out in his comment on the question.
As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to https://github.com/psevon/exceptions-and-raii-in-c This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly.
You can also configure your component like this :
package mypackage;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConstructorClassConfig {
@Bean
public MyConstructorClass myConstructorClass(){
return new myConstructorClass("foobar");
}
}
}
With the Bean
annotation, you are telling Spring to register the returned bean in the BeanFactory
.
So you can autowire it as you wish.
Microsoft Core Library, ie they are at the heart of everything.
There is a more "massaged" explanation you may prefer:
"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."
From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx
Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.
Minimal runnable example
main.cpp
#include <cassert>
class C {
public:
int i;
C(int i) : i(i) {}
int m(int j) { return this->i + j; }
};
int main() {
// Get a method pointer.
int (C::*p)(int) = &C::m;
// Create a test object.
C c(1);
C *cp = &c;
// Operator .*
assert((c.*p)(2) == 3);
// Operator ->*
assert((cp->*p)(2) == 3);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Tested in Ubuntu 18.04.
You cannot change the order of the parenthesis or omit them. The following do not work:
c.*p(2)
c.*(p)(2)
GCC 9.2 would fail with:
main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
19 | assert(c.*p(2) == 3);
|
C++11 standard
.*
and ->*
are a single operators introduced in C++ for this purpose, and not present in C.
.*
and ->*
.Following solution is working fine.
HTML:
<table>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
</table>
JQuery:
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
I have done bins on http://codebins.com/bin/4ldqpa9
It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:
<html>
<head>
<meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
</head>
<body>
<div>HEADER - use 2 fingers to scroll contents:</div>
<div id="scrollee" style="height:75%;" >
<object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
</div>
<div>FOOTER</div>
</body>
</html>
Just made autocrlf
param in .gitconfig file false
and recloned the code. It worked!
[core]
autocrlf = false
I received the same error when trying to clone a heroku git repository.
Upon accessing heroku dashboard I saw a warning that the tool was under maintenance, and should come back in a few hours.
Cloning into 'foo-repository'...
remote: ! Heroku has temporarily disabled this feature, please try again shortly. See https://status.heroku.com for current Heroku platform status.
fatal: unable to access 'https://git.heroku.com/foo-repository.git/': The requested URL returned error: 503
If you receive the same error, check the service status
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
Disabling and Enabling the Developer options and debug mode on the Android phone settings fixed the issue.
for UNIX time-stamp in milliseconds
moment().format('x') // lowerCase x
for UNIX time-stamp in seconds
moment().format('X') // capital X
The :query_string_normalizer
option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
my problem (git on macOS) was solved by using
sudo git
instead of just git
in all add
and commit
commands
You can use the MouseClicked
event:
private void tableMouseClicked(java.awt.event.MouseEvent evt) {
// Do something.
}
On some system, instead of the .bashrc file, you can edit your profils' specific by editing:
sudo nano /etc/profile
..... Toast t = Toast.makeText(context, "try... " , Toast.LENGTH_SHORT); t.show();
Cursor callInitCheck = db.rawQuery("select count(*) from call", null);
Toast t2a = Toast.makeText(context, "count rows " + callInitCheck.getCount() , Toast.LENGTH_SHORT);
t2a.show();
callInitCheck.moveToNext();
if( Integer.parseInt( callInitCheck.getString(0)) == 0) // if no rows then do
{
// if empty then insert into call
.....
A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.
Being a void element, an <input>
element is considered empty by the HTML definition of "empty", since the content model of all void elements is always empty. So they will always match the :empty
pseudo-class, whether or not they have a value. This is also why their value is represented by an attribute in the start tag, rather than text content within start and end tags.
Also, from the Selectors spec:
The
:empty
pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;
Consequently, input:not(:empty)
will never match anything in a proper HTML document. (It would still work in a hypothetical XML document that defines an <input>
element that can accept text or child elements.)
I don't think you can style empty <input>
fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value
attribute (input[value=""]
) or lack the attribute altogether (input:not([value])
), but that's about it.
CTRL-F6 in Eclipse, like ALT-TAB (on windows), brings up a list of tabs/windows available (if you keep the CTRL / ALT key depressed) and highlights the one you will jump to when you let go of this key. You do not have to select the window. If you want to traverse several tabs at once hold down the CTRL button and tap the TAB button. This is identical behaviour to ALT-TAB on Windows.
In this sense, CTRL-SHIFT-F6 in eclipse is the ALT-SHIFT-TAB analog. Personally, I change these bindings in Eclipse to be like Visual Studio. I.e. CTRL-TAB and CTRL-SHIFT-TAB and I do it like this:
Window>Preferences>General>Keys
Then set "Next Editor"=Ctrl+Tab and "Previous Editor"=Ctrl+Shift+Tab. Don't forget to click "Unbind Command" before setting the new binding.
This is CTRL-PageDown to go right, CTRL-PageUp to go left. Frustratingly, when you get to the end of the list of tabs (say far right hand tab) and then try to go right again Eclipse does not cycle round to the first tab (far left) like most browsers would.
You can install opencv in a simple way
$ pip install opencv-python
If u are having errors, you can do this
$ pip install opencv-python-headless
Needs ensure library but you can compare list by:
ensure([1, 2]).contains_only([2, 1])
This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github
Have you tried editing the shell entry in account settings.
Go to the Accounts preferences, unlock, and right-click on your user account for the Advanced Settings dialog. Your shell should be /bin/zsh, and you can edit that invocation appropriately (i.e. add the --login argument).
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:
std::map<std::string, std::map<std::string, std::string>> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}
this should be much cleaner than the earlier versions, and avoids unnecessary copies.
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
It looks like you have to set the option for the format with data-date-*. This example works for me with 24h support.
<div class="form-group">
<div class="input-group date timepicker"
data-date-format="HH:mm"
data-date-useseconds="false"
data-date-pickDate="false">
<input type="text" name="" />
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
</div>
</div>
malloc
is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc
:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
All you have to do is
@media (min-width: 980px) { body { padding-top: 40px; } }
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
I have the same problem with a element in a webform. So what I did to fix it was validate. if(Object === 'null') do something
Team->Share project
is exactly what you need to do. Select SVN from the list, then click "Next". Subclipse will notice the presence of .svn directories that will ask you to confirm that the information is correct, and associate the project with subclipse.
This one did it for me:
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#form1').append(input);
is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)
used the Firefox firebug to check whether the element was inserted.
Hidden elements do get posted back in the form collection, only read-only fields are discarded.
Michel
Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)
$attributes = ['first'=>'a','second'=>'b'];
$query->where(function ($query) use ($attributes)
{
foreach ($attributes as $key=>value)
{
//you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});
All the answers so far are pretty flawed - they either involve adding class="noprint"
to everything or will mess up display
within #printable
.
I think the best solution would be to create a wrapper around the non-printable stuff:
<head>
<style type="text/css">
#printable { display: none; }
@media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<body>
<div id="non-printable">
Your normal page contents
</div>
<div id="printable">
Printer version
</div>
</body>
Of course this is not perfect as it involves moving things around in your HTML a bit...
ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
In addition to the accepted answer if you're using an alternative method of triggering ng-cloak...
You may also wish to add some additional specificities to your CSS/LESS:
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],
.ng-cloak, .x-ng-cloak,
.ng-hide {
display: none !important;
}
For me the same error occurred while connecting to postgres while creating a dataframe from table .It was caused due to,the missing dependency. jdbc dependency was not set .I was using maven for the build ,so added the required dependency to the pom file from maven dependency
You haven't really asked a question, but the code should be
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"};
i.e. no trailing () after the list.
I faced a similar problem today, where I have a struct that I want to fill with test data which will be passed as arguments to a function I'm testing. I wanted to have a vector of these structs and was looking for a one-liner method to initialize each struct.
I ended up going with a constructor function in the struct, which I believe was also suggested in a few answers to your question.
It's probably bad practice to have the arguments to the constructor have the same names as the public member variables, requiring use of the this
pointer. Someone can suggest an edit if there is a better way.
typedef struct testdatum_s {
public:
std::string argument1;
std::string argument2;
std::string argument3;
std::string argument4;
int count;
testdatum_s (
std::string argument1,
std::string argument2,
std::string argument3,
std::string argument4,
int count)
{
this->rotation = argument1;
this->tstamp = argument2;
this->auth = argument3;
this->answer = argument4;
this->count = count;
}
} testdatum;
Which I used in in my test function to call the function being tested with various arguments like this:
std::vector<testdatum> testdata;
testdata.push_back(testdatum("val11", "val12", "val13", "val14", 5));
testdata.push_back(testdatum("val21", "val22", "val23", "val24", 1));
testdata.push_back(testdatum("val31", "val32", "val33", "val34", 7));
for (std::vector<testdatum>::iterator i = testdata.begin(); i != testdata.end(); ++i) {
function_in_test(i->argument1, i->argument2, i->argument3, i->argument4m i->count);
}
just use this at the end of your button click event
protected void btnAddButton_Click(object sender, EventArgs e)
{
... save data routin
Response.Redirect(Request.Url.AbsoluteUri);
}
nodeName will give you the tag name in uppercase, while localName will give you the lower case.
$("yourelement")[0].localName
will give you : yourelement instead of YOURELEMENT
I suggest using "outline" instead of "border". For example: outline: 1px solid #1e5180
.
I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.
Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.
That's because the json you're getting is an array of your RootObject
class, rather than a single instance, change your DeserialiseObject<RootObject>
to be something like DeserialiseObject<RootObject[]>
(un-tested).
You'll then have to either change your method to return a collection of RootObject
or do some further processing on the deserialised object to return a single instance.
If you look at a formatted version of the response you provided:
[
{
"id":3636,
"is_default":true,
"name":"Unit",
"quantity":1,
"stock":"100000.00",
"unit_cost":"0"
},
{
"id":4592,
"is_default":false,
"name":"Bundle",
"quantity":5,
"stock":"100000.00",
"unit_cost":"0"
}
]
You can see two instances in there.
This is now supported in Chrome by the "Pause on all exceptions" button.
To enable it:
Note that this button has multiple states. Keep clicking the button to switch between
You may also use the ed
command to do in-file search and replace:
# delete all lines matching foobar
ed -s test.txt <<< $'g/foobar/d\nw'
See more in "Editing files via scripts with ed
".
It is called the extended call syntax. From the documentation:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.
and:
If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.
//Runs function after x seconds
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
//Use:-
runThisAfterDelay(seconds: x){
//write your code here
}
The python 2.5 documentation explains it well.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).
Unfortunately that page seems to have disappeared in the documentation for more recent versions.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
A better JQuery answer would be:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()});
});
You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.
A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})
Late to the story but I think some details are overlooked?
if you use
if (uemail !== undefined) {
//some function
}
You are, technically, comparing variable uemail
with variable undefined
and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true.
But it overlooks the potential that a variable by the name of undefined
may actually exist -however unlikely- and would therefore then not be of type undefined.
In that case, the comparison will return false.
To be correct one would have to declare a constant of type undefined for example:
const _undefined: undefined
and then test by:
if (uemail === _undefined) {
//some function
}
This test will return true
as uemail
now equals both value & type of _undefined
as _undefined
is now properly declared to be of type undefined.
Another way would be
if (typeof(uemail) === 'undefined') {
//some function
}
In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.
You need to get mac for it. There are several tool chains available (like win-chain) that actually lets you write and build i Phone applications on windows. There are several associated tutorials to build the Objective C code on Windows. But there is a problem, the apps hence developed will work on Jail broken i Phones only.
We’ve seen few hacks to get over that and make it to App Store, but as Apple keeps on updating SDKs, tool chains need regular updates. It’s a hassle to make it up all the time.If you want to get ready app you can also take help from arcapps its launches apps at a reasonable price. iphone app development
Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...
I was trying to add List to existing key in dictionary and reached the following solution:
Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);
It will not show any exception and won't replace previous values.
I use SourceTree git client, and I see that their initial commit/push command is:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
JavaScript is case sensitive.
So, if you want to change the font size, you have to go:
span.style.fontSize = "25px";
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
Use the built-in MSDB.DBO.AGENT_DATETIME(20150119,0)
https://blog.sqlauthority.com/2015/03/13/sql-server-interesting-function-agent_datetime/
use <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
refer this.
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the *
inside the parenthesis as
suggested above. Otherwise your matching
group will contain only one
character.
Get rid of the ^
and $
. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.
I suppose you want the matching group (what's
inside the parenthesis) rather than
the full array? arr[0]
is
the full match ("\nSUMMARY:..."
) and
the next indexes contain the group
matches.
String.match(regexp) is supposed to return an array with the matches. In my browser it doesn't (Safari on Mac returns only the full match, not the groups), but Regexp.exec(string) works.
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
If you are trying this in Windows Powershell, you will get this error:
[ERROR] Unknown lifecycle phase ".test.skip=true". You must specify a valid lifecycle phase or a goal in the format...
The reason for this is, in Powershell the "-
" has special meaning and it is causing problem with maven.
The solution is to prepend it with a backtick (`), like so..
mvn `-Dmaven.test.skip=true install
Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:
Sub find()
Dim i As Integer
Dim firstTime As Integer
Dim bNotFound As Boolean
i = 1
bNotFound = True
Do While bNotFound
If Cells(i, 2).Value = "ProjTemp" Then
firstTime = i
bNotFound = false
End If
i = i + 1
Loop
End Sub
From my research and starting on this post, i think this is the best option:
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p>
_x000D_
This option allow resizes of the page and even if the page is blank it will stick at the bottom.
Easiest solution is to use BuildConfig
.
I use BuildConfig.VERSION_NAME
in my application.
You can also use BuildConfig.VERSION_CODE
to get version code.
There is no "best way" to create an object. Each way has benefits depending on your use case.
The constructor pattern (a function paired with the new
operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don't. So if you want prototypal inheritance, then a constructor function is a fine way to go.
However, if you want prototypal inheritance, you may as well use Object.create
, which makes the inheritance more obvious.
Creating an object literal (ex: var obj = {foo: "bar"};
) works great if you happen to have all the properties you wish to set on hand at creation time.
For setting properties later, the NewObject.property1
syntax is generally preferable to NewObject['property1']
if you know the property name. But the latter is useful when you don't actually have the property's name ahead of time (ex: NewObject[someStringVar]
).
Hope this helps!
You can also use inspect.getdoc
. It cleans up the __doc__
by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.
Why does everyone like to list out source files? A simple find command can take care of that easily.
Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C
files and then type make
...
appname := myapp
CXX := clang++
CXXFLAGS := -std=c++11
srcfiles := $(shell find . -name "*.C")
objects := $(patsubst %.C, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
C# requires the end of switch sections, including the final one,
So you also need to add a break;
to your default
section, otherwise there will still will be a compiler error.
This method all is old method, in drupal 7 we can get it very simple
current_path()
and another function with tiny difference
request_path()
If you need stricter replacement matching, PostgreSQL's regexp_replace
function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).
I will use flags i
and g
for case-insensitive and global matching, respectively. I will also use \m
and \M
to match the beginning and the end of a word, respectively.
There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
--> Cat bobdog cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
--> dog bobcat cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
--> Cat bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
--> dog bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
--> dog bobcat dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
--> dog bobdog dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
--> dog bobcat dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
--> dog bobcat dog dogs catfish
Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.
Check out the current PostgreSQL pattern matching docs for all the details.
Given my examples, maybe the safest option would be:
UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');
How about
vim -O a a
That way you can edit a single file on your left and navigate the whole dir on your right... Just a thought, not the solution...
Use Node Version Manager (NVM)
It's a Bash script that lets you download and manage different versions of node. Full source code is here.
There is a separate project for nvm for Windows: github.com/coreybutler/nvm-windows
Below are the full steps to use NVM for multiple version of node on windows
nvm list available
from cmd or gitbash or powershell, this will list all available version of node nvm install version
e.g. nvm install 12.14.0
to install on the machinenvm use version
to use newer version e.g. nvm use 12.14.0
Complete instruction is as follow:
openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes
openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem
yum install -y ca-certificates
,
cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
,
update-ca-trust
,
update-ca-trust force-enable
Hope to be useful
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
Donald Knuth's The Art of Computer Programming Vol.1 has a demonstration of elevator and the data-structures. Knuth presents a very thorough discussion and program.
Knuth(1997) "Information Structures", The Art of Computer Programming Vol. 1 pp.302-308
There are two ways to download a file where the HTTP request requires that a header be set.
The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.
The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.
The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.
Solution:
var id = 123;
var req = ic.ajax.raw({
type: 'GET',
url: '/api/dowloads/'+id,
beforeSend: function (request) {
request.setRequestHeader('token', 'token for '+id);
},
processData: false
});
var maxSizeForBase64 = 1048576; //1024 * 1024
req.then(
function resolve(result) {
var str = result.response;
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
var blob = new Blob([result.response], { type: 'text/bin' });
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', id+'.bin');
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
else {
//use base64 encoding when less than set limit or file API is not available
anchor.attr({
href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
download: id+'.bin',
});
anchor.get(0).click();
}
}.bind(this),
function reject(err) {
console.log(err);
}
);
Note that I'm not using a raw XMLHttpRequest
,
and instead using ic-ajax,
and should be quite similar to a jQuery.ajax
solution.
Note also that you should substitute text/bin
and .bin
with whatever corresponds to the file type being downloaded.
The implementation of FormatUtils.utf8toBase64
can be found here
Daemon threads are threads that run in the background as long as other non-daemon threads of the process are still running. Thus, when all of the non-daemon threads complete, the daemon threads are terminated. An example for the non-daemon thread is the thread running the Main.
A thread is made daemon by calling the setDaemon()
method before the thread is started
For More Reference : Daemon thread in Java
Using parameters in batch files: %0 and %9
Batch files can refer to the words passed in as parameters with the tokens: %0
to %9
.
%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.
parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0
is the program name as it was called, in DOS %0
will be empty for AUTOEXEC.BAT if started at boot time.
Example:
Put the following command in a batch file called mybatch.bat
:
@echo off
@echo hello %1 %2
pause
Invoking the batch file like this: mybatch john billy
would output:
hello john billy
Get more than 9 parameters for a batch file, use: %*
The Percent Star token %*
means "the rest of the parameters". You can use a for loop to grab them, as defined here:
http://www.robvanderwoude.com/parameters.php
Notes about delimiters for batch parameters
Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:
commas (",") are replaced by spaces, unless they are part of a string in
double quotes
semicolons (";") are replaced by spaces, unless they are part of a string in
double quotes
"=" characters are sometimes replaced by spaces, not if they are part of a
string in double quotes
the first forward slash ("/") is replaced by a space only if it immediately
follows the command, without a leading space
multiple spaces are replaced by a single space, unless they are part of a
string in double quotes
tabs are replaced by a single space
leading spaces before the first command line argument are ignored
At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :
The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).
"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".
But eventually, I think we can all agree that they will develop such API, it's only a matter of time.
Have you checked if:
class
file under src
folder in your JAVA project?(not file
)I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.
Here is my Library That I have created for simple Webservice Calling,
You can use this by adding a one line gradle dependency -
compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'
Here is the demonstration of using.
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
Please refer to update_attribute
. On clicking show source you will get following code
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
2614: def update_attribute(name, value)
2615: send(name.to_s + '=', value)
2616: save(false)
2617: end
and now refer update_attributes
and look at its code you get
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
2621: def update_attributes(attributes)
2622: self.attributes = attributes
2623: save
2624: end
the difference between two is update_attribute
uses save(false)
whereas update_attributes
uses save
or you can say save(true)
.
Sorry for the long description but what I want to say is important. save(perform_validation = true)
, if perform_validation
is false it bypasses (skips will be the proper word) all the validations associated with save
.
For second question
Also, what is the correct syntax to pass a hash to update_attributes... check out my example at the top.
Your example is correct.
Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")
or
Object.update_attributes :field1 => "value", :field2 => "value2", :field3 => "value3"
or if you get all fields data & name in a hash say params[:user]
here use just
Object.update_attributes(params[:user])
There can be any possible reason:
module
does not have CommonModule
in imports[]
component
, where you are using *ngFor
, is not a part of any module
.*ngFor
i.e. **ngFor
or *ngfor
etc. typo.IDE
i.e. VS Code, IntelliJ etc.I'm from Brazil and I create my data bases using latin1_spanish_ci
. For the html and everything else I use:
charset=ISO-8859-1
The data goes right with é
,ã
and ç
... Sometimes I have to put the texts of the html using the code of it, such as:
Olá
gives me
Olá
You can find the codes in this page: http://www.ascii.cl/htmlcodes.htm
Hope this helps. I remember it was REALLY annoying.
You should use java.time classes with Java 8 and later. To use java.time, add:
import java.time.* ;
Below is an example, how you can format date.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));
You can try a rebase --interactive
session to amend your old commit (provided you did not already push those commits to another repo).
Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.Start it with the last commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...
The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
Try this:
update table YourTable
set YourField = substring(YourField, 5, len(YourField)-3);
haml is a good choice for node.js
http://github.com/creationix/haml-js
haml-js
!!! XML
!!! strict
%html{ xmlns: "http://www.w3.org/1999/xhtml" }
%head
%title Sample haml template
%body
.profile
.left.column
#date= print_date()
#address= current_user.address
.right.column
#email= current_user.email
#bio= current_user.bio
html
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Sample haml template
</title></head><body><div class="profile"><div class="left column"><div id="date">January 1, 2009
</div><div id="address">Richardson, TX
</div></div><div class="right column"><div id="email">[email protected]
</div><div id="bio">Experienced software professional...
</div></div></div></body></html>
I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.
Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!
Here's class TkRepeatingTask and BackgroundTask:
import threading
class TkRepeatingTask():
def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
self.__tk_ = tkRoot
self.__func_ = taskFuncPointer
self.__freq_ = freqencyMillis
self.__isRunning_ = False
def isRunning( self ) : return self.__isRunning_
def start( self ) :
self.__isRunning_ = True
self.__onTimer()
def stop( self ) : self.__isRunning_ = False
def __onTimer( self ):
if self.__isRunning_ :
self.__func_()
self.__tk_.after( self.__freq_, self.__onTimer )
class BackgroundTask():
def __init__( self, taskFuncPointer ):
self.__taskFuncPointer_ = taskFuncPointer
self.__workerThread_ = None
self.__isRunning_ = False
def taskFuncPointer( self ) : return self.__taskFuncPointer_
def isRunning( self ) :
return self.__isRunning_ and self.__workerThread_.isAlive()
def start( self ):
if not self.__isRunning_ :
self.__isRunning_ = True
self.__workerThread_ = self.WorkerThread( self )
self.__workerThread_.start()
def stop( self ) : self.__isRunning_ = False
class WorkerThread( threading.Thread ):
def __init__( self, bgTask ):
threading.Thread.__init__( self )
self.__bgTask_ = bgTask
def run( self ):
try :
self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
except Exception as e: print repr(e)
self.__bgTask_.stop()
Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:
def tkThreadingTest():
from tkinter import Tk, Label, Button, StringVar
from time import sleep
class UnitTestGUI:
def __init__( self, master ):
self.master = master
master.title( "Threading Test" )
self.testButton = Button(
self.master, text="Blocking", command=self.myLongProcess )
self.testButton.pack()
self.threadedButton = Button(
self.master, text="Threaded", command=self.onThreadedClicked )
self.threadedButton.pack()
self.cancelButton = Button(
self.master, text="Stop", command=self.onStopClicked )
self.cancelButton.pack()
self.statusLabelVar = StringVar()
self.statusLabel = Label( master, textvariable=self.statusLabelVar )
self.statusLabel.pack()
self.clickMeButton = Button(
self.master, text="Click Me", command=self.onClickMeClicked )
self.clickMeButton.pack()
self.clickCountLabelVar = StringVar()
self.clickCountLabel = Label( master, textvariable=self.clickCountLabelVar )
self.clickCountLabel.pack()
self.threadedButton = Button(
self.master, text="Timer", command=self.onTimerClicked )
self.threadedButton.pack()
self.timerCountLabelVar = StringVar()
self.timerCountLabel = Label( master, textvariable=self.timerCountLabelVar )
self.timerCountLabel.pack()
self.timerCounter_=0
self.clickCounter_=0
self.bgTask = BackgroundTask( self.myLongProcess )
self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )
def close( self ) :
print "close"
try: self.bgTask.stop()
except: pass
try: self.timer.stop()
except: pass
self.master.quit()
def onThreadedClicked( self ):
print "onThreadedClicked"
try: self.bgTask.start()
except: pass
def onTimerClicked( self ) :
print "onTimerClicked"
self.timer.start()
def onStopClicked( self ) :
print "onStopClicked"
try: self.bgTask.stop()
except: pass
try: self.timer.stop()
except: pass
def onClickMeClicked( self ):
print "onClickMeClicked"
self.clickCounter_+=1
self.clickCountLabelVar.set( str(self.clickCounter_) )
def onTimer( self ) :
print "onTimer"
self.timerCounter_+=1
self.timerCountLabelVar.set( str(self.timerCounter_) )
def myLongProcess( self, isRunningFunc=None ) :
print "starting myLongProcess"
for i in range( 1, 10 ):
try:
if not isRunningFunc() :
self.onMyLongProcessUpdate( "Stopped!" )
return
except : pass
self.onMyLongProcessUpdate( i )
sleep( 1.5 ) # simulate doing work
self.onMyLongProcessUpdate( "Done!" )
def onMyLongProcessUpdate( self, status ) :
print "Process Update: %s" % (status,)
self.statusLabelVar.set( str(status) )
root = Tk()
gui = UnitTestGUI( root )
root.protocol( "WM_DELETE_WINDOW", gui.close )
root.mainloop()
if __name__ == "__main__":
tkThreadingTest()
Two import points I'll stress about BackgroundTask:
1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.
2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!
To answer the question about mappings: your provided __iter__
should iterate over the keys of the mapping. The following is a simple example that creates a mapping x -> x * x
and works on Python3 extending the ABC mapping.
import collections.abc
class MyMap(collections.abc.Mapping):
def __init__(self, n):
self.n = n
def __getitem__(self, key): # given a key, return it's value
if 0 <= key < self.n:
return key * key
else:
raise KeyError('Invalid key')
def __iter__(self): # iterate over all keys
for x in range(self.n):
yield x
def __len__(self):
return self.n
m = MyMap(5)
for k, v in m.items():
print(k, '->', v)
# 0 -> 0
# 1 -> 1
# 2 -> 4
# 3 -> 9
# 4 -> 16
Here you can do it by using HttpRequest
or HttpSession
. And think your problem is within the JSP.
If you are going to use the inside servlet do following,
Object obj = new Object();
session.setAttribute("object", obj);
or
HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);
and after setting your attribute by using request or session, use following to access it in the JSP,
<%= request.getAttribute("object")%>
or
<%= session.getAttribute("object")%>
So seems your problem is in the JSP.
If you want use scriptlets it should be as follows,
<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>
Or can use expressions as follows,
<%= session.getAttribute("object")%>
or can use EL as follows,
${object}
or ${sessionScope.object}
There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!
In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!
So... how do we do this?
My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:
static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// Swap the items.
T temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
// Return the items in the new order.
foreach (T item in source)
yield return item;
// Restore the collection.
source[index2] = source[index1];
source[index1] = temp;
}
This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:
There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):
static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// If nothing needs to be swapped, just return the original collection.
if (index1 == index2)
return source;
// Make a copy.
List<T> copy = source.ToList();
// Swap the items.
T temp = copy[index1];
copy[index1] = copy[index2];
copy[index2] = temp;
// Return the copy with the swapped items.
return copy;
}
One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.
You might consider the following solution:
static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using (IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for (int i = 0; i < index1; i++)
yield return source[i];
// Return the item at the second index.
yield return source[index2];
if (index1 != index2)
{
// Return the items between the first and second index.
for (int i = index1 + 1; i < index2; i++)
yield return source[i];
// Return the item at the first index.
yield return source[index1];
}
// Return the remaining items.
for (int i = index2 + 1; i < source.Count; i++)
yield return source[i];
}
}
And if you want to input parameter to be IEnumerable:
static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using(IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for(int i = 0; i < index1; i++)
{
if (!e.MoveNext())
yield break;
yield return e.Current;
}
if (index1 != index2)
{
// Remember the item at the first position.
if (!e.MoveNext())
yield break;
T rememberedItem = e.Current;
// Store the items between the first and second index in a temporary list.
List<T> subset = new List<T>(index2 - index1 - 1);
for (int i = index1 + 1; i < index2; i++)
{
if (!e.MoveNext())
break;
subset.Add(e.Current);
}
// Return the item at the second index.
if (e.MoveNext())
yield return e.Current;
// Return the items in the subset.
foreach (T item in subset)
yield return item;
// Return the first (remembered) item.
yield return rememberedItem;
}
// Return the remaining items in the list.
while (e.MoveNext())
yield return e.Current;
}
}
Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.
First take the JSON string and make real objects out of it. Loop though all of the properties of the object, placing the items in an unordered list. Every time you get to a new object, make a new list.
Like this... I used it to read Chinese characters...
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String
Do
a = reader.ReadLine
'
' Code here
'
Loop Until a Is Nothing
reader.Close()
select CONCAT(UCASE(LEFT('CHRIS', 1)),SUBSTRING(lower('CHRIS'),2));
Above statement can be used for first letter CAPS and rest as lower case.
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
You can do this using the splat operator:
some_func(*params)
This causes the function to receive each list item as a separate parameter. There's a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists
You can do it by using window_handles
and switch_to_window
method.
Before clicking the link first store the window handle as
window_before = driver.window_handles[0]
after clicking the link store the window handle of newly opened window as
window_after = driver.window_handles[1]
then execute the switch to window method to move to newly opened window
driver.switch_to_window(window_after)
and similarly you can switch between old and new window. Following is the code example
import unittest
from selenium import webdriver
class GoogleOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print window_before
driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
print window_after
driver.find_element_by_link_text("ATM").click()
driver.switch_to_window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type
).
public static Type ListOfWhat(Object list)
{
return ListOfWhat2((dynamic)list);
}
private static Type ListOfWhat2<T>(IList<T> list)
{
return typeof(T);
}
Example usage:
object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();
Prints
typeof(DateTime)
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.
A previous reply to this question has given a great explanation of what the various types are.
You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.
http://www.softwareverify.com/cpp/memory/index.html
Disclaimer: I designed Memory Validator.
<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>
css:
.smallDiv { height: 150px; width: 150px; }
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
There are many possible answers to this question. I think it all depends on what your environment and installation procedure is. I'm running into the same issue as stated multiple times above. I cannot install ADT 23 because of a conflict dependency.
This is my environment:
I'm running Windows 7 64-bit with Eclipse 4.2.2. I installed ADT through menu Help ? Install New Software.
My solution:
Menu Help ? About Eclipse ? Uninstall ? ALL_ANDROID. Then I simply installed each of the ADT 23 tools through the "Install New Software".
Note: This is with the LATEST ADT release.
Run commands below, in this order:
brew update
brew doctor
brew upgrade node
Now you have installed updated version of node, and it's probably not linked. If it's not, then just type: brew link node
or brew link --overwrite node
The best way is
AddTaskViewController * add = [self.storyboard instantiateViewControllerWithIdentifier:@"addID"];
[self presentViewController:add animated:YES completion:nil];
I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.
App Engine is a Platform-as-a-Service. It means that you simply deploy your code, and the platform does everything else for you. For example, if your app becomes very successful, App Engine will automatically create more instances to handle the increased volume.
Compute Engine is an Infrastructure-as-a-Service. You have to create and configure your own virtual machine instances. It gives you more flexibility and generally costs much less than App Engine. The drawback is that you have to manage your app and virtual machines yourself.
Read more about Compute Engine
You can mix both App Engine and Compute Engine, if necessary. They both work well with the other parts of the Google Cloud Platform.
EDIT (May 2016):
One more important distinction: projects running on App Engine can scale down to zero instances if no requests are coming in. This is extremely useful at the development stage as you can go for weeks without going over the generous free quota of instance-hours. Flexible runtime (i.e. "managed VMs") require at least one instance to run constantly.
EDIT (April 2017):
Cloud Functions (currently in beta) is the next level up from App Engine in terms of abstraction - no instances! It allows developers to deploy bite-size pieces of code that execute in response to different events, which may include HTTP requests, changes in Cloud Storage, etc.
The biggest difference with App Engine is that functions are priced per 100 milliseconds, while App Engine's instances shut down only after 15 minutes of inactivity. Another advantage is that Cloud Functions execute immediately, while a call to App Engine may require a new instance - and cold-starting a new instance may take a few seconds or longer (depending on runtime and your code).
This makes Cloud Functions ideal for (a) rare calls - no need to keep an instance live just in case something happens, (b) rapidly changing loads where instances are often spinning and shutting down, and possibly more use cases.
jQuery dialog has an isOpen
property that can be used to check if a jQuery dialog is open or not.
You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html
type node js
command prompt in start screen. and use it.
OR
set PATH
of node in environment variable.
This code works to catch the user closing the console window:
using System;
using System.Runtime.InteropServices;
class Program {
static void Main(string[] args) {
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
Console.ReadLine();
}
static bool ConsoleEventCallback(int eventType) {
if (eventType == 2) {
Console.WriteLine("Console window closing, death imminent");
}
return false;
}
static ConsoleEventDelegate handler; // Keeps it from getting garbage collected
// Pinvoke
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
}
Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().
On iOS, it currently does not matter if you use int
or NSInteger
. It will matter more if/when iOS moves to 64-bits.
Simply put, NSInteger
s are int
s in 32-bit code (and thus 32-bit long) and long
s on 64-bit code (long
s in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger
instead of long
is to not break existing 32-bit code (which uses int
s).
CGFloat
has the same issue: on 32-bit (at least on OS X), it's float
; on 64-bit, it's double
.
Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.
Update 2: Also, using NSInteger
s helps with Swift code interoperability.
I have just started using hooks and I got the above warning when i was calling useEffect inside a function:
Then I have to move the useEffect outside of the function as belows:
const onChangeRetypePassword = async value => {
await setRePassword(value);
//previously useEffect was here
};
//useEffect outside of func
useEffect(() => {
if (password !== rePassword) {
setPasswdMismatch(true);
}
else{
setPasswdMismatch(false);
}
}, [rePassword]);
Hope it will be helpful to someone !
Mainly the R.java file is relating to the .xml file and the Java. We know the XML tags, but what about Java, so for that we need to have an unique id for identifying the tag.
Here the R.java file is mainly related to the XML file with Java for getting the values.
So basically you want to find a file in mounted filesystem (not necessarily in PATH directories only) and check if it is executable. This translates to following plan:
I'd say, doing this in a portable way will require lots of computing power and time. Is it really what you need?
This is my simple solution:
String secToTime(int sec) {
int seconds = sec % 60;
int minutes = sec / 60;
if (minutes >= 60) {
int hours = minutes / 60;
minutes %= 60;
if( hours >= 24) {
int days = hours / 24;
return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
}
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
return String.format("00:%02d:%02d", minutes, seconds);
}
Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745
If you don't care about IE =6, you could use pure CSS ...
.forum:hover { background-color: #380606; }
.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */_x000D_
_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
With jQuery, usually it is better to create a specific class for this style:
.forum_hover { background-color: #380606; }
and then apply the class on mouseover, and remove it on mouseout.
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});
$(document).ready(function(){_x000D_
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});_x000D_
});
_x000D_
.forum_hover { background-color: #380606 !important; }_x000D_
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
If you must not modify the class, you could save the original background color in .data()
:
$('.forum').data('bgcolor', '#380606').hover(function(){
var $this = $(this);
var newBgc = $this.data('bgcolor');
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
});
$(document).ready(function(){_x000D_
$('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
var $this = $(this);_x000D_
var newBgc = $this.data('bgcolor');_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
});_x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
or
$('.forum').hover(
function(){
var $this = $(this);
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
},
function(){
var $this = $(this);
$this.css('background-color', $this.data('bgcolor'));
}
);
$(document).ready(function(){_x000D_
$('.forum').hover(_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
},_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.css('background-color', $this.data('bgcolor'));_x000D_
}_x000D_
); _x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
Try the following:
int[][] multi = new int[5][10];
... which is a short hand for something like this:
int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];
Note that every element will be initialized to the default value for int
, 0
, so the above are also equivalent to:
int[][] multi = new int[][]{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
this worked perfectly for me:
for(a in array)console.log(array[a])
you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted
Try npm install [email protected]
and also replace
bson = require('../build/Release/bson');
to
bson = require('../browser_build/bson');
in node_modules/bson/ext/index.js
While working with AsyncTask, it is necessary to create a class-successor and in it to register the implementation of methods necessary for us. In this lesson we will look at three methods:
doInBackground - will be executed in a new thread, and here we solve all our difficult tasks. Because a non-primary thread does not have access to the UI.
onPreExecute - executed before doInBackground and has access to the UI
onPostExecute - executed after doInBackground (does not work if AsyncTask was canceled - about this in the next lessons) and has access to the UI.
This is the MyAsyncTask class:
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Start");
}
@Override
protected Void doInBackground(Void... params) {
// Your background method
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tvInfo.setText("Finish");
}
}
And this is how to call in your Activity or Fragment:
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
For me below code worked, first sending json string with proper headers
$.ajax({
type: "POST",
url : 'save',
data : JSON.stringify(valObject),
contentType:"application/json; charset=utf-8",
dataType:"json",
success : function(resp){
console.log(resp);
},
error : function(resp){
console.log(resp);
}
});
And then on Spring side -
@RequestMapping(value = "/save",
method = RequestMethod.POST,
consumes="application/json")
public @ResponseBody String save(@RequestBody ArrayList<KeyValue> keyValList) {
//Saving call goes here
return "";
}
Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.
My json object is like this -
[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
{"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]
This is what I did:
HTML
<div id="divProgress"></div>
<div id="divStepTitle">
<span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>
<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />
CSS
#divProgress
{
width: 600px;
}
#divStepTitle
{
width: 600px;
}
.spanStep
{
text-align: center;
width: 200px;
}
Javascript/jQuery
var progress = 0;
$(function({
//set step progress bar
$("#divProgress").progressbar();
//event handler for prev and next button
$("#btnPrev, #btnNext").click(function(){
step($(this));
});
});
function step(obj)
{
//switch to prev/next page
if (obj.val() == "Prev")
{
//set new value for progress bar
progress -= 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing previous page
}
else if (obj.val() == "Next")
{
//set new value for progress bar
progress += 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing next page
}
}
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
Check this:
let cloned = source.map(x => Object.assign({}, x));
Linebreaks are not the same under windows/linux/mac. You should use System.getProperties with the attribute line.separator.
just in case you need to create thumb with a max width and a max height ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
Another way would be to encode the quotes using htmlspecialchars:
$json_array = array(
'title' => 'Example string\'s with "special" characters'
);
$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');
You can use Array.filter function to filter out elements of an array based on the return value of a callback function. The callback function runs for every element of the original array.
The logic for the callback function here is that if the indexOf
value for current item is same as the index, it means the element has been encountered first time, so it can be considered unique. If not, it means the element has been encountered already, so should be discarded now.
var arr = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];_x000D_
_x000D_
var filteredArray = arr.filter(function(item, pos){_x000D_
return arr.indexOf(item)== pos; _x000D_
});_x000D_
_x000D_
console.log( filteredArray );
_x000D_
Caveat: As pointed out by rob in the comments, this method should be avoided with very large arrays as it runs in O(N^2)
.
UPDATE (16 Nov 2017)
If you can rely on ES6 features, then you can use Set object and Spread operator to create a unique array from a given array, as already specified in @Travis Heeter's answer below:
var uniqueArray = [...new Set(array)]
we had: SQLSTATE[HY000]: General error: 1114 The table 'catalog_product_index_price_bundle_sel_tmp' is full
solved by:
edit config of db:
nano /etc/my.cnf
tmp_table_size=256M max_heap_table_size=256M
public ActionResult Index()
{
return View();
}
public ActionResult Test(string Name)
{
return RedirectToAction("Index");
}
Return View
Directly displays your view
but
Redirect ToAction
Action is performed
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
if (elem === 3) {_x000D_
return;_x000D_
}_x000D_
_x000D_
console.log(elem);_x000D_
});
_x000D_
Output: 1, 2, 4
Path to the current .exe
#include <Windows.h>
std::wstring getexepathW()
{
wchar_t result[MAX_PATH];
return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));
}
std::wcout << getexepathW() << std::endl;
// -------- OR --------
std::string getexepathA()
{
char result[MAX_PATH];
return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));
}
std::cout << getexepathA() << std::endl;
Try this:
$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");
Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.
For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:
he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.
Here’s how you’d use it:
he.decode("We're unable to complete your request at this time.");
? "We're unable to complete your request at this time."
Disclaimer: I'm the author of the he library.
See this Stack Overflow answer for some more info.
Another way to achieve this is using file
with state: hard
.
This is an example I got to work:
- name: Link source file to another destination
file:
src: /path/to/source/file
path: /target/path/of/file
state: hard
Only tested on localhost (OSX) though, but should work on Linux as well. I can't tell for Windows.
Note that absolute paths are needed. Else it wouldn't let me create the link. Also you can't cross filesystems, so working with any mounted media might fail.
The hardlink is very similar to moving, if you remove the source file afterwards:
- name: Remove old file
file:
path: /path/to/source/file
state: absent
Another benefit is that changes are persisted when you're in the middle of a play. So if someone changes the source, any change is reflected in the target file.
You can verify the number of links to a file via ls -l
. The number of hardlinks is shown next to the mode (e.g. rwxr-xr-x 2, when a file has 2 links).
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location
service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location
helper methods. E.g. we ran $location.search(..., ...)
to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url()
if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.com/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/'
as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has
.bind("change", function(){ ... });
Or
.change(function(){ ... });
which are equivalents.
for a unique selector change your name attribute to id and then jQuery("#imafile")
or a general jQuery('input[type="file"]')
for all the file inputs
It happened to me couple of weeks back. The version of mongoimport was too old. Once i Updated to latest version it ran successfully and imported all documents.
I am posting this answer even though this thread is old. I couldn't get the accepted answer to work for me. This one works well and is pretty simple.
I load the height of each div I want into the data
$('div').each(function(){
$(this).data('height',$(this).css('height'));
$(this).css('height','20px');
});
Then I just use that when animating on click.
$('div').click(function(){
$(this).css('height',$(this).data('height'));
});
I am using CSS transition, so I don't use the jQuery animate, but you could do animate just the same.
There is no need for slow loops, generators or recursive functions (with or without caching). Here is a fast one-liner using Array
and reduce
.
ECMAScript 6:
var fibonacci=(n)=>Array(n).fill().reduce((a,b,c)=>a.concat(c<2?c:a[c-1]+a[c-2]),[])
ECMAScript 5:
function fibonacci(n){
return Array.apply(null,{length:n}).reduce(function(a,b,c){return a.concat((c<2)?c:a[c-1]+a[c-2]);},[]);
}
Tested in Chrome 59 (Windows 10):
fibonacci(10); // 0 ms -> (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
JavaScript can handle numbers up to 1476 before reaching Infinity
.
fibonacci(1476); // 11ms -> (1476) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
You basically need a helper method to read a stream into memory. This works pretty well:
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
Then you'd call it with:
public static byte[] loadFile(String sourcePath) throws IOException
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
Don't mix up text and binary data - it only leads to tears.
Here's my contribution if looking for
h:mm:ss
instead like I was:
function msConversion(millis) {
let sec = Math.floor(millis / 1000);
let hrs = Math.floor(sec / 3600);
sec -= hrs * 3600;
let min = Math.floor(sec / 60);
sec -= min * 60;
sec = '' + sec;
sec = ('00' + sec).substring(sec.length);
if (hrs > 0) {
min = '' + min;
min = ('00' + min).substring(min.length);
return hrs + ":" + min + ":" + sec;
}
else {
return min + ":" + sec;
}
}
Note the plural in this method:
document.getElementsByName()
That returns an array of elements, so use [0] to get the first occurence, e.g.
document.getElementsByName()[0]
If it's a single line string. wrapt it with b or B. e.g:
variable = b"This is a variable"
or
variable2 = B"This is also a variable"
In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.
In App.xaml:
<Application
x:Class="BuildAssistantUI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
StartupUri="MainWindow.xaml"
>
<Application.Resources>
<local:MainViewModel x:Key="MainViewModel" />
</Application.Resources>
</Application>
In MainWindow.xaml:
<Window x:Class="BuildAssistantUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{StaticResource MainViewModel}"
/>
for PHP developer
filter_var($value, FILTER_VALIDATE_MAC)
Please check you are using //
not \\
by-mistake , like below
Wrong:"http:\\stackoverflow.com"
Right:"http://stackoverflow.com"
One more method is to Define the Layout inside the View:
@{
Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
}
More Ways to do, can be found here, hope this helps someone.
For me I doing this:
import paramiko
hostname = 'my hostname or IP'
myuser = 'the user to ssh connect'
mySSHK = '/path/to/sshkey.pub'
sshcon = paramiko.SSHClient() # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed
works for me pretty ok
If the goal is to have the object appear self-contained and be within one set of braces, you could try this:
var a = new function () {
if (conditionB)
this.b = 5;
if (conditionC)
this.c = 5;
if (conditionD)
this.d = 5;
};
You can just look for the value that corresponds with the key and then check if the input is equal to the key.
for key in PIX0:
NUM = input("Which standard has a resolution of %s " % PIX0[key])
if NUM == key:
Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.
print("I'm sorry but thats wrong. The correct answer was: %s." % key )
Also, I would recommend using str.format
for string formatting instead of the %
syntax.
Your full code should look like this (after adding in string formatting)
PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
for key in PIX0:
NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))
@Component({
selector: 'my-app',
template: `
<div>
<input name="file" type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
file: File;
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
console.log(this.file);
}
doAnythingWithFile() {
}
}
Tilde expansion in Bash:
http://bash-hackers.org/wiki/doku.php/syntax/expansion/tilde
You should use async pipe. Doc: https://angular.io/api/common/AsyncPipe
For example:
<li *ngFor="let a of authorizationTypes | async"[value]="a.id">
{{ a.name }}
</li>
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
You can define the drawables that are used for the background, and the switcher part like this:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/switch_thumb_holo_light" />
</selector>
This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:
The deactivated version (xhdpi version that Android is using)
The pressed slider:
The activated slider (on state):
The default version (off state):
There are also three different states for the background that are defined in the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" />
<item android:drawable="@drawable/switch_bg_holo_dark" />
</selector>
The deactivated version:
The focused version:
And the default version:
To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.
I'm just writing this to remind myself...
Array.prototype.slice.call(arguments);
== Array.prototype.slice(arguments[1], arguments[2], arguments[3], ...)
== [ arguments[1], arguments[2], arguments[3], ... ]
Or just use this handy function $A to turn most things into an array.
function hasArrayNature(a) {
return !!a && (typeof a == "object" || typeof a == "function") && "length" in a && !("setInterval" in a) && (Object.prototype.toString.call(a) === "[object Array]" || "callee" in a || "item" in a);
}
function $A(b) {
if (!hasArrayNature(b)) return [ b ];
if (b.item) {
var a = b.length, c = new Array(a);
while (a--) c[a] = b[a];
return c;
}
return Array.prototype.slice.call(b);
}
example usage...
function test() {
$A( arguments ).forEach( function(arg) {
console.log("Argument: " + arg);
});
}
If you want to set the active tab by ID instead of index, you can also use the following:
$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });
Another option is to use InjectableValues and @JacksonInject. It is very useful if you need to use not always the same value but one get from DB or somewhere else for the specific case. Here is an example of using JacksonInject
:
protected static class Some {
private final String field1;
private final String field2;
public Some(@JsonProperty("field1") final String field1,
@JsonProperty("field2") @JacksonInject(value = "defaultValueForField2",
useInput = OptBoolean.TRUE) final String field2) {
this.field1 = requireNonNull(field1);
this.field2 = requireNonNull(field2);
}
public String getField1() {
return field1;
}
public String getField2() {
return field2;
}
}
@Test
public void testReadValueInjectables() throws JsonParseException, JsonMappingException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final InjectableValues injectableValues =
new InjectableValues.Std().addValue("defaultValueForField2", "somedefaultValue");
mapper.setInjectableValues(injectableValues);
final Some actualValueMissing = mapper.readValue("{\"field1\": \"field1value\"}", Some.class);
assertEquals(actualValueMissing.getField1(), "field1value");
assertEquals(actualValueMissing.getField2(), "somedefaultValue");
final Some actualValuePresent =
mapper.readValue("{\"field1\": \"field1value\", \"field2\": \"field2value\"}", Some.class);
assertEquals(actualValuePresent.getField1(), "field1value");
assertEquals(actualValuePresent.getField2(), "field2value");
}
Keep in mind that if you are using constructor to create the entity (this usually happens when you use @Value or @AllArgsConstructor in lombok ) and you put @JacksonInject
not to the constructor but to the property it will not work as expected - value of the injected field will always override value in json, no matter whether you put useInput = OptBoolean.TRUE
in @JacksonInject
. This is because jackson injects those properties after constructor is called (even if the property is final
) - field is set to the correct value in constructor but then it is overrided (check: https://github.com/FasterXML/jackson-databind/issues/2678 and https://github.com/rzwitserloot/lombok/issues/1528#issuecomment-607725333 for more information), this test is unfortunately passing:
protected static class Some {
private final String field1;
@JacksonInject(value = "defaultValueForField2", useInput = OptBoolean.TRUE)
private final String field2;
public Some(@JsonProperty("field1") final String field1,
@JsonProperty("field2") @JacksonInject(value = "defaultValueForField2",
useInput = OptBoolean.TRUE) final String field2) {
this.field1 = requireNonNull(field1);
this.field2 = requireNonNull(field2);
}
public String getField1() {
return field1;
}
public String getField2() {
return field2;
}
}
@Test
public void testReadValueInjectablesIncorrectBehavior() throws JsonParseException, JsonMappingException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final InjectableValues injectableValues =
new InjectableValues.Std().addValue("defaultValueForField2", "somedefaultValue");
mapper.setInjectableValues(injectableValues);
final Some actualValueMissing = mapper.readValue("{\"field1\": \"field1value\"}", Some.class);
assertEquals(actualValueMissing.getField1(), "field1value");
assertEquals(actualValueMissing.getField2(), "somedefaultValue");
final Some actualValuePresent =
mapper.readValue("{\"field1\": \"field1value\", \"field2\": \"field2value\"}", Some.class);
assertEquals(actualValuePresent.getField1(), "field1value");
// unfortunately "field2value" is overrided because of putting "@JacksonInject" to the field
assertEquals(actualValuePresent.getField2(), "somedefaultValue");
}
Hope this helps to someone with a similar problem.
P.S. I'm using jackson v. 2.9.6
_route
is not the way to go and never was. It was always meant for debugging purposes according to Fabien who created Symfony. It is unreliable as it will not work with things like forwarding and other direct calls to controllers like partial rendering.
You need to inject your route's name as a parameter in your controller, see the doc here
Also, please never use $request->get('');
if you do not need the flexibility it is way slower than using get on the specific property bag that you need (attributes, query or request) so $request->attributes->get('_route');
in this case.
2020 answer
Just open the url. Facebook automatically registers for deep links.
let url = URL(string:"https://www.facebook.com/TheGoodLordAbove")!
UIApplication.shared.open(url,completionHandler:nil)
this opens in the facebook app if installed, and in your default browser otherwise
From the manpage of ld
(this does not work with gcc), referring to the --static
option:
You may use this option multiple times on the command line: it affects library searching for -l options which follow it.
One solution is to put your dynamic dependencies before the --static
option on the command line.
Another possibility is to not use --static
, but instead provide the full filename/path of the static object file (i.e. not using -l option) for statically linking in of a specific library. Example:
# echo "int main() {}" > test.cpp
# c++ test.cpp /usr/lib/libX11.a
# ldd a.out
linux-vdso.so.1 => (0x00007fff385cc000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f9a5b233000)
libm.so.6 => /lib/libm.so.6 (0x00007f9a5afb0000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f9a5ad99000)
libc.so.6 => /lib/libc.so.6 (0x00007f9a5aa46000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a5b53f000)
As you can see in the example, libX11
is not in the list of dynamically-linked libraries, as it was linked statically.
Beware: An .so
file is always linked dynamically, even when specified with a full filename/path.
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:
A.java
public class A {
private final String test;
public A(String test) {
this.test = test;
}
public String check() {
return "checked " + this.test;
}
}
MockA.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
@Test
public void test_not_mocked() throws Throwable {
assertThat(new A("random string").check(), equalTo("checked random string"));
}
@Test
public void test_mocked() throws Throwable {
A a = mock(A.class);
when(a.check()).thenReturn("test");
PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
assertThat(new A("random string").check(), equalTo("test"));
}
}
Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2
-webkit-box-shadow: 0 3px 5px -3px #000;
-moz-box-shadow: 0 3px 5px -3px #000;
box-shadow: 0 3px 5px -3px #000;
To Answer your question: now AWS make cloning real easy see Launch instance from your Existing Instance
This will take the existing instance as a Template for the new once.
or you can also take a snapshot of the existing volume and use the snapshot with the AMI (existing one) which you ping during your instance launch
code for a simple copy.
cp -r ./SourceFolder ./DestFolder
code for a copy with success result
cp -rv ./SourceFolder ./DestFolder
code for Forcefully if source contains any readonly file it will also copy
cp -rf ./SourceFolder ./DestFolder
for details help
cp --help
I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream
Follow the instructions at https://gist.github.com/application2000/73fd6f4bf1be6600a2cf9f56315a2d91 to set up the gcc version you need - gcc 5 or gcc 6 - on Ubuntu 14.04. The instructions include configuring update-alternatives
to allow you to switch between versions as you need to.
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
=> ["A", "B", "C"]
If vim is compiled with clipboard support, then you can use "*y
meaning: yank visually selected text into register *
('*' is for clipboard)
If there is no clipboard support, I think only other way is to use Ctrl+Insert
after visually selecting the text in vim.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy
Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS
Done in this order, it follows logic and no error occurs.
HERE is my FULL version in side htaccess with WordPress:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
You're calling br.readLine()
a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
The error is because fName
is included in the SELECT
list, but is not included in a GROUP BY
clause and is not part of an aggregate function (Count()
, Min()
, Max()
, Sum()
, etc.)
You can fix that problem by including fName
in a GROUP BY
. But then you will face the same issue with surname
. So put both in the GROUP BY
:
SELECT
fName,
surname,
Count(*) AS num_rows
FROM
author
INNER JOIN book
ON author.aID = book.authorID;
GROUP BY
fName,
surname
Note I used Count(*)
where you wanted SUM(orders.quantity)
. However, orders
isn't included in the FROM
section of your query, so you must include it before you can Sum()
one of its fields.
If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.
Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:
def copy_net(
infile: (str, 'The name of the file to send'),
host: (str, 'The host to send the file to'),
port: (int, 'The port to connect to')):
pass
example adopted from: https://pypi.org/project/autocommand/
Best solution for me so far
Select Database -> Right Click -> Tasks -> Generate Scripts - will open wizard for generating scripts. After choosing objects in set Scripting option click Advanced Button. Under "Script DROP and CREATE" select Script DROP.
Run script.
select username,
account_status
from dba_users
where lock_date is not null;
This will actually give you the list of locked users.
Simplest is to use this one-liner in csh/tcsh:
printf "%50s\n" '' | tr '[:blank:]' '[=]'
I have the same error I was replacing my Set with a new one get from Jackson.
To solve this I keep the existing set, I remove from the old set the element unknown into the new list with retainAll
.
Then I add the new ones with addAll
.
this.oldSet.retainAll(newSet);
this.oldSet.addAll(newSet);
No need to have the Session and manipulate it.
use -Wno-reorder
(man gcc is your friend :) )