This should work:
select * from syscat.tables
MySQL 5.7 now provides a JSON data type. This new datatype provides a convenient new way to store complex data: lists, dictionaries, etc.
That said, arrays don't map well databases which is why object-relational maps can be quite complex. Historically people have stored lists/arrays in MySQL by creating a table that describes them and adding each value as its own record. The table may have only 2 or 3 columns, or it may contain many more. How you store this type of data really depends on characteristics of the data.
For example, does the list contain a static or dynamic number of entries? Will the list stay small, or is it expected to grow to millions of records? Will there be lots of reads on this table? Lots of writes? Lots of updates? These are all factors that need to be considered when deciding how to store collections of data.
Also, Key/Value data stores, Document stores such as Cassandra, MongoDB, Redis etc provide a good solution as well. Just be aware of where the data is actually being stored (if its being stored on disk or in memory). Not all of your data needs to be in the same database. Some data does not map well to a relational database and you may have reasons for storing it elsewhere, or you may want to use an in-memory key:value database as a hot-cache for data stored on disk somewhere or as an ephemeral storage for things like sessions.
Another way based on a merge of serveral responses here before :
docker-compose file :
version: "3"
services:
db:
container_name: db
image: mysql
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=mysql
- MYSQL_DATABASE=db
volumes:
- /home/user/db/mysql/data:/var/lib/mysql
- /home/user/db/mysql/init:/docker-entrypoint-initdb.d/:ro
where /home/user
.. is a shared folder on the host
And in the /home/user/db/mysql/init
folder .. just drop one sql file, with any name, for example init.sql
containing :
CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'%' IDENTIFIED BY 'mysql';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' IDENTIFIED BY 'mysql';
USE mydb
CREATE TABLE CONTACTS (
[ ... ]
);
INSERT INTO CONTACTS VALUES ...
[ ... ]
According to the official mysql documentation, you can put more than one sql file in the docker-entrypoint-initdb.d
, they are executed in the alphabetical order
To check all disabled indexes on db
SELECT INDEX_SCHEMA, COLUMN_NAME, COMMENT
FROM information_schema.statistics
WHERE table_schema = 'mydb'
AND COMMENT = 'disabled'
Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.
it is better that you use the following query to get all column names easily
Show columns from tablename
oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.
olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..
Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.
In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.
As defined in the MySQL Glossary:
In MySQL, physically, a schema is synonymous with a database. You can substitute the keyword
SCHEMA
instead ofDATABASE
in MySQL SQL syntax, for example usingCREATE SCHEMA
instead ofCREATE DATABASE
.Some other database products draw a distinction. For example, in the Oracle Database product, a schema represents only a part of a database: the tables and other objects owned by a single user.
Use this query :
SELECT
t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name , *
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
Where
( c.name LIKE '%' + '<ColumnName>' + '%' )
AND
( t.type = 'U' ) -- Use This To Prevent Selecting System Tables
Rolling back last migration:
# rails < 5.0
rake db:rollback
# rails >= 5.0
rake db:rollback
# or
rails db:rollback
Rolling back last n
number of migrations
# rails < 5.0
rake db:rollback STEP=2
# rails >= 5.0
rake db:rollback STEP=2
# or
rails db:rollback STEP=2
Rolling back a specific migration
# rails < 5.0
rake db:migrate:down VERSION=20100905201547
# rails >= 5.0
rake db:migrate:down VERSION=20100905201547
# or
rails db:migrate:down VERSION=20100905201547
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
In Go with "sql.DB" (note the search_path
with underscore):
postgres://user:password@host/dbname?sslmode=disable&search_path=schema
Read about Storage Engines.
MyISAM:
The MyISAM storage engine in MySQL.
InnoDB:
The InnoDB storage engine in MySQL.
MyISAM Limitations:
InnoDB Limitations:
ROW_FORMAT=COMPRESSED
)For brief understanding read below links:
SELECT sys.columns.name AS ColumnName, tables.name AS TableName
FROM sys.columns
JOIN sys.tables ON sys.columns.object_id = tables.object_id
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
Super Key : Super key is a set of one or more attributes whose values identify tuple in the relation uniquely.
Candidate Key : Candidate key can be defined as a minimal subset of super key. In some cases , candidate key can not alone since there is alone one attribute is the minimal subset. Example,
Employee(id, ssn, name, addrress)
Here Candidate key is (id, ssn) because we can easily identify the tuple using either id or ssn . Althrough, minimal subset of super key is either id or ssn. but both of them can be considered as candidate key.
Primary Key : Primary key is a one of the candidate key.
Example : Student(Id, Name, Dept, Result)
Here
Super Key : {Id, Id+Name, Id+Name+Dept} because super key is set of attributes .
Candidate Key : Id because Id alone is the minimal subset of super key.
Primary Key : Id because Id is one of the candidate key
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
You can also try pressing the "FN" or function key with the button "Break" or with the button "sys rq" - system request as this - must be pressed together and this stops any running macro
SSIS Integration with Visual Studio 2017 available from Aug 2017.
SSIS designer is now available for Visual Studio 2017! ARCHIVE
I installed in July 2018 and appears working fine. See Download link
You can use lscache. It handles this for you automatically, including instances where the storage size exceeds the limit. If that happens, it begins pruning items that are the closest to their specified expiration.
From the readme
:
lscache.set
Stores the value in localStorage. Expires after specified number of minutes.
Arguments
key (string)
value (Object|string)
time (number: optional)
This is the only real difference between the regular storage methods. Get, remove, etc work the same.
If you don't need that much functionality, you can simply store a time stamp with the value (via JSON) and check it for expiry.
Noteworthy, there's a good reason why local storage is left up to the user. But, things like lscache do come in handy when you need to store extremely temporary data.
Perhaps what you're looking for is the SVG element's pointer-events property, which you can read about at the SVG w3C working group docs.
You can use CSS to set what happens to the SVG element when it is clicked, etc.
This is the only solution possible for using nothing but cut:
echo "s.t.r.i.n.g." | cut -d'.' -f2- [repeat_following_part_forever_or_until_out_of_memory:] | cut -d'.' -f2-
Using this solution, the number of fields can indeed be unknown and vary from time to time. However as line length must not exceed LINE_MAX characters or fields, including the new-line character, then an arbitrary number of fields can never be part as a real condition of this solution.
Yes, a very silly solution but the only one that meets the criterias I think.
For Oracle:
select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
As you have it, the argument w
is expecting a value after -w
on the command line. If you are just looking to flip a switch by setting a variable True
or False
, have a look here (specifically store_true and store_false)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')
where action='store_true'
implies default=False
.
Conversely, you could haveaction='store_false'
, which implies default=True
.
In this mode you can find all element which has class active and remove it
try this
$(document).ready(function() {
$(this.attr('id')).click(function () {
$(document).find('.active').removeClass('active');
var DivId = $(this).attr('id');
alert(DivId);
$(this).addClass('active');
});
});
An optimized Imran Tariq's version
Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();
Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.
When we are using normal text at that time we want <p>
tag.when we are using normal text with some effects at that time we want <span>
tag
Here is the fucntion
public int getIndexOfMax(ArrayList<Integer> arr){
int MaxVal = arr.get(0); // take first as MaxVal
int indexOfMax = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then MaxVal
if(arr.get(i) < MaxVal ){
MaxVal = arr.get(i); // put it in MaxVal
indexOfMax = i; // put index of current Max
}
}
return indexOfMax;
}
Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.
Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR
Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR
Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.
Credit to www.androidofficer.com
Use the -cp
or -classpath
switch.
$ java -help
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
...
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
(Note that the separator used to separate entries on the classpath differs between OSes, on my Windows machine it is ;
, in *nix it is usually :
.)
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
This exception comes when the service of docker is not running or the logged in user dont have the permission to access docker and generally it comes in RedHat
Using below command should resolve the issue
sudo service docker start
In the relevant page which makes a mixed content https to http call which is not accessible we can add the following entry in the relevant and get rid of the mixed content error.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<?php function writeUTF8File($filename,$content) { $f=fopen($filename,"w"); # Now UTF-8 - Add byte order mark fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); } ?>
1) Download toast-notifications-ios from this link
2) go to Targets -> Build Phases and add -fno-objc-arc to the "compiler Sources" for relevant files
3) make a function and #import "iToast.h"
-(void)showToast :(NSString *)strMessage {
iToast * objiTost = [iToast makeText:strMessage];
[objiTost setFontSize:11];
[objiTost setDuration:iToastDurationNormal];
[objiTost setGravity:iToastGravityBottom];
[objiTost show];
}
4) call where you need to display toast message
[self showToast:@"This is example text."];
I am afraid the body of your question is unrelated to title question.
If to answer the title:
In SQL, is UPDATE always faster than DELETE+INSERT?
then answer is NO!
Just google for
Such update(s) result in more costly (more processing) realization of update through insert+update than direct insert+update. These are the cases when
My fast (non-exhaustive) search, not pretending to be covering one, gave me [1], [2]
[1]
Update Operations
(Sybase® SQL Server Performance and Tuning Guide
Chapter 7: The SQL Server Query Optimizer)
http://www.lcard.ru/~nail/sybase/perf/11500.htm
[2]
UPDATE Statements May be Replicated as DELETE/INSERT Pairs
http://support.microsoft.com/kb/238254
As a follow on, you could select "all nodes with a particular attribute" like this:
//*[@id='4']
For whoever is using Kotlin, honestly the by far easiest way to iterate over a SparseArray is: Use the Kotlin extension from Anko or Android KTX! (credit to Yazazzello for pointing out Android KTX)
Simply call forEach { i, item -> }
Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.
A tutorial on the subject.
I'm amazed by everyone else's MUCH more complicated answers.
You can very simply define the alpha in the color definition of the button (or any other view) in your xml:
android:color="#66FF0000" // Partially transparent red
In the above example, the color would be a partially transparent red.
When defining the color of a view, the format can be either #RRGGBB
or #AARRGGBB
, where AA
is the hex alpha value. FF
would be fully opaque and 00
would be full transparent.
If you need to dynamically alter the opacity in your code, use
myButton.getBackground().setAlpha(128); // 50% transparent
Where the INT ranges from 0
(fully transparent) to 255
(fully opaque).
I made a little critters that lived in this little world. They had a neural network brain which received some inputs from the world and the output was a vector for movement among other actions. Their brains were the "genes".
The program started with a random population of critters with random brains. The inputs and output neurons were static but what was in between was not.
The environment contained food and dangers. Food increased energy and when you have enough energy, you can mate. The dangers would reduce energy and if energy was 0, they died.
Eventually the creatures evolved to move around the world and find food and avoid the dangers.
I then decided to do a little experiment. I gave the creature brains an output neuron called "mouth" and an input neuron called "ear". Started over and was surprised to find that they evolved to maximize the space and each respective creature would stay in its respective part (food was placed randomly). They learned to cooperate with each other and not get in each others way. There were always the exceptions.
Then i tried something interesting. I dead creatures would become food. Try to guess what happened! Two types of creatures evolved, ones that attacked like in swarms, and ones that were high avoidance.
So what is the lesson here? Communication means cooperation. As soon as you introduce an element where hurting another means you gain something, then cooperation is destroyed.
I wonder how this reflects on the system of free markets and capitalism. I mean, if businesses can hurt their competition and get away with it, then its clear they will do everything in their power to hurt the competition.
Edit:
I wrote it in C++ using no frameworks. Wrote my own neural net and GA code. Eric, thank you for saying it is plausible. People usually don't believe in the powers of GA (although the limitations are obvious) until they played with it. GA is simple but not simplistic.
For the doubters, neural nets have been proven to be able to simulate any function if they have more than one layer. GA is a pretty simple way to navigate a solution space finding local and potentially global minimum. Combine GA with neural nets and you have a pretty good way to find functions that find approximate solutions for generic problems. Because we are using neural nets, then we are optimizing the function for some inputs, not some inputs to a function as others are using GA
Here is the demo code for the survival example: http://www.mempko.com/darcs/neural/demos/eaters/ Build instructions:
darcs clone --lazy http://www.mempko.com/darcs/neural/
cd neural
cmake .
make
cd demos/eaters
./eaters
try this:
sudo pip install -i https://testpypi.python.org/pypi psycopg2==2.7b2
.. this is especially helpful if you're running into egg error
on aws ec2 instances if you run into gcc error; try this
1. sudo yum install gcc python-setuptools python-devel postgresql-devel
2. sudo su -
3. sudo pip install psycopg2
The namespace name http://www.w3.org/1999/xhtml
is intended for use in various specifications such as:
Recommendations:
XHTML™ 1.0: The Extensible HyperText Markup Language
XHTML Modularization
XHTML 1.1
XHTML Basic
XHTML Print
XHTML+RDFa
Check here for more detail
Use this
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>
In case of Debug Running
~/Library/Developer/Xcode/DerivedData/{your app}/Build/Products/Debug/{Project Name}.app/Contents/MacOS
You can find standalone executable file(Mach-O 64-bit executable x86_64)
Probably very late to the answer but I just read this while preparing for my 70-480
exam, and found this to work -
var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }
Notice the event as onclick
instead of onClick
.
JS Bin example.
Here's one-liner that I came up with recently for solving this problem. It's based on the setdefault dictionary method:
my_dict = {}
my_dict[key] = my_dict.setdefault(key, 0) + 1
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
You cannot truncate a datetime object because it is immutable.
However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:
newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)
Assuming i'm in a container with 15px padding, this is what i always use for the inner part:
width:auto;
right:15px;
left:15px;
That will stretch the inner part to whatever width it should be less the 15px either side.
The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.
In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.
var last_value;
var current_value;
$(document).on("click","select",function(){
last_value = $(this).val();
}).on("change","select",function(){
current_value = $(this).val();
console.log('last value - '+last_value);
console.log('current value - '+current_value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
_x000D_
For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.
Using a text editor, check for ^M
(control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.
sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt
You can use this conversion table: http://roselab.jhu.edu/~raj/MISC/hexdectxt.html
eg, if you want a transparency of 60%, you use 3C (hex equivalent).
This is usefull for IE background gradient transparency:
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454)";
where startColorstr and endColorstr: 2 first characters are a hex value for transparency, and the six remaining are the hex color.
Dmytro's answer works fine for my case. I think it's better to declare the function as synchronized. at least for my case, it would invoke null pointer exception otherwise, e.g. getWritableDatabase not yet returned in one thread and openDatabse called in another thread meantime.
public synchronized SQLiteDatabase openDatabase() {
if(mOpenCounter.incrementAndGet() == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.
Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";
You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.
Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.
var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
hash = type[1];
alert(hash);
Working demo on jsfiddle
basename
does remove the directory prefix of a path:
$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
In my project, the view controller is involved with lots of Constraints and StackView, and I set the TextView height as a constraint, and it varies based on the textView.contentSize.height value.
step1: get a IB outlet
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
step2: use the delegation method below.
extension NewPostViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewHeight.constant = self.textView.contentSize.height + 10
}
}
How about trying this:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
Use:
SELECT *
FROM `table`
WHERE INSTR(`column`, '{$needle}') > 0
Reference:
After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));
The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:
// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);
DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));
Here is how you can do it:
std::string & trim(std::string & str)
{
return ltrim(rtrim(str));
}
And the supportive functions are implemeted as:
std::string & ltrim(std::string & str)
{
auto it2 = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( str.begin() , it2);
return str;
}
std::string & rtrim(std::string & str)
{
auto it1 = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( it1.base() , str.end() );
return str;
}
And once you've all these in place, you can write this as well:
std::string trim_copy(std::string const & str)
{
auto s = str;
return ltrim(rtrim(s));
}
Try this
You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.
CSS:
.tinted { opacity: 0.8; }
If you're interested in better browser compatability, I suggest reading this:
http://css-tricks.com/css-transparency-settings-for-all-broswers/
If you're determined enough you can get this working as far back as IE7 (who knew!)
Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.
Similar to laszlo answer but you can reuse the same prototype cell for both the table cells and the section header cell. Add the first two functions below to your UIViewController subClass
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell") as! DataCell
cell.data1Label.text = "DATA KEY"
cell.data2Label.text = "DATA VALUE"
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 75
}
// Example of regular data cell dataDelegate to round out the example
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as! PlayerCell
cell.data1Label.text = "\(dataList[indexPath.row].key)"
cell.data2Label.text = "\(dataList[indexPath.row].value)"
return cell
}
I also faced with the same problem and "Find all references" for selected class has solved this issue.
Create a new user in the schema ‘mysql’ (mysql.user)
Run this code in your mysql work space
“GRANT ALL ON . to user@'%'IDENTIFIED BY '';
Open the ‘3306’ port at the machine which is having the Data Base.
Control Panel ->
Windows Firewall ->
Advance Settings ->
Inbound Rules ->
New Rule ->
Port ->
Next ->
TCP & set port as 3306 ->
Next ->
Next ->
Next ->
Fill Name and Description ->
Finish ->
Try to check by a telnet msg on cmd including DB server's IP
Start Android Studio. Close any open project.Go to File > Close Project.(Welcome window will open) Go to Configure > Settings. On Settings dialog,select Compiler (Gradle-based Android Projects) from left and set VM Options to -Xmx512m(i.e. write -Xmx512m under VM Options:) and press OK.
and then do this
Right click on My Computer and Open up your System Properties (The bit you had open before that shows your CPU/RAM values) >> On the left sidebar, click Advanced System Settings >> Click Environment Variables >> Under System Variables, press New >> Use the values below: // Variable name: _JAVA_OPTIONS // Variable value: -Xmx524M then, press OK and try again. restart Android Studio
In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:
template <class IntegerType>
class smart_integer {
public:
typedef integer_traits<Integer> traits;
IntegerType operator+=(IntegerType value){
typedef typename traits::larger_integer_t larger_t;
larger_t interm = larger_t(myValue) + larger_t(value);
if(interm > traits::max() || interm < traits::min())
throw overflow();
myValue = IntegerType(interm);
}
}
larger_integer_t
is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t
is a type. class, on the otherhand, has no such overloaded meaning.
That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.
You can do this by wrapping the page contents in a div with the following id styling applied:
<style>
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -60px;
}
</style>
<div id="wrap">
<!-- Your page content here... -->
</div>
Worked for me.
You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:
try
{
db.execSQL(Create_CashBook);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
}
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.
docker exec -t -i container_name /bin/bash
Will take you to the containers console.
File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/R.id.list_item_image"
android:layout_width="100dip"
android:layout_height="wrap_content" />
</LinearLayout>
Solution without Mocking class, Java9+ and Spring only.
FileItem fileItem = new DiskFileItemFactory().createItem("file",
Files.probeContentType(file.toPath()), false, file.getName());
try (InputStream in = new FileInputStream(file); OutputStream out = fileItem.getOutputStream()) {
in.transferTo(out);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);
Perhaps this will help someone, as the error message is extremely unhelpful, and I had gone through all of the standard permission steps numerous times to no avail.
Docker occasionally leaves ghost environment variables in place that block access, despite your system otherwise being correctly set up. The following shell commands may make it accessible again, if you have had it running at one point and it just stopped cooperating after a reboot:
unset DOCKER_HOST
unset DOCKER_TLS_VERIFY
unset DOCKER_TLS_PATH
docker ps
I had a previously working docker install, and after rebooting my laptop it simply refused to work. Was correctly added to the docker user group, had the correct permissions on the socket, etc, but could still not run docker login
, docker run ...
, etc. This fixed it for me. Unfortunately I have to run this on each reboot. This is mentioned on a couple of github issues also as a workaround, although it seems like a bug that this is a persistent barrier to correct operation of Docker (note: I am on Arch Linux, not OSX, but this was the same issue for me).
Hello i have got the same issue i was getting Optional(3) So, i have tried this below code
cell.lbl_Quantity.text = "(data?.quantity!)" //"Optional(3)"
let quantity = data?.quantity
cell.lbl_Quantity.text = "(quantity!)" //"3"
COLLATE UTF8_GENERAL_CI
will work as ignore-case.
USE:
SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';
or
SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';
Use first letter capital in the function name.
function App(){}
Here's a function to pretty up your json: pretty_json
You can use this approach:
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:MobileNumber"]]
iOS will automatically navigate from your app to the messages app's message composing page. Since the URL's scheme starts with sms:, this is identified as a type that is recognized by the messages app and launches it.
This works in Oracle:
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
The thing to remember here is to use the from dual
statement.
You're calling e.nextElement()
twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:
while(e.hasMoreElements()){
String param = e.nextElement();
System.out.println(param);
}
.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px; /* width of the image plus a little extra padding */
display: block; /* may not need this, but I've found I do */
}
Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).
I'm not sure, but I would guess they tested some sample of prime numbers and found that 31 gave the best distribution over some sample of possible Strings.
For the sake of completion, here's a Sass / Compass example which really shortens the code, the compiled CSS will include the necessary prefixes etc.
div
margin: 20px
width: 100px
height: 100px
background: #f00
+animation(spin 40000ms infinite linear)
+keyframes(spin)
from
+transform(rotate(0deg))
to
+transform(rotate(360deg))
The factory pattern is more flexible as it can return functions and values as well as objects.
There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be:
Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.
I would do this:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
Even if the filename is valid, you may still want to touch
it to be sure the user has permission to write.
If you won't be thrashing the disk with hundreds of files in a short period of time, I think creating an empty file is a reasonable approach.
If you really want something lighter, like just checking for invalid chars, then compare your filename against Path.GetInvalidFileNameChars().
Converting the date without specifying the current format can bring this error to you easily.
sdate <- "2015.10.10"
date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".
date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.
You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:
or on OS X:
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
Not sure if this is a good practice, but I noticed I can also get just the value by casting the series as float
.
e.g.
rate
3 0.042679
Name: Unemployment_rate, dtype: float64
float(rate)
0.0426789
You need to assign some height to make the overflow: auto;
property work.
For testing purpose, add height: 100px;
and check.
and also it will be better if you give overflow-y:auto;
instead of overflow: auto;
, because this makes the element to scroll only vertical but not horizontal.
float:left;
width:1000px;
overflow-y: auto;
height: 100px;
If you don't know the height of the container and you want to show vertical scrollbar when the container reaches a fixed height say 100px
, use max-height
instead of height
property.
For more information, read this MDN article.
User Endless is right,
$.browser.chrome = (typeof window.chrome === "object");
code is best to detect Chrome browser using jQuery.
If you using IE and added GoogleFrame as plugin then
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
If you just need the free space on a device, see the answer using os.statvfs()
below.
If you also need the device name and mount point associated with the file, you should call an external program to get this information. df
will provide all the information you need -- when called as df filename
it prints a line about the partition that contains the file.
To give an example:
import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
output.split("\n")[1].split()
Note that this is rather brittle, since it depends on the exact format of the df
output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc
filesystem below that are even less portable than this one.)
I've actually resorted to a bit of trickery to deal with this at times. I developed a jQuery scrollbar widget where I encountered the problem that I don't know ahead of time if the scrollable content is a part of a hidden piece of markup or not. Here's what I did:
// try to grab the height of the elem
if (this.element.height() > 0) {
var scroller_height = this.element.height();
var scroller_width = this.element.width();
// if height is zero, then we're dealing with a hidden element
} else {
var copied_elem = this.element.clone()
.attr("id", false)
.css({visibility:"hidden", display:"block",
position:"absolute"});
$("body").append(copied_elem);
var scroller_height = copied_elem.height();
var scroller_width = copied_elem.width();
copied_elem.remove();
}
This works for the most part, but there's an obvious problem that can potentially come up. If the content you are cloning is styled with CSS that includes references to parent markup in their rules, the cloned content will not contain the appropriate styling, and will likely have slightly different measurements. To get around this, you can make sure that the markup you are cloning has CSS rules applied to it that do not include references to parent markup.
Also, this didn't come up for me with my scroller widget, but to get the appropriate height of the cloned element, you'll need to set the width to the same width of the parent element. In my case, a CSS width was always applied to the actual element, so I didn't have to worry about this, however, if the element doesn't have a width applied to it, you may need to do some kind of recursive traversal of the element's DOM ancestry to find the appropriate parent element's width.
Ok, I think I have worked out "git stash unapply". It's more complex than git apply --reverse
because you need reverse merging action in case there was any merging done by the git stash apply
.
The reverse merge requires that all current changes be pushed into the index:
git add -u
Then invert the merge-recursive
that was done by git stash apply
:
git merge-recursive stash@{0}: -- $(git write-tree) stash@{0}^1
Now you will be left with just the non-stash changes. They will be in the index. You can use git reset
to unstage your changes if you like.
Given that your original git stash apply
failed I assume the reverse might also fail since some of the things it wants to undo did not get done.
Here's an example showing how the working copy (via git status
) ends up clean again:
$ git status
# On branch trunk
nothing to commit (working directory clean)
$ git stash apply
Auto-merging foo.c
# On branch trunk
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: foo.c
#
no changes added to commit (use "git add" and/or "git commit -a")
$ git add -u
$ git merge-recursive stash@{0}: -- $(git write-tree) stash@{0}^1
Auto-merging foo.c
$ git status
# On branch trunk
nothing to commit (working directory clean)
First of all, please remove the "{Not using Genymotion}" from the title. It distracts readers like me who don't know what Genymotion is. The absurd here is that you got the second highest voted answer with currently 90 points which says "go to GenyMotion settings"...
The main point that all the others have missed, is that you will get this error when you have a running adb process in the background. So the first step is to find it and kill it:
ps aux | grep adb
user 46803 0.0 0.0 2442020 816 s023 S+ 5:07AM 0:00.00 grep adb
user 46636 0.0 0.0 651740 3084 ?? S 5:07AM 0:00.02 adb -P 5037 fork-server server
When you find it, you can kill it using kill -9 46636
.
In my case, the problem was an old version of adb coming from GapDebug. If you got this with GapDebug, get out of it and then do
adb kill-server
adb start-server
because with GapDebug in the background, when you kill the adb server, GapDebug will start its own copy immediately, causing the start-server to be ignored
I read this question looking for an answer, and didn't like any of them.
So I wrote a quick and dirty solution. Just put this somewhere on your sys.path, and it'll add any directory under folder
(from the current working directory), or under abspath
:
#using.py
import sys, os.path
def all_from(folder='', abspath=None):
"""add all dirs under `folder` to sys.path if any .py files are found.
Use an abspath if you'd rather do it that way.
Uses the current working directory as the location of using.py.
Keep in mind that os.walk goes *all the way* down the directory tree.
With that, try not to use this on something too close to '/'
"""
add = set(sys.path)
if abspath is None:
cwd = os.path.abspath(os.path.curdir)
abspath = os.path.join(cwd, folder)
for root, dirs, files in os.walk(abspath):
for f in files:
if f[-3:] in '.py':
add.add(root)
break
for i in add: sys.path.append(i)
>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]
And I like it because I can have a folder for some random tools and not have them be a part of packages or anything, and still get access to some (or all) of them in a couple lines of code.
Try this formula in B2
cell
=IFERROR(INDEX($A$2:$A$7,MATCH(0,COUNTIF(B$1:$B1,$A$2:$A$7),0),1),"")
After click F2
and press Ctrl
+ Shift
+ Enter
Any of above solutions didn't work for me but I finally found it!
You should remove under folders in C:\Users\[your user]\VirtualBox VMs
.
I hope it helps you.
import android.support.v7.widget.RecyclerView;
In Android Studio, importing is not as intuitive as one would hope. Try importing this bit and see how it helps!
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
Only for modification time
if test `find "text.txt" -mmin +120`
then
echo old enough
fi
You can use -cmin
for change or -amin
for access time. As others pointed I don’t think you can track creation time.
I had the same issue as you, I figured it out. Facebook now roles some features as plugins. In the left hand side select Products and add product. Then select Facbook Login. Pretty straight forward from there, you'll see all the Oauth options show up.
One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior. Also, if one day you want to have multiple ways of doing that one thing, it can be rather painful to change, depending on how you lay out your code.
One thing to note, if you DO use singletons, try to pass them in to whoever needs them rather than have them access it directly... Otherwise if you ever choose to have multiple ways of doing the thing that singleton does, it will be rather difficult to change as each class embeds a dependency if it accesses the singleton directly.
So basically:
public MyConstructor(Singleton singleton) {
this.singleton = singleton;
}
rather than:
public MyConstructor() {
this.singleton = Singleton.getInstance();
}
I believe this sort of pattern is called dependency injection and is generally considered a good thing.
Like any pattern though... Think about it and consider if its use in the given situation is inappropriate or not... Rules are made to be broken usually, and patterns should not be applied willy nilly without thought.
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas
could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage
and fillText
, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle
and relative positions of parts of it using offsetTop
et al.)
Many people will feel surprised maybe, but this question is incorrect. If you hear this question during an interview, you need to help the interviewer understand where the confusion is.
Let's start from the fact that there is no concrete pattern that is called just "Factory". There is pattern that is called "Abstract Factory", and there is pattern that is called "Factory Method".
So, what does "Factory" mean then? one of the following (all can be considered correct, depending on the scope of the reference):
And, unfortunately, many people use "Factory" to denote another kind of factory, that creates factory or factories (or their interfaces). Based on their theory:
Product implements IProduct, which is created by Factory, which implements IFactory, which is created by AbstractFactory.
To understand how silly this is, let's continue our equation:
AbstractFactory implements IAbstractFactory, which is created by... AbstractAbstractFactory???
I hope you see the point. Don't get confused, and please don't invent things that don't exist for reason.
-
P.S.: Factory for Products is AbstractFactory, and Factory for Abstract Factories would be just another example of AbstractFactory as well.
Because abstract classes have state (fields) and somethimes they need to be initialized somehow.
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.If you want a specific version:
pip install numpy==1.8
If you have DotPeek
from JetBrains
, you can see it in Assembly Explorer
.
This what I came up with, since I need to run several operations in a chain.
<button onclick="tprom('Hello Niclas')">test promise</button>
<script>
function tprom(mess) {
console.clear();
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(mess);
}, 2000);
});
var promise2 = new Promise(async function (resolve, reject) {
await promise;
setTimeout(function () {
resolve(mess + ' ' + mess);
}, 2000);
});
var promise3 = new Promise(async function (resolve, reject) {
await promise2;
setTimeout(function () {
resolve(mess + ' ' + mess+ ' ' + mess);
}, 2000);
});
promise.then(function (data) {
console.log(data);
});
promise2.then(function (data) {
console.log(data);
});
promise3.then(function (data) {
console.log(data);
});
}
</script>
You should be using the thread pool (or async delgates, which in turn use the thread pool) so that the system can decide how many threads should run.
If you want to de-duplicate your array based on all arguments and not just one. You can use the uniqBy
function of lodash that can take a function as a second argument.
You will have this one-liner:
_.uniqBy(array, e => { return e.place && e.name })
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
Most GUIs assume that if you are in a directory and "open", double-click, or otherwise attempt to execute an .R file, that the directory in which it resides will be the working directory unless otherwise specified. The Mac GUI provides a method to change that default behavior which is changeable in the Startup panel of Preferences that you set in a running session and become effective at the next "startup". You should be also looking at:
?Startup
The RStudio documentation says:
"When launched through a file association, RStudio automatically sets the working directory to the directory of the opened file." The default setup is for RStudio to be register as a handler for .R files, although there is also mention of ability to set a default "association" with RStudio for .Rdata and .R extensions. Whether having 'handler' status and 'association' status are the same on Linux, I cannot tell.
This may be what you are looking for...
http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx
I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.
This code will help you to make a repeating alarm. The repeating time can set by you.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:paddingTop="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="@+id/ethr"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Hr"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etmin"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Min"
android:singleLine="true" />
<EditText
android:id="@+id/etsec"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Sec"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp">
<Button
android:id="@+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
int hr = 0;
int min = 0;
int sec = 0;
int result = 1;
AlarmManager alarmManager;
PendingIntent pendingIntent;
BroadcastReceiver mReceiver;
EditText ethr;
EditText etmin;
EditText etsec;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ethr = (EditText) findViewById(R.id.ethr);
etmin = (EditText) findViewById(R.id.etmin);
etsec = (EditText) findViewById(R.id.etsec);
RegisterAlarmBroadcast();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void onClickSetAlarm(View v) {
String shr = ethr.getText().toString();
String smin = etmin.getText().toString();
String ssec = etsec.getText().toString();
if(shr.equals(""))
hr = 0;
else {
hr = Integer.parseInt(ethr.getText().toString());
hr=hr*60*60*1000;
}
if(smin.equals(""))
min = 0;
else {
min = Integer.parseInt(etmin.getText().toString());
min = min*60*1000;
}
if(ssec.equals(""))
sec = 0;
else {
sec = Integer.parseInt(etsec.getText().toString());
sec = sec * 1000;
}
result = hr+min+sec;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
}
private void RegisterAlarmBroadcast() {
mReceiver = new BroadcastReceiver() {
// private static final String TAG = "Alarm Example Receiver";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
registerReceiver(mReceiver, new IntentFilter("sample"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast() {
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
}
If you need alarm only for a single time then replace
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
with
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
You should use the unslick method:
function getSliderSettings(){
return {
infinite: true,
slidesToShow: 3,
slidesToScroll: 1
}
}
$.ajax({
type: 'get',
url: '/public/index',
dataType: 'script',
data: data_send,
success: function() {
$('.skills_section').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
$('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
$('.skills_section').slick(getSliderSettings()); /* Initialize the slick again */
}
});
You may try to use pagehide event for Chrome and Safari
.
Check these links:
How to detect browser support for pageShow and pageHide?
http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.
If the user passes it to you, or it will wind up in a URL, you need to escape it.
If it appears in static text on a page? All browsers will get this one right either way, you don't worry much about it, since it will work.
This is what I am using:
Milliseconds to a pretty format time string:
function ms2Time(ms) {
var secs = ms / 1000;
ms = Math.floor(ms % 1000);
var minutes = secs / 60;
secs = Math.floor(secs % 60);
var hours = minutes / 60;
minutes = Math.floor(minutes % 60);
hours = Math.floor(hours % 24);
return hours + ":" + minutes + ":" + secs + "." + ms;
}
Short answer: no (easy?) way, but you can do something that serves your purpose.
I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:
spawn('bash', ['-i'], {
cwd: new_cwd,
env: new_env,
stdio: 'inherit'
});
After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:
However, for me, that differences are desirable.
Try the following:
<link rel="icon" type="image/png" href="img/iconimg.png" />
NB: The href
is the directory to your image example. Your image is in a folder called "img" and your image name is "iconimg" and if it is a png use .png
, if it is a jpg then .jpg
. Remember to do this in the head of your file and not in the body.
This is how you can do it from DB2 client.
Open the Command Editor and Run the select Query in the Commands Tab.
Open the corresponding Query Results Tab
Then from Menu --> Selected --> Export
Ubuntu reporsitories can be more useful
https://wiki.ubuntu.com/LucidLynx/ReleaseNotes#Sun%20Java%20moved%20to%20the%20Partner%20repository
In this example cafec_param
is a base class (parent class) and abc
is a child class. abc
calls the AWC
method in the base class.
class cafec_param:
def __init__(self,precip,pe,awc,nmonths):
self.precip = precip
self.pe = pe
self.awc = awc
self.nmonths = nmonths
def AWC(self):
if self.awc<254:
Ss = self.awc
Su = 0
self.Ss=Ss
else:
Ss = 254; Su = self.awc-254
self.Ss=Ss + Su
AWC = Ss + Su
return self.Ss
def test(self):
return self.Ss
#return self.Ss*4
class abc(cafec_param):
def rr(self):
return self.AWC()
ee=cafec_param('re',34,56,2)
dd=abc('re',34,56,2)
print(dd.rr())
print(ee.AWC())
print(ee.test())
Output
56
56
56
Seems like looking for something specific to the installed program would work better, but HKCU\Software and HKLM\Software are the spots to look.
null
is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.
There is only one way to represent null
in JSON. Per the specs (RFC 4627 and json.org):
2.1. Values A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true
You can populate the table until you have enough disk space. For better performance you can try migration to SQL Server 2005 and then partition the table and put parts on different disks(if you have RAID configuration that could really help you). Partitioning is possible only in enterprise version of SQL Server 2005. You can look partitioning example at this link: http://technet.microsoft.com/en-us/magazine/cc162478.aspx
Also you can try to create views for most used data portion, that is also one of the solutions.
Hope this helped...
Set your database collation
to UTF-8
then apply table collation
to database default.
I choose to use both methods. Cellpadding on the table as a fallback in case the inline style doesn't stick and inline style for most clients.
<table cellpadding="5">_x000D_
<tr>_x000D_
<td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
<td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
</tr>_x000D_
</table>
_x000D_
run composer update
. That's it
Surprisingly, no one mentioned this alternative that uses only built-in bash commands:
i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"
As an added bonus you can easily obtain the name of the parent directory with:
[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"
These will work on Bash 4.3-alpha or newer.
The idiomatic interface for 'getting a String' is to use the CustomStringConvertible
interface and access the description
getter. Define your enum
as:
enum Foo : CustomStringConvertible {
case Bing
case Bang
case Boom
var description : String {
switch self {
// Use Internationalization, as appropriate.
case .Bing: return "Bing"
case .Bang: return "Bang"
case .Boom: return "Boom"
}
}
}
In action:
> let foo = Foo.Bing
foo: Foo = Bing
> println ("String for 'foo' is \(foo)"
String for 'foo' is Bing
Updated: For Swift >= 2.0, replaced Printable
with CustomStringConvertible
Note: Using CustomStringConvertible
allows Foo
to adopt a different raw type. For example enum Foo : Int, CustomStringConvertible { ... }
is possible. This freedom can be useful.
Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing
#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()
Nicely explained above!
For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the %
with a !
So:
SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!
for finding a specific value of a column you can use the code below
irrespective of the preference you can use the any of the method you like
df.col_name.value_counts().Value_you_are_looking_for
take example of the titanic dataset
df.Sex.value_counts().male
this gives a count of all male on the ship Although if you want to count a numerical data then you cannot use the above method because value_counts() is used only with series type of data hence fails So for that you can use the second method example
the second method is
#this is an example method of counting on a data frame
df[(df['Survived']==1)&(df['Sex']=='male')].counts()
this is not that efficient as value_counts() but surely will help if you want to count values of a data frame hope this helps
I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.
This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.
I use this:
//http://detectmobilebrowsers.com/ + tablets
(function(a) {
if(/android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(ad|hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|playbook|silk/i.test(a)
||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
{
window.location="yourNewIndex.html"
}
})(navigator.userAgent||navigator.vendor||window.opera);
Open a basic text editor and type out your html. Save it as .html If you type in file:///C:/ into the address bar you can then navigate to your chosen file and run it. If you want to open a file that is on a server type in file:/// and instead of C:/ the first letter of the server followed by :/.
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
This formula will do the job:
=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)
you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1
.
The command is this:
mysqlcheck -u root -p --auto-repair --check --all-databases
You must supply the password when asked,
or you can run this one but it's not recommended because the password is written in clear text:
mysqlcheck -u root --password=THEPASSWORD --auto-repair --check --all-databases
Perhaps use tikz.
My solution that would work on Chrome, Firefox, IE9, IE10 (Change the degrees as per your requirement):
.rotate-text {
-webkit-transform: rotate(270deg);
-moz-transform: rotate(270deg);
-ms-transform: rotate(270deg);
-o-transform: rotate(270deg);
transform: rotate(270deg);
filter: none; /*Mandatory for IE9 to show the vertical text correctly*/
}
You can use drop command to delete meta data and actual data from HDFS.
And just to delete data and keep the table structure, use truncate command.
For further help regarding hive ql, check language manual of hive.
Since Python lists are zero-based, we can use the zip built-in function as follows:
>>> [i for i,j in zip(range(len(haystack)), haystack) if j == 'needle' ]
where "haystack" is the list in question and "needle" is the item to look for.
(Note: Here we are iterating using i to get the indexes, but if we need rather to focus on the items we can switch to j.)
const
is equivalent to #define
but only for value statements(e.g. #define myvalue = 2
). The value declared replaces the name of the variable before compilation.
static
is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.
As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.
Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.
public class Test
{
public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct
In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes. In managed languages, the only way to have the effect of a global variable is to declare it as static.
Have a Table class whose rows is a list of dict or better row objects
In table do not directly add rows but have a method which update few lookup maps e.g. for name if you are not adding rows in order or id are not consecutive you can have idMap too e.g.
class Table(object):
def __init__(self):
self.rows = []# list of row objects, we assume if order of id
self.nameMap = {} # for faster direct lookup for row by name
def addRow(self, row):
self.rows.append(row)
self.nameMap[row['name']] = row
def getRow(self, name):
return self.nameMap[name]
table = Table()
table.addRow({'ID':1,'name':'a'})
Same thing.. makes no difference at all... htm was used in the days where only 3 letter extensions were common.
For anyone interested in a shorter way:
gotdata = len(dlist)>1 and dlist[1] or 'null'
But for best performance, I suggest using False
instead of 'null'
, then a one line test will suffice:
gotdata = len(dlist)>1 and dlist[1]
Pylint message control is documented in the Pylint manual:
Is it possible to locally disable a particular message?
Yes, this feature has been added in Pylint 0.11. This may be done by adding
# pylint: disable=some-message,another-one
at the desired block level or at the end of the desired line of code.
You can use the message code or the symbolic names.
For example,
def test():
# Disable all the no-member violations in this function
# pylint: disable=no-member
...
global VAR # pylint: disable=global-statement
The manual also has further examples.
There is a wiki that documents all Pylint messages and their codes.
Alternatively you can install GNU date like so:
brew install coreutils
alias date="/usr/local/bin/gdate"
date +%s
1547838127Comments saying Mac has to be "different" simply reveal the commenter is ignorant of the history of UNIX. macOS is based on BSD UNIX, which is way older than Linux. Linux essentially was a copy of other UNIX systems, and Linux decided to be "different" by adopting GNU tools instead of BSD tools. GNU tools are more user friendly, but they're not usually found on any *BSD system (just the way it is).
Really, if you spend most of your time in Linux, but have a Mac desktop, you probably want to make the Mac work like Linux. There's no sense in trying to remember two different sets of options, or scripting for the mac's BSD version of Bash, unless you are writing a utility that you want to run on both BSD and GNU/Linux shells.
This is very good discussion. I had one of those moments when I wished or lets say hoped (successfully that I might add) to reinvent the wheel be it a square one. Any ways above is good discussion, so any one coming here looking for what is the difference between Element property and attribute. here is my penny worth and I did have to find it out hard way. I would keep it simple so no extraordinary tech jargon.
suppose we have a variable calls 'A'. what we are used to is as following.
Below will throw an error because simply it put its is kind of object that can only have one property and that is singular left hand side = singular right hand side object. Every thing else is ignored and tossed out in bin.
let A = 'f';
A.b =2;
console.log(A.b);
_x000D_
who has decided that it has to be singular = singular. People who make JavaScript and html standards and thats how engines work.
Lets change the example.
let A = {};
A.b =2;
console.log(A.b);
_x000D_
This time it works ..... because we have explicitly told it so and who decided we can tell it in this case but not in previous case. Again people who make JavaScript and html standards.
I hope we are on this lets complicate it further
let A = {};
A.attribute ={};
A.attribute.b=5;
console.log(A.attribute.b); // will work
console.log(A.b); // will not work
_x000D_
What we have done is tree of sorts level 1 then sub levels of non-singular object. Unless you know what is where and and call it so it will work else no.
This is what goes on with HTMLDOM when its parsed and painted a DOm tree is created for each and every HTML ELEMENT. Each has level of properties per say. Some are predefined and some are not. This is where ID and VALUE bits come on. Behind the scene they are mapped on 1:1 between level 1 property and sun level property aka attributes. Thus changing one changes the other. This is were object getter ans setter scheme of things plays role.
let A = {
attribute :{
id:'',
value:''
},
getAttributes: function (n) {
return this.attribute[n];
},
setAttributes: function (n,nn){
this.attribute[n] = nn;
if(this[n]) this[n] = nn;
},
id:'',
value:''
};
A.id = 5;
console.log(A.id);
console.log(A.getAttributes('id'));
A.setAttributes('id',7)
console.log(A.id);
console.log(A.getAttributes('id'));
A.setAttributes('ids',7)
console.log(A.ids);
console.log(A.getAttributes('ids'));
A.idsss=7;
console.log(A.idsss);
console.log(A.getAttributes('idsss'));
_x000D_
This is the point as shown above ELEMENTS has another set of so called property list attributes and it has its own main properties. there some predefined properties between the two and are mapped as 1:1 e.g. ID is common to every one but value is not nor is src. when the parser reaches that point it simply pulls up dictionary as to what to when such and such are present.
All elements have properties and attributes and some of the items between them are common. What is common in one is not common in another.
In old days of HTML3 and what not we worked with html first then on to JS. Now days its other way around and so has using inline onlclick become such an abomination. Things have moved forward in HTML5 where there are many property lists accessible as collection e.g. class, style. In old days color was a property now that is moved to css for handling is no longer valid attribute.
Element.attributes is sub property list with in Element property.
Unless you could change the getter and setter of Element property which is almost high unlikely as it would break hell on all functionality is usually not writable off the bat just because we defined something as A.item does not necessarily mean Js engine will also run another line of function to add it into Element.attributes.item.
I hope this gives some headway clarification as to what is what. Just for the sake of this I tried Element.prototype.setAttribute with custom function it just broke loose whole thing all together, as it overrode native bunch of functions that set attribute function was playing behind the scene.
try <div style = {{height:"100vh"}}> </div>
Just wanted to contribute a solution that I used for my app.
It is also based on the OnScrollListener
interface, but I found it to have a much better scrolling performance on low-end devices, since none of the visible/total count calculations are carried out during the scroll operations.
ListFragment
or ListActivity
implement OnScrollListener
Add the following methods to that class:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
where currentPage
is the page of your datasource that should be added to your list, and threshold
is the number of list items (counted from the end) that should, if visible, trigger the loading process. If you set threshold
to 0
, for instance, the user has to scroll to the very end of the list in order to load more items.
(optional) As you can see, the "load-more check" is only called when the user stops scrolling. To improve usability, you may inflate and add a loading indicator to the end of the list via listView.addFooterView(yourFooterView)
. One example for such a footer view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/progressBar1"
android:padding="5dp"
android:text="@string/loading_text" />
</RelativeLayout>
(optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView)
if there are no more items or pages.
You need to disable the button in the onsubmit
event of the <form>
:
<form action='/' method='POST' onsubmit='disableButton()'>
<input name='txt' type='text' required />
<button id='btn' type='submit'>Post</button>
</form>
<script>
function disableButton() {
var btn = document.getElementById('btn');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
Note: this way if you have a form element which has the required
attribute will work.
In the comments you asked if another view can be focused instead of the EditText. Yes it can. Use .requestFocus()
method for the view you want to be focused at the beginning (in onCreate() method)
Also focusing other view will cut out some amount of code. (code for hiding the keyboard for example)
Click on simulator , Navigate to Window and enable Device Bezels
Building on the original tweet from @rustyshelf, and illustrated answer from iDevzilla, here's a solution that silences the noise from the simulator without disabling NSLog output from the device.
Put
finish();
immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
$blog is an object not an array
try using $blog->id
instead of $blog['id']
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
a couple ways:
1. Absolute positioning-- you need to have a declared height to make this work:
<div>
<div class='center'>Hey</div>
</div>
div {height: 100%; width: 100%; position: relative}
div.center {
width: 100px;
height: 100px;
top: 50%;
margin-top: -50px;
}
*2. Use display: table http://jsfiddle.net/B7CpL/2/ *
<div>
<img src="/img.png" />
<div class="text">text centered with image</div>
</div>
div {
display: table;
vertical-align: middle
}
div img,
div.text {
display: table-cell;
vertical-align: middle
}
The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.
Instead of returning in the last iteration, just return true after the loop:
public static bool isTwenty(int num) {
for(int j = 1; j <= 20; j++) {
if(num % j != 0) {
return false;
}
}
return true;
}
Side note, there is a logical error in the original code. You are checking if num == 20
in the last condition, but you should have checked if j == 20
. Also checking if num % j == 0
was superflous, as that is always true when you get there.
Option Explicit
Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook
TitleId = 4
Resultid = 0
Dim FileName1, FileName2 As String
Dim Difference As Long
'TestPassCount = 0
'TestFailCount = 0
'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count
If (TestDataRowCount <= 2) Then
MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
For RecordId = 3 To TestDataRowCount
RefreshResultSheet
'Source File row count
SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
Set sourcewb = Workbooks.Open(SrceFile)
With sourcewb.Worksheets(1)
SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
sourcewb.Close
End With
'Target File row count
TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
Set targetwb = Workbooks.Open(TrgtFile)
With targetwb.Worksheets(1)
TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
targetwb.Close
End With
' Set Row Count Result Test data value
TitleId = TitleId + 3
Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value
'Compare Source and Target Row count
Resultid = TitleId + 1
Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
If (SourceRowCount = TargetRowCount) Then
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestPassCount = TestPassCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestFailCount = TestFailCount + 1
End If
'For comparison of two files
FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
FileName2 = Worksheets("TestData").Range("E" & RecordId).Value
Set myWorkbook1 = Workbooks.Open(FileName1)
Set myWorkbook2 = Workbooks.Open(FileName2)
Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
myWorkbook1.Close
myWorkbook2.Close
'MsgBox Difference
'Set Result of data validation in result sheet
Resultid = Resultid + 1
Worksheets("Result").Activate
Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"
If Difference > 0 Then
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestFailCount = TestFailCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestPassCount = TestPassCount + 1
End If
Next RecordId
End If
UpdateTestExecData TestPassCount, TestFailCount
End Sub
Sub RefreshResultSheet()
Worksheets("Result").Activate
Worksheets("Result").Range("B1:B4").Select
Selection.ClearContents
Worksheets("Result").Range("D1:D4").Select
Selection.ClearContents
Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub
Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
Worksheets("Result").Range("D2").Value = TestPassCount
Worksheets("Result").Range("D3").Value = TestFailCount
Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub
mysqldump -u root -p --no-data dbname > schema.sql
mysqldump -u root -p drop dbname
mysqldump -u root -p < schema.sql
REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).
First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).
EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.
Same problem here, I tried all solutions but nothing worked. Then I went into C:\Users\User_name
and deleted the ".android" folder and then, the SDK Manager could open normally, and automatically created other ".android" folder.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
One already exists. If you cannot get over the "Move" syntax of the System.IO
namespace. There is a static class FileSystem
within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory
and RenameFile
already within it.
As mentioned by SLaks, this is just a wrapper for Directory.Move
and File.Move
.
If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:
CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);
Drop a MongoDB database using python:
import argparse
import pymongo
if __name__ == "__main__":
"""
Drop a Database.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--host", default='mongodb://localhost:27017',
help="mongodb URI [default: %(default)s]")
parser.add_argument("--database", default=None,
help="database name: %(default)s]")
args = parser.parse_args()
client = pymongo.MongoClient(host=args.host)
if args.database in client.list_database_names():
client.drop_database(args.database)
print(f"Dropped: '{args.database}'")
else:
print(f"Database '{args.database}' does not exist")
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
var readSream = fs.createReadStream('index.html','utf8')
readSream.pipe(response);
}).listen(3000);
console.log("server is running on port number ");
In the latest release of Visual Studio Code, you can now drag the cursor while holding Option (Alt on Windows) to select the same column on multiple rows.
To enable this, make sure you change your editor.multiCursorModifier
to look like this:
"editor.multiCursorModifier": "ctrlCmd"
From the Visual Studio Code release notes 1.32.0:
In the following video, the selection begins as a regular selection and then Alt is pressed and held until the mouse button is released:
I'm doing something like that.
Getting the values in lowercase and MySQL does the rest
$string = $_GET['string'];
mysqli_query($con,"SELECT *
FROM table_name
WHERE LOWER(column_name)
LIKE LOWER('%$string%')");
And For MySQL PDO Alternative:
$string = $_GET['string'];
$q = "SELECT *
FROM table_name
WHERE LOWER(column_name)
LIKE LOWER(?);";
$query = $dbConnection->prepare($q);
$query->bindValue(1, "%$string%", PDO::PARAM_STR);
$query->execute();
Use:
>>> def round_to_nearest(n, m):
r = n % m
return n + m - r if r + r >= m else n - r
It does not use multiplication and will not convert from/to floats.
Rounding to the nearest multiple of 10:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 10)))
-21 => -20
-18 => -20
-15 => -10
-12 => -10
-9 => -10
-6 => -10
-3 => 0
0 => 0
3 => 0
6 => 10
9 => 10
12 => 10
15 => 20
18 => 20
21 => 20
24 => 20
27 => 30
As you can see, it works for both negative and positive numbers. Ties (e.g. -15 and 15) will always be rounded upwards.
A similar example that rounds to the nearest multiple of 5, demonstrating that it also behaves as expected for a different "base":
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 5)))
-21 => -20
-18 => -20
-15 => -15
-12 => -10
-9 => -10
-6 => -5
-3 => -5
0 => 0
3 => 5
6 => 5
9 => 10
12 => 10
15 => 15
18 => 20
21 => 20
24 => 25
27 => 25
Given that canvas is nothing without JavaScript, use JavaScript too for sizing and positionning (you know: onresize
, position:absolute
, etc.)
You could use the following:
$('[element]').trigger('reset')
You can use two elements, one inside the other, and give the outer one overflow: hidden
and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"
#outer {
width: 100px;
overflow: hidden;
padding-bottom: 10px;
}
#outer > div {
width: 100px;
height: 100px;
background: orange;
-moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}
Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/
Here's a function:
clear <- function() cat(c("\033[2J","\033[0;0H"))
then you can simply call it, as you call any other R function, clear()
.
If you prefer to simply type clear
(instead of having to type clear()
, i.e. with the parentheses), then you can do
clear_fun <- function() cat(c("\033[2J","\033[0;0H"));
makeActiveBinding("clear", clear_fun, baseenv())
Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.
Here's a set of basic rules:
program param1 param2 param 3
will pass four parameters to program.exe
:param1
, param2
, param
, and 3
.program one two "three and more"
will pass three parameters to program.exe
:one
, two
, and three and more
.hello"to the entire"world
acts as one parameter: helloto the entireworld
."Tim says, ""Hi!"""
will act as one parameter: Tim says, "Hi!"
Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:
" open double-quote group T inside ""s i inside ""s m inside ""s inside ""s - space doesn't separate s inside ""s a inside ""s y inside ""s s inside ""s , inside ""s inside ""s - space doesn't separate " close double-quoted group " quote directly follows closer - acts as plain unwrapped text: " H outside ""s - gets joined to previous adjacent group i outside ""s - ... ! outside ""s - ... " open double-quote group " close double-quote group " quote directly follows closer - acts as plain unwrapped text: "
Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,
is the first, wrapped to escape the spaces
"Hi!
is the second, not wrapped (there are no spaces)
is the third, a double-quote group wrapping nothing
"
is the fourth, the unwrapped close quote.
As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.
From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:
"Tim said to him, """What's been happening lately?""""
will print Tim said to him, "What's been happening lately?"
as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.
Here are a few examples to close it off:
program a b REM sends (a) and (b) program """a""" REM sends ("a") program """a b""" REM sends ("a) and (b") program """"Hello,""" Mike said." REM sends ("Hello," Mike said.) program ""a""b""c""d"" REM sends (abcd) since the "" groups wrap nothing program "hello to """quotes"" REM sends (hello to "quotes") program """"hello world"" REM sends ("hello world") program """hello" world"" REM sends ("hello world") program """hello "world"" REM sends ("hello) and (world") program "hello ""world""" REM sends (hello "world") program "hello """world"" REM sends (hello "world")
Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.
I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).
In addition to richq answer of using git log -g --grep=<regexp>
or git grep -e <regexp> $(git log -g --pretty=format:%h)
: take a look at the following blog posts by Junio C Hamano, current git maintainer
Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.
You can use git log --grep=<foo> --grep=<bar>
(or git log --author=<foo> --grep=<bar>
that internally translates to two --grep
) to find commits that match either of patterns (implicit OR semantic).
Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar>
to find commit that has both line matching first and line matching second somewhere.
With git grep
you can combine multiple patterns (all which must use the -e <regexp>
form) with --or
(which is the default), --and
, --not
, (
and )
. For grep --all-match
means that file must have lines that match each of alternatives.
To revert a merge commit, you need to use: git revert -m <parent number>
. So for example, to revert the recent most merge commit using the parent with number 1 you would use:
git revert -m 1 HEAD
To revert a merge commit before the last commit, you would do:
git revert -m 1 HEAD^
Use git show <merge commit SHA1>
to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2
git merge documentation: http://schacon.github.com/git/git-merge.html
git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt
This tutorial should help you:
Getting Started with Oracle SQL Developer
See the prerequisites:
Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:
alter user hr identified by hr account unlock;
Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.
Another version from May 2011: Getting Started with Oracle SQL Developer
For more info check this related question:
How to create a new database after initally installing oracle database 11g Express Edition?
One place where the use of *args
and **kwargs
is quite useful is for subclassing.
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
This code should fix your example:
ContentValues data=new ContentValues();
data.put("Field1","bob");
data.put("Field2",19);
data.put("Field3","male");
DB.update(Tablename, data, "_id=" + id, null);
You can do that using count
:
my_dict = {i:MyList.count(i) for i in MyList}
>>> print my_dict #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Or using collections.Counter
:
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
As stated in the Google documentation, Add the latest version of the Google Service plugin (4.0.1 on 06/04/18). Hope this hepls!
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:4.0.1' // google-services plugin
}
}
`
Use the ':visible' selector. Where .menuitem is the to-hide element(s) ...
$('body').click(function(){
$('.menuitem:visible').hide('fast');
});
Or if you already have the .menuitem element(s) in a var ...
var menitems = $('.menuitem');
$('body').click(function(){
menuitems.filter(':visible').hide('fast');
});
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
where T: class
literally means that T has to be a class
. It can be any reference type. Now whenever any code calls your DoThis<T>()
method it must provide a class to replace T. For example if I were to call your DoThis<T>()
method then I will have to call it like following:
DoThis<MyClass>();
If your metthod is like like the following:
public IList<T> DoThis<T>() where T : class
{
T variablename = new T();
// other uses of T as a type
}
Then where ever T appears in your method, it will be replaced by MyClass. So the final method that the compiler calls , will look like the following:
public IList<MyClass> DoThis<MyClass>()
{
MyClass variablename= new MyClass();
//other uses of MyClass as a type
// all occurences of T will similarly be replace by MyClass
}
From the docs on angular.element
:
find()
- Limited to lookups by tag name
So if you're not using jQuery with Angular, but relying upon its jqlite implementation, you can't do elm.find('#someid')
.
You do have access to children()
, contents()
, and data()
implementations, so you can usually find a way around it.
If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
use "not" in if-else
x = input()
if not x:
print("Value is not entered")
else:
print("Value is entered")
"abcd4yyyy" | grep 4 -c
gives the count as 1
I found a similar answer as teabot to create a MockFactory that provides the mocks. I used the following example to create the mock factory (since the link to narkisr are dead): http://hg.randompage.org/java/src/407e78aa08a0/projects/bookmarking/backend/spring/src/test/java/org/randompage/bookmarking/backend/testUtils/MocksFactory.java
<bean id="someFacade" class="nl.package.test.MockFactory">
<property name="type" value="nl.package.someFacade"/>
</bean>
This also helps to prevent that Spring wants to resolve the injections from the mocked bean.
This is usually caused by a program that writes into the event log and is then uninstalled or moved.