I think you summed it up quite well in your own answer.
In the process of UTF-8-ing(?) from end to end you might also want to make sure java itself is using UTF-8. Use -Dfile.encoding=utf-8 as parameter to the JVM (can be configured in catalina.bat).
If you installed MySQL Server and you still get
mysql -u root -p command not found
You're most likely experiencing this because you have an older mac version.
Try this:
in the home directory in terminal open -t .bash_profile
paste export PATH=${PATH}:/usr/local/mysql/bin/
inside and save it
instead of writing mysql -u root -p
paste the following in your terminal:
/usr/local/mysql/bin/mysql -u root -p
Enter your password. Now you're in.
How about:
insert into my_table values('hi, my name' + char(39) + 's tim.')
Try this:
var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
Well, I would do it like this:
select datediff(minute,'1990-1-1',datetime)
where '1990-1-1' is an arbitrary base datetime.
You have to update your app.config file manually
// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Do whatever you need, like modifying the appSettings section
// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
And then tell your application to reload any section you modified
ConfigurationManager.RefreshSection("appSettings");
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command %load
.
If you execute a cell containing:
%load filename.py
the content of filename.py
will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic %%writefile filename.py
at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a ?
: like %load?
or %%writefile?
.
For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.
See also: Magic functions from the official IPython docs.
You can access the USB drive by its drive letter. To know the drive letter you can run this command:
C:\>wmic logicaldisk where drivetype=2 get deviceid, volumename, description
From here you will get the drive letter (Device ID) of your USB drive.
For example if its F: then run the following command in command prompt to see its contents:
C:\> F:
F:\> dir
You could use curl
instead. It is installed by default into /usr/bin
.
System.out.println(list);//toString() is easy and good enough for debugging.
toString()
of AbstractCollection
will be clean and easy enough to do that. AbstractList
is a subclass of AbstractCollection
, so no need to for loop and no toArray() needed.
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
If you are using any custom object in your list, say Student , you need to override its toString()
method(it is always good to override this method) to have a meaningful output
See the below example:
public class TestPrintElements {
public static void main(String[] args) {
//Element is String, Integer,or other primitive type
List<String> sList = new ArrayList<String>();
sList.add("string1");
sList.add("string2");
System.out.println(sList);
//Element is custom type
Student st1=new Student(15,"Tom");
Student st2=new Student(16,"Kate");
List<Student> stList=new ArrayList<Student>();
stList.add(st1);
stList.add(st2);
System.out.println(stList);
}
}
public class Student{
private int age;
private String name;
public Student(int age, String name){
this.age=age;
this.name=name;
}
@Override
public String toString(){
return "student "+name+", age:" +age;
}
}
output:
[string1, string2]
[student Tom age:15, student Kate age:16]
I have faced the same issue with you, then solved it,
Here are solutions, I wish it maybe can help
First
In the IIS modules
Configuration, loop up the WebDAVModule, if your web server has it, then remove it
Second
In the IIS handler mappings
configuration, you can see the list of enabling handler, to choose the PHP item
, edit it, on the edit page, click request restrictions button, then select the verbs tab
in the modal, in the specify the verbs to be handle label, check the all verbs radio
, then click ok, you also maybe see a warning, it shows us that use double quotation marks to PHP-CGI execution, then do it
if done it, then restart IIS server, it will be ok
I know this has been answered, but I'd like to add my own answer:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}
If you not use maven, try to put your jars to WEB-INF/lib, it worked for me.
If the size of the subdirectory is not particularly huge, AND you wish to stay away from the CLI, here's a quick solution to manually reset the sub-directory:
Cheers. You just manually reset a sub-directory in your feature branch to be same as that of master branch !!
Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives).
If you have an int that you want to interpret as an unsigned value (e.g. you read an int from a DataInputStream
that you know should be interpreted as an unsigned value) then you can do the following trick.
int fourBytesIJustRead = someObject.getInt();
long unsignedValue = fourBytesIJustRead & 0xffffffffL;
Note, that it is important that the hex literal is a long literal, not an int literal - hence the 'L' at the end.
So starting with the answer given and applying the fact that CSS3 allows multiple settings - the below code is useful for creating a complete box:
#border {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
line-height: 100px;_x000D_
background: linear-gradient(to right, orange 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(blue 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(to right, green 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(red 50%, rgba(255, 255, 255, 0) 0%);_x000D_
background-position: top, right, bottom, left;_x000D_
background-repeat: repeat-x, repeat-y;_x000D_
background-size: 10px 1px, 1px 10px;_x000D_
}
_x000D_
<div id="border">_x000D_
bordered area_x000D_
</div>
_x000D_
Its worth noting that the 10px in the background size gives the area that the dash and gap will cover. The 50% of the background tag is how wide the dash actually is. It is therefore possible to have different length dashes on each border side.
Answering your question as the examples also given previously:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
Try a clear: left on #inner2. Because they are both being set to float it should cause a line return.
#inner1 {_x000D_
float:left; _x000D_
}_x000D_
_x000D_
#inner2{_x000D_
float:left; _x000D_
clear: left;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="inner1">This is inner div 1</div>_x000D_
<div id="inner2">This is inner div 2</div>_x000D_
</div>
_x000D_
The answers so far describe why, but here is a something else you might want to consider:
You can can call a method from an instantiable class by appending a method call to its constructor,
Object instance = new Constuctor().methodCall();
or
primitive name = new Constuctor().methodCall();
This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
You could code an ES5.1 helper function:
function setAttributes(el, attrs) {
Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}
Call it like this:
setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });
When using java -cp
you are required to provide fully qualified main class name, e.g.
java -cp com.mycompany.MyMain
When using java -jar myjar.jar
your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF
:
Main-Class: com.mycompany.MyMain
I made this script, It worked for my 10 pandas Data frames
from pyspark.sql.types import *
# Auxiliar functions
def equivalent_type(f):
if f == 'datetime64[ns]': return TimestampType()
elif f == 'int64': return LongType()
elif f == 'int32': return IntegerType()
elif f == 'float64': return FloatType()
else: return StringType()
def define_structure(string, format_type):
try: typo = equivalent_type(format_type)
except: typo = StringType()
return StructField(string, typo)
# Given pandas dataframe, it will return a spark's dataframe.
def pandas_to_spark(pandas_df):
columns = list(pandas_df.columns)
types = list(pandas_df.dtypes)
struct_list = []
for column, typo in zip(columns, types):
struct_list.append(define_structure(column, typo))
p_schema = StructType(struct_list)
return sqlContext.createDataFrame(pandas_df, p_schema)
You can see it also in this gist
With this you just have to call spark_df = pandas_to_spark(pandas_df)
I have an idea, which can work and it most likely to be very fast. You can sub-sample an image to say 80x60 resolution or comparable, and convert it to grey scale (after subsampling it will be faster). Process both images you want to compare. Then run normalised sum of squared differences between two images (the query image and each from the db), or even better Normalised Cross Correlation, which gives response closer to 1, if both images are similar. Then if images are similar you can proceed to more sophisticated techniques to verify that it is the same images. Obviously this algorithm is linear in terms of number of images in your database so even though it is going to be very fast up to 10000 images per second on the modern hardware. If you need invariance to rotation, then a dominant gradient can be computed for this small image, and then the whole coordinate system can be rotated to canonical orientation, this though, will be slower. And no, there is no invariance to scale here.
If you want something more general or using big databases (million of images), then you need to look into image retrieval theory (loads of papers appeared in the last 5 years). There are some pointers in other answers. But It might be overkill, and the suggest histogram approach will do the job. Though I would think combination of many different fast approaches will be even better.
Recursion-based, pure pathlib
solution:
from pathlib import Path
def remove_path(path: Path):
if path.is_file() or path.is_symlink():
path.unlink()
return
for p in path.iterdir():
remove_path(p)
path.rmdir()
Supports Windows and symbolic links
The error you mentioned happens when you have two versions of NumPy on your system. As you mentioned, the version of NumPy you imported is still not upgraded since you tried to upgrade it through pip (it will upgrade the version existing in '/Library/Python/2.7/site-packages'
).
However Python still loads the packages from '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy'
where the pre-installed packages live.
In order to upgrade that version you have to use easy_install
. The other way around this problem is using virtualenv
and setting up a new environment with all the requirements you need.
You can use like 'A%' expression, but if you want this query to run fast for large tables I'd recommend you to put number of first button into separate field with tiny int type.
innerHTML is a property of every element. It tells you what is between the starting and ending tags of the element, and it also let you sets the content of the element.
property describes an aspect of an object. It is something an object has as opposed to something an object does.
<p id="myParagraph">
This is my paragraph.
</p>
You can select the paragraph and then change the value of it's innerHTML with the following command:
document.getElementById("myParagraph").innerHTML = "This is my paragraph";
If you are using an input field and an icon (like this example):
<input name="hasta" id="Hasta" type="text" readonly />
<a href="#" id="Hasta_icono" ></a>
You can attach the datepicker to your icon (in my case inside the A tag via CSS) like this:
$("#Hasta").datepicker();
$("#Hasta_icono").click(function() {
$("#Hasta").datepicker( "show" );
});
Dot notation and the properties are equivalent. So you would accomplish like so:
var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)
(alerts "whatever")
I found this to be the best way to check for the platform of the system and the process:
bool 64BitSystem = Environment.Is64BitOperatingSystem;
bool 64BitProcess = Environment.Is64BitProcess;
The first property returns true for 64-bit system, and false for 32-bit. The second property returns true for 64-bit process, and false for 32-bit.
The need for these two properties is because you can run 32-bit processes on 64-bit system, so you will need to check for both the system and the process.
Nowadays there's a simpler way to achieve this if you are using a DialogFragment
(not a Fragment
):
val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
activity.supportFragmentManager,
"YOUR_TAG_FRAGMENT"
)
Under the hood, the show()
method does create a FragmentTransaction
and adds the tag by using the add()
method. But it's much more convenient to use the show()
method in my opinion.
You could shorten it for Fragment
too, by using a Kotlin Extension :)
I have Notepad++ 5.3.1 (UNICODE). I haven't done any magic and it works fine for me as described by you.
Maybe it depends on the (programming/markup/...) "Language"?
when using count(*)
the result is {'count(*)': 9}
-- where 9 represents the number of rows in the table, for the instance.
So, in order to fetch the just the number, this worked in my case, using mysql 8.
cursor.fetchone()['count(*)']
What will you do when a user hits ALT + F4 or closes it from Task Manager
Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."
Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)
Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function
http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html
will give you this.
std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);
std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...
BOOST_FOREACH(const int & i, boost::join(v0, v1)){
cout << i << endl;
}
should give you
1
2
3
4
5
6
Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.
From PHP 7.1 you can do this (Accepted rfc for negative string offsets):
<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();
I'll let you guess the output.
Also, I added this to xenonite's performance code with these results:
substr() took 7.0334868431091seconds
array access took 2.3111131191254seconds
Direct string access (negative string offsets) took 1.7971360683441seconds
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
a {
color: orange !important;
}
!important
has the effect that the property in question cannot be overridden unless another !important
is used. It is generally considered bad practice to use !important
unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited
using CSS only.
I had the same problem with PHP 5.2 and solved it with MySQL. Might not be exactly what you're looking for, but this will do the trick and return the number of days:
$datediff_q = $dbh->prepare("SELECT DATEDIFF(:date2, :date1)");
$datediff_q->bindValue(':date1', '2007-03-24', PDO::PARAM_STR);
$datediff_q->bindValue(':date2', '2009-06-26', PDO::PARAM_STR);
$datediff = ($datediff_q->execute()) ? $datediff_q->fetchColumn(0) : false;
More info here http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die()
statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx
or something similar to get only one row and not more. Also you can access your id like $row['id']
The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking
First, open up the document setting up the path of python
nano ~/.bash_profile
Then something like this shows up:
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH
The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
Change and save the file. Restart the computer, and typing in python3.7
, I get the python I installed for brew.
Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.
In iOS 5 you can change the navigationBar title color in this manner:
navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
I used angular with electron,
In my case, setInterval
returns a Nodejs Timer object. which when I called clearInterval(timerobject)
it did not work.
I had to get the id first and call to clearInterval
clearInterval(timerobject._id)
I have struggled many hours with this. hope this helps.
Here's quite a good example of how you can get caught out from not declaring local variables with var
:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i
is reset at every iteration of the loop, as it's not declared locally in the for
loop but globally) eventually resulting in infinite loop
Here is a javascript code I have tested successfully :
var txtFile = new XMLHttpRequest();
var allText = "file not found";
txtFile.onreadystatechange = function () {
if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
allText = txtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('txt').innerHTML = allText;
}
txtFile.open("GET", '/result/client.txt', true);
txtFile.send(null);
Though @chrisb's accepted answer does answer the question, I would like to add to it the following.
A simple method I use to get the nth
data or drop the nth
row is the following:
df1 = df[df.index % 3 != 0] # Excludes every 3rd row starting from 0
df2 = df[df.index % 3 == 0] # Selects every 3rd raw starting from 0
This arithmetic based sampling has the ability to enable even more complex row-selections.
This assumes, of course, that you have an index
column of ordered, consecutive, integers starting at 0.
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
var elem = $('#some-id');
elem.mouseover(function () {
// Some code here
}).mouseout(function (event) {
var e = event.toElement || event.relatedTarget;
if (elem.has(e).length > 0) return;
// Some code here
});
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
I just put one simple declaration of the app
var app = angular.module("app", ["xeditable"]);
Then I built one service and two controllers
For each controller I had a line in the JS
app.controller('EditableRowCtrl', function ($scope, CRUD_OperService) {
And in the HTML I declared the app scope in a surrounding div
<div ng-app="app">
and each controller scope separately in their own surrounding div (within the app div)
<div ng-controller="EditableRowCtrl">
This worked fine
Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider
From the help page for ?toupper
:
.simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
> sapply(name, .simpleCap)
zip code state final count
"Zip Code" "State" "Final Count"
On server, su to root and do this:
# mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql
(Note that the command at the end is of course mysql
, and, you're sending it to a table which happens to have the same name: mysql
.)
Next, you can now # ls /usr/share/zoneinfo
.
Use that command to see all the time zone info on ubuntu or almost any unixish server.
(BTW that's the convenient way to find the exact official name of some time zone.)
For example
mysql> select ts, CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') from example_table ;
+---------------------+-----------------------------------------+
| ts | CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') |
+---------------------+-----------------------------------------+
| 2020-10-20 16:59:57 | 2020-10-20 06:59:57 |
| 2020-10-20 17:02:59 | 2020-10-20 07:02:59 |
| 2020-10-20 17:30:08 | 2020-10-20 07:30:08 |
| 2020-10-20 18:36:29 | 2020-10-20 08:36:29 |
| 2020-10-20 18:37:20 | 2020-10-20 08:37:20 |
| 2020-10-20 18:37:20 | 2020-10-20 08:37:20 |
| 2020-10-20 19:00:18 | 2020-10-20 09:00:18 |
+---------------------+-----------------------------------------+
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
check this if it works it works fine for me
<script>
var windowObjectReference;
var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
}
</script>
The answers here are very good, but still insufficient for me.
I wrote a small loop that compares Uri.EscapeUriString
with Uri.EscapeDataString
for all characters from 0 to 255.
NOTE: Both functions have the built-in intelligence that characters above 0x80 are first UTF-8 encoded and then percent encoded.
Here is the result:
******* Different *******
'#' -> Uri "#" Data "%23"
'$' -> Uri "$" Data "%24"
'&' -> Uri "&" Data "%26"
'+' -> Uri "+" Data "%2B"
',' -> Uri "," Data "%2C"
'/' -> Uri "/" Data "%2F"
':' -> Uri ":" Data "%3A"
';' -> Uri ";" Data "%3B"
'=' -> Uri "=" Data "%3D"
'?' -> Uri "?" Data "%3F"
'@' -> Uri "@" Data "%40"
******* Not escaped *******
'!' -> Uri "!" Data "!"
''' -> Uri "'" Data "'"
'(' -> Uri "(" Data "("
')' -> Uri ")" Data ")"
'*' -> Uri "*" Data "*"
'-' -> Uri "-" Data "-"
'.' -> Uri "." Data "."
'_' -> Uri "_" Data "_"
'~' -> Uri "~" Data "~"
'0' -> Uri "0" Data "0"
.....
'9' -> Uri "9" Data "9"
'A' -> Uri "A" Data "A"
......
'Z' -> Uri "Z" Data "Z"
'a' -> Uri "a" Data "a"
.....
'z' -> Uri "z" Data "z"
******* UTF 8 *******
.....
'Ò' -> Uri "%C3%92" Data "%C3%92"
'Ó' -> Uri "%C3%93" Data "%C3%93"
'Ô' -> Uri "%C3%94" Data "%C3%94"
'Õ' -> Uri "%C3%95" Data "%C3%95"
'Ö' -> Uri "%C3%96" Data "%C3%96"
.....
EscapeUriString
is to be used to encode URLs, while EscapeDataString
is to be used to encode for example the content of a Cookie, because Cookie data must not contain the reserved characters '='
and ';'
.
This usually happens to me if I misplace a return statement, for example:
Adding a return statement, or in my case, moving it to correct scope will do the trick:
Also, we can use it following ways
To get only first
$cat_details = DB::table('an_category')->where('slug', 'people')->first();
To get by limit and offset
$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();
You can configure individual ObjectMappers like this:
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
If you want it set globally, I usually access a configured mapper through a wrapper class.
Try Ctrl+Alt+U
Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S
If you are looking to highlight a shell session command sequence as it looks to the user (with prompts, not just as contents of a hypothetical script file), then the right identifier to use at the moment is console:
```console
foo@bar:~$ whoami
foo
```
Working upon @Demosthenex work, @Tmdean and @Jon Crowell invaluable comments! (+1 them)
I save module files in git\ dir beside workbook location. Change that to your liking.
This will NOT track changes to Workbook code. So it's up to you to synchronize them.
Sub SaveCodeModules()
'This code Exports all VBA modules
Dim i As Integer, name As String
With ThisWorkbook.VBProject
For i = .VBComponents.count To 1 Step -1
If .VBComponents(i).Type <> vbext_ct_Document Then
If .VBComponents(i).CodeModule.CountOfLines > 0 Then
name = .VBComponents(i).CodeModule.name
.VBComponents(i).Export Application.ThisWorkbook.Path & _
"\git\" & name & ".vba"
End If
End If
Next i
End With
End Sub
Sub ImportCodeModules()
Dim i As Integer
Dim ModuleName As String
With ThisWorkbook.VBProject
For i = .VBComponents.count To 1 Step -1
ModuleName = .VBComponents(i).CodeModule.name
If ModuleName <> "VersionControl" Then
If .VBComponents(i).Type <> vbext_ct_Document Then
.VBComponents.Remove .VBComponents(ModuleName)
.VBComponents.Import Application.ThisWorkbook.Path & _
"\git\" & ModuleName & ".vba"
End If
End If
Next i
End With
End Sub
And then in Workbook module:
Private Sub Workbook_Open()
ImportCodeModules
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
SaveCodeModules
End Sub
i'd try tinyproxy. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for Lua, especially after seeing how well it worked for mysqlproxy
You can use below command to get list of files in easily human readable format.
ls -lrtsh
To add to the good answer by @Tomalak:
Here are some unmentioned and important differences:
xsl:apply-templates
is much richer and deeper than xsl:call-templates
and even from xsl:for-each
, simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
The code that will be applied
can be written way after the xsl:apply template
s was written and by
people that do not know the original author.
The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates>
instruction.
Summary: Templates and the <xsl:apply-templates>
instruction is how XSLT implements and deals with polymorphism.
Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"
brightness = sqrt(R^2+G^2+B^2)
was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.
change the focused border to none
TextField(
decoration: new InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
hintText: 'Subject'
),
),
A simple inline JavaScript confirm would suffice:
<form onsubmit="return confirm('Do you really want to submit the form?');">
No need for an external function unless you are doing validation, which you can do something like this:
<script>
function validate(form) {
// validation code here ...
if(!valid) {
alert('Please correct the errors in the form!');
return false;
}
else {
return confirm('Do you really want to submit the form?');
}
}
</script>
<form onsubmit="return validate(this);">
May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.
mysqldump --routines=true -u <user> my_database > my_database.sql
There is no best IDE. You make it as good as you get used using it.
Set
'auth' => false,
Also, see if port 25 works.
r = list(qs[:1])
if r:
return r[0]
return None
I'll like to add to this post, that I was experienceing the same issue but in a PartialView.
And I needed to add
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
To the partial view, even if already present in the _Layout view.
References:
hg rollback
is what you want.
In TortoiseHg, the hg rollback
is accomplished in the commit dialog. Open the commit dialog and select "Undo".
Someone has already mentioned the problem with the 32 bit OS. In my case the problem was that I was compiling with 32 bit JDK.
WHERE
clause is used to eliminate the tuples in a relation,and HAVING
clause is used to eliminate the groups in a relation.
HAVING
clause is used for aggregate functions such as
MIN
,MAX
,COUNT
,SUM
.But always use GROUP BY
clause before HAVING
clause to minimize the error.
A different take on authentication is Passwordless, a token-based authentication module for express that circumvents the inherent problem of passwords [1]. It's fast to implement, doesn't require too many forms, and offers better security for the average user (full disclosure: I'm the author).
This will be enough to set the file size to 0:
> error.log
In just a few words...
SAX (Simple API for XML): Is a stream-based processor. You only have a tiny part in memory at any time and you "sniff" the XML stream by implementing callback code for events like tagStarted()
etc. It uses almost no memory, but you can't do "DOM" stuff, like use xpath or traverse trees.
DOM (Document Object Model): You load the whole thing into memory - it's a massive memory hog. You can blow memory with even medium sized documents. But you can use xpath and traverse the tree etc.
Set<String> tabs = driver.getWindowHandles();
Iterator<String> it = tabs.iterator();
tab1 = it.next();
tab2 = it.next();
driver.switchTo().window(tab1);
driver.close();
driver.switchTo().window(tab2);
Try this. It should work
Sometimes you want to keep these things contained within your component. Depending on DOM state (the elements you're listening on must exist in DOM when your Vue component is instantiated), you can listen to events on elements outside of your component from within your Vue component. Let's say there is an element outside of your component, and when the user clicks it, you want your component to respond.
In html you have:
<a href="#" id="outsideLink">Launch the component</a>
...
<my-component></my-component>
In your Vue component:
methods() {
doSomething() {
// do something
}
},
created() {
document.getElementById('outsideLink').addEventListener('click', evt =>
{
this.doSomething();
});
}
As noted by others, bash
does not support floating point arithmetic, although you could fake it with some fixed decimal trickery, e.g. with two decimals:
echo $(( 100 * 1 / 3 )) | sed 's/..$/.&/'
Output:
.33
See Nilfred's answer for a similar but more concise approach.
Besides the mentioned bc
and awk
alternatives there are also the following:
clisp -x '(/ 1.0 3)'
with cleaned up output:
clisp --quiet -x '(/ 1.0 3)'
or through stdin
:
echo '(/ 1.0 3)' | clisp --quiet | tail -n1
echo 2k 1 3 /p | dc
echo 1/3.0 | genius
echo 1 3 div = | gs -dNODISPLAY -dQUIET | sed -n '1s/.*>//p'
echo 'pr 1/3.' | gnuplot
convert xc: -format '%[fx:1/3]' info:
or through stdin
:
echo 1/3 | { convert xc: -format "%[fx:$(cat)]" info:; }
echo 1/3 | jq -nf /dev/stdin
Or:
jq -n 1/3
echo 'print $(( 1/3. ))' | ksh
lua -e 'print(1/3)'
or through stdin:
echo 'print(1/3)' | lua
echo '1/3,numer;' | maxima
with cleaned up output:
echo '1/3,numer;' | maxima --quiet | sed -En '2s/[^ ]+ [^ ]+ +//p'
echo 1/3 | node -p
echo 1/3 | octave
echo print 1/3 | perl
echo print 1/3. | python2
echo 'print(1/3)' | python3
echo 1/3 | R --no-save
with cleaned up output:
echo 1/3 | R --vanilla --quiet | sed -n '2s/.* //p'
echo print 1/3.0 | ruby
units 1/3
with compact output:
units --co 1/3
echo 1/3 | wcalc
with cleaned up output:
echo 1/3 | wcalc | tr -d ' ' | cut -d= -f2
print $(( 1/3. ))
or through stdin
:
echo 'print $(( 1/3. ))' | zsh
#Other sources
Stéphane Chazelas answered a similar question over on Unix.SX.
There are several approaches to customize the error handling behavior with JAX-RS. Here are three of the easier ways.
The first approach is to create an Exception class that extends WebApplicationException.
Example:
public class NotAuthorizedException extends WebApplicationException {
public NotAuthorizedException(String message) {
super(Response.status(Response.Status.UNAUTHORIZED)
.entity(message).type(MediaType.TEXT_PLAIN).build());
}
}
And to throw this newly create Exception you simply:
@Path("accounts/{accountId}/")
public Item getItem(@PathParam("accountId") String accountId) {
// An unauthorized user tries to enter
throw new NotAuthorizedException("You Don't Have Permission");
}
Notice, you don't need to declare the exception in a throws clause because WebApplicationException is a runtime Exception. This will return a 401 response to the client.
The second and easier approach is to simply construct an instance of the WebApplicationException
directly in your code. This approach works as long as you don't have to implement your own application Exceptions.
Example:
@Path("accounts/{accountId}/")
public Item getItem(@PathParam("accountId") String accountId) {
// An unauthorized user tries to enter
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
This code too returns a 401 to the client.
Of course, this is just a simple example. You can make the Exception much more complex if necessary, and you can generate what ever http response code you need to.
One other approach is to wrap an existing Exception, perhaps an ObjectNotFoundException
with an small wrapper class that implements the ExceptionMapper
interface annotated with a @Provider
annotation. This tells the JAX-RS runtime, that if the wrapped Exception is raised, return the response code defined in the ExceptionMapper
.
No, there isn't.
<br>
is an HTML ELEMENT. It can't be replaced by a text node or part of a text node.
You can create a new-line effect using CR/LF inside a <pre>
element like below:
<pre>Line 1_x000D_
Line 2</pre>
_x000D_
But this is not the same as a <br>
.
Suppose your "Don't Check" list is on Sheet2 in cells A1:A100
, say, and your current client IDs are in Sheet1 in Column A.
What you would do is:
Conditional Formatting
> New Rule
> Use a Formula to determine which cells to format
=ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0))
and select how you want those rows formattedAnd that should do the trick.
I fixed this problem by running this in terminal. Full writeup is available over here
rvm install 2.2.0 --disable-binary
The rem
command is indeed for comments. It doesn't inherently update anyone after running the script. Some script authors might use it that way instead of echo
, though, because by default the batch interpreter will print out each command before it's processed. Since rem
commands don't do anything, it's safe to print them without side effects. To avoid printing a command, prefix it with @
, or, to apply that setting throughout the program, run @echo off
. (It's echo off
to avoid printing further commands; the @
is to avoid printing that command prior to the echo setting taking effect.)
So, in your batch file, you might use this:
@echo off
REM To skip the following Python commands, put "REM" before them:
python foo.py
python bar.py
1) Install GhostScript
2) Install ImageMagick
3) Create "Convert-to-TIFF.bat" (Windows XP, Vista, 7) and use the following line:
for %%f in (%*) DO "C:\Program Files\ImageMagick-6.6.4-Q16\convert.exe" -density 300 -compress lzw %%f %%f.tiff
Dragging any number of single-page PDF files onto this file will convert them to compressed TIFFs, at 300 DPI.
You can find the answer here: Is there a minlength validation attribute in HTML5?
Therefore this should do the job:
<input pattern=".{6,6}">
If the above solution doesn't work, check to see if you have $(LibraryPath) in Properties->VC++ Directories->Library Directories. If you are missing it, try adding it.
As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.
Not dependent on Java Math.round() types
The other solutions are great for a single if
/ else
construct. However, ternary statements within list comprehensions are arguably difficult to read.
Using a function aids readability, but such a solution is difficult to extend or adapt in a workflow where the mapping is an input. A dictionary can alleviate these concerns:
row = [None, 'This', 'is', 'a', 'filler', 'test', 'string', None]
d = {None: '', 'filler': 'manipulated'}
res = [d.get(x, x) for x in row]
print(res)
['', 'This', 'is', 'a', 'manipulated', 'test', 'string', '']
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
Just right click on your project and then go to
*Export -> Android -> Export Android Application -> YOUR_PROJECT_NAME -> Create new key store path -> Fill the detail -> Set the .apk location -> Now you can get your .apk file*
Install it in your mobile.
Regex to the rescue!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
Example:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
Here is a solution without eval nor $() nor `` :
ord () {
local s
printf -v s '\\%03o' $1
printf "$s"
}
ord 65
Here is the function:
function split(pString, pPattern)
local Table = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pPattern
local last_end = 1
local s, e, cap = pString:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(Table,cap)
end
last_end = e+1
s, e, cap = pString:find(fpat, last_end)
end
if last_end <= #pString then
cap = pString:sub(last_end)
table.insert(Table, cap)
end
return Table
end
Call it like:
list=split(string_to_split,pattern_to_match)
e.g.:
list=split("1:2:3:4","\:")
For more go here:
http://lua-users.org/wiki/SplitJoin
Give Java NIO a try:
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
Using transferFrom()
is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
Check more about it here.
Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.MAX_VALUE
will transfer at most 2^31 bytes, Long.MAX_VALUE
will allow at most 2^63 bytes (larger than any file in existence).
The simple approach (gcc -dM -E - < /dev/null
) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:
g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates
always fails, because it silently invokes the C-drivers (as if invoked by gcc
). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C
.
Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++
option to force the invocation of the C++ compiler (Credits for using the -x c++
options instead of an empty dummy file go to yuyichao, see below):
g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates
There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use
g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates
which finally yields
#define __cpp_alias_templates 200704
noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11
.
Another solution to the problem could be the following set of CSS rules:
.ellipsis{
white-space:nowrap;
overflow:hidden;
}
.ellipsis:after{
content:'...';
}
The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.
My two cents. Hats off to the original technique by Justin Maxwell
If you want it based on the screen height, and not the window height:
const height = 0.7 * screen.height
// jQuery
$('.header').height(height)
// Vanilla JS
document.querySelector('.header').style.height = height + 'px'
// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
node.style.height = height + 'px'
})
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
Better to use:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
In your web.config (on the server) add
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
</listeners>
</source>
</sources>
</system.diagnostics>
On Red Hat I had to do
sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python
Then it worked.
You could use std::numeric_limits<size_t>::max()
for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector
has size equal to std::numeric_limits<size_t>::max()
, then maximum allowed index will be (std::numeric_limits<size_t>::max()-1)
, since elements counted from 0.
You're almost there: it's NOW() - INTERVAL 1 DAY
From the Official documentation,
For example, to set the background color to orange:
<meta name="theme-color" content="#db5945">
In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:
<link rel="icon" sizes="192x192" href="nice-highres.png">
You can also use pyodbc with the MySQL Connector/ODBC to use MySQL on Windows. Unixodbc is also available to make the code compatible on Linux. Pyodbc uses the standard Python DB API 2.0 so if you stick with that switching between MySQL/PostgreSQL/SQLite/ODBC/JDBC drivers etc. should be relatively painless.
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
You can also use numpy.subtract
It has the advantage over the difference operator, -
, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:
array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
Example: (Python 3.5)
import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
which gives you
the difference = [ 0.1 0.2 0.3]
Remember, however, that if you try to subtract sequences (lists or tuples) with the -
operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays
Wrong Code:
print([1.1, 2.2, 3.3] - [1, 2, 3])
'CORRECTED VERSION OF LAST FUNCTION IN VISUAL BASIC BY GLENNG
Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
If _TimeoutMS <> 0 Then
w.Timeout = _TimeoutMS
End If
Return w '<<< NOTICE: MyBase.GetWebRequest(address) DOES NOT WORK >>>
End Function
Regex.Split("abc][rfd][5][,][.", @"\]\]");
just move image or shape
InflateException:
android.view.InflateException: Binary XML file line #32: Error inflating class androidx.appcompat.widget.SearchView
at android.view.LayoutInflater.createView(LayoutInflater.java:633)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at androidx.databinding.DataBindingUtil.inflate(DataBindingUtil.java:126)
at androidx.databinding.DataBindingUtil.inflate(DataBindingUtil.java:95)
at com.foamkart.Fragment.SearchFragment.onCreateView(SearchFragment.kt:37)
You can make a method just like new Date(year,month,date)
in your code by using Calendar
class.
private Date getDate(int year,int month,int date){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month-1);
cal.set(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
It will work just like the deprecated constructor of Date
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
In simple words we can say that in Dynamic Programming
(having problem sending message on network) one can first examine the path which takes the shortest time and then start journey,
On the other hand Greedy algorithm
take the optimal decision
on the spot without thinking for the next step and on the next step change its decision again and so on...
Notes:
Dynamic programming
is reliable while Greedy Algorithms is not reliable always.
Use an std::vector
.
std::vector< std::vector<int> > my_array; /* 2D Array */
my_array.size(); /* size of y */
my_array[0].size(); /* size of x */
Or, if you can only use a good ol' array, you can use sizeof
.
sizeof( my_array ); /* y size */
sizeof( my_array[0] ); /* x size */
Your code can be factored to this (in lieu of File.ReadAllBytes):
public byte[] ReadAllBytes(string fileName)
{
byte[] buffer = null;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
}
return buffer;
}
Note the Integer.MaxValue - file size limitation placed by the Read method. In other words you can only read a 2GB chunk at once.
Also note that the last argument to the FileStream is a buffer size.
I would also suggest reading about FileStream and BufferedStream.
As always a simple sample program to profile which is fastest will be most beneficial.
Also your underlying hardware will have a large effect on performance. Are you using server based hard disk drives with large caches and a RAID card with onboard memory cache? Or are you using a standard drive connected to the IDE port?
https://github.com/Glavin001/atom-beautify
Includes many different languages, html too..
mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds | Query | 0 | init | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds | Sleep | 4 | | NULL |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)
mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)
USER 192 :
mysql> SELECT * FROM exept;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query
You are opening the csv file in binary mode, it should be 'w'
import csv
# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
fieldnames = ["SNo", "States", "Dist", "Population"]
writer = csv.DictWriter(w, fieldnames=fieldnames)
# write list of dicts
writer.writerows(list_of_dicts) #writerow(dict) if write one row at time
In swift 3
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
self.navigationController?.pushViewController(nextVC, animated: true)
This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse
Relevant bits below:
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
return Response;
REPLACE INTO table(column_list) VALUES(value_list);
is a shorter form of
INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.
REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.
This is a work around.. not checked the speed..
INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
followed by
UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
This method allows a replace to occur without causing a trigger.
class FormPage extends React.Component{
constructor(props){
super(props);
this.state = {
hidediv: false
}
}
handleClick = (){
this.setState({
hidediv: true
});
}
render(){
return(
<div>
<div className="date-range" hidden = {this.state.hidediv}>
<input type="submit" value="Search" onClick={this.handleClick} />
</div>
<div id="results" className="search-results" hidden = {!this.state.hidediv}>
Some Results
</div>
</div>
);
}
}
A Swift 3 solution along the lines of Sunkas's:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Use:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Output:
foo?
Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.
Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422
Error message clearly says that source
parameter is null
. Source is the enumerable you are enumerating. In your case it is ListMetadataKor
object. And its definitely null
at the time you are filtering it second time. Make sure you never assign null
to this list. Just check all references to this list in your code and look for assignments.
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
If you face the problem in Ruby on Rails, the exhaustive solution is provided by Bootstrap Ruby Gem readme file.
or in short:
application.css
to application.scss
@import "bootstrap";
gem 'jquery-rails'
to Gemfile
unless it exists.//= require jquery3
//= require popper
//= require bootstrap
//= require bootstrap-sprockets
to application.js
.The accepted answer is really helpful! Just to add that process substitution (i.e., <(COMMAND)
) is not supported in some shells (e.g., dash
).
In my case, I was trying to create a custom action (basically a one-line shell script) in Thunar file manager to start a shell and activate the selected Python virtual environment. My first attempt was:
urxvt -e bash --rcfile <(echo ". $HOME/.bashrc; . %f/bin/activate;")
where %f
is the path to the virtual environment handled by Thunar.
I got an error (by running Thunar from command line):
/bin/sh: 1: Syntax error: "(" unexpected
Then I realized that my sh
(essentially dash
) does not support process substitution.
My solution was to invoke bash
at the top level to interpret the process substitution, at the expense of an extra level of shell:
bash -c 'urxvt -e bash --rcfile <(echo "source $HOME/.bashrc; source %f/bin/activate;")'
Alternatively, I tried to use here-document for dash
but with no success. Something like:
echo -e " <<EOF\n. $HOME/.bashrc; . %f/bin/activate;\nEOF\n" | xargs -0 urxvt -e bash --rcfile
P.S.: I do not have enough reputation to post comments, moderators please feel free to move it to comments or remove it if not helpful with this question.
Shorter syntax
select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
END
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
In cassandra , the difference between primary key,partition key,composite key, clustering key always makes some confusion.. So I am going to explain below and co relate to each others. We use CQL (Cassandra Query Language) for Cassandra database access. Note:- Answer is as per updated version of Cassandra. Primary Key :-
CREATE TABLE Cass (
id int PRIMARY KEY,
name text
);
Create Table Cass (
id int,
name text,
PRIMARY KEY(id)
);
In CQL, the order in which columns are defined for the PRIMARY KEY matters. The first column of the key is called the partition key having property that all the rows sharing the same partition key (even across table in fact) are stored on the same physical node. Also, insertion/update/deletion on rows sharing the same partition key for a given table are performed atomically and in isolation. Note that it is possible to have a composite partition key, i.e. a partition key formed of multiple columns, using an extra set of parentheses to define which columns forms the partition key.
Partitioning and Clustering The PRIMARY KEY definition is made up of two parts: the Partition Key and the Clustering Columns. The first part maps to the storage engine row key, while the second is used to group columns in a row.
CREATE TABLE device_check (
device_id int,
checked_at timestamp,
is_power boolean,
is_locked boolean,
PRIMARY KEY (device_id, checked_at)
);
Here device_id is partition key and checked_at is cluster_key.
We can have multiple cluster key as well as partition key too which depends on declaration.
If you have a List
of objects, you can serialize them to JSON as follow:
List<MyObjectClass> listOfObjects = new List<MyObjectClass>();
And then use addParameter
:
requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));
And you wil need to set the request format to JSON
:
requestREST.RequestFormat = DataFormat.Json;
I created a library to address the need for a page indicator in a ViewPager. My library contains a View called DotIndicator. To use my library, add compile 'com.matthew-tamlin:sliding-intro-screen:3.2.0'
to your gradle build file.
The View can be added to your layout by adding the following:
<com.matthewtamlin.sliding_intro_screen_library.indicators.DotIndicator
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:numberOfDots=YOUR_INT_HERE
app:selectedDotIndex=YOUR_INT_HERE/>
The above code perfectly replicates the functionality of the dots on the Google Launcher homescreen, however if you want to further customise it then the following attributes can be added:
app:unselectedDotDiameter
and app:selectedDotDiameter
to set the diameters of the dotsapp:unselectedDotColor
and app:selectedDotColor
to set the colors of the dotsapp:spacingBetweenDots
to change the distance between the dotsapp:dotTransitionDuration
to set the time for animating the change from small to big (and back)Additionally, the view can be created programatically using:
DotIndicator indicator = new DotIndicator(context);
Methods exist to modify the properties, similar to the attributes. To update the indicator to show a different page as selected, just call method indicator.setSelectedItem(int, true)
from inside ViewPager.OnPageChangeListener.onPageSelected(int)
.
Here's an example of it in use:
If you're interested, the library was actually designed to make intro screens like the one shown in the above gif.
Github source available here: https://github.com/MatthewTamlin/SlidingIntroScreen
Use parameter expansion, if the value is already stored in a variable.
$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}
Or use read
$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"
Either way,
$ echo $value
7.092200e-01
If you don't mind using jQuery, then you can use offset()
function. Refer to documentation if you want to read up more about this function.
The only thing that worked for me was uninstalling R entirely (make sure to remove it from the Programs files as well), and install it, but unselect Message Translations during the installation process. When I installed R, and subsequently RCmdr, it finally came up in English.
If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.
I'm seeing different behaviors between Windows 10 and Windows Server 2016 and between IE and Edge. I tested using www.microsoft.com.
Windows Server 2016 IE 11:
Favorites: site icon
Address bar: site icon
Browser tab: site icon
Windows 10 IE 11:
Favorites: site icon
Address bar: generic blue-E icon
Browser tab: generic blue-E icon
Windows 10 Edge:
Favorites: site icon
Address bar: no icon
Browser tab: site icon
What's the deal with Windows 10 IE showing the generic icon?
After spending hours on this issue found solution here
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule
]
})
Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
yourCommand && (
echo yourCommand was successful
) || (
echo yourCommand failed
)
There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.
yourCommand && (
someCommandThatMayFail
) || (
echo This will fire if yourCommand or someCommandThatMayFail raises an error
)
The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call )
, which does nothing except set the ERRORLEVEL to 0. There is a corollary (call)
that does nothing except set the ERRORLEVEL to 1.
yourCommand && (
someCommandThatMayFail
(call )
) || (
echo This can only fire if yourCommand raises an error
)
See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.
Are you asking how to bring up a command windows? If so, you can use the Process object ...
Process.Start("cmd");
As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.
But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.
There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.
PM> Install-Package CSharpVitamins.ShortGuid
Usage:
Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine(sguid1);
Console.WriteLine(sguid1.Guid);
This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:
ShortGuid: FEx1sZbSD0ugmgMAF_RGHw
Guid: b1754c14-d296-4b0f-a09a-030017f4461f
Check your routing method:
if your routing state is like this
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
}
}
})
then you should use
$location.path("/app/register");
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...
The relativedelta function from dateutil function (a powerful extension to the datetime lib)
import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)
>2015-03-01 2015-02-28
Maybe I am off the mark here and not understanding the OP but why are you joining tables?
If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.
SELECT group_id, COUNT(*) as membercount
FROM members
GROUP BY group_id
HAVING membercount > 4
This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.
If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.
In current release
Assuming you have handled the verification of the request to reset the forgotten password, use following code as a sample code steps.
ApplicationDbContext =new ApplicationDbContext()
String userId = "<YourLogicAssignsRequestedUserId>";
String newPassword = "<PasswordAsTypedByUser>";
ApplicationUser cUser = UserManager.FindById(userId);
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
store.SetPasswordHashAsync(cUser, hashedNewPassword);
In AspNet Nightly Build
The framework is updated to work with Token for handling requests like ForgetPassword. Once in release, simple code guidance is expected.
Update:
This update is just to provide more clear steps.
ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
String userId = User.Identity.GetUserId();//"<YourLogicAssignsRequestedUserId>";
String newPassword = "test@123"; //"<PasswordAsTypedByUser>";
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
ApplicationUser cUser = await store.FindByIdAsync(userId);
await store.SetPasswordHashAsync(cUser, hashedNewPassword);
await store.UpdateAsync(cUser);
The ruby version 1.8.7 seems to be your system ruby.
Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:
rvm use 2.0.0
You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.
Update: To set the ruby as default:
rvm use 2.0.0 --default
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")].
zip, sort by the second column, return the first column.
zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc.
You will need to use jQuery .load()
method to do stuff after image load.
$('yourimageselector').attr('src', 'newsrc').load(function(){
this.width; // Note: $(this).width() will not work for in memory images
});
Reason for editing: https://stackoverflow.com/a/670433/561545
Add tomcat in Eclipse
In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like
You can make use of the first-child selector
<div class="sidebar">
<div class="box">
<p>
Text is here
</p>
</div>
<div class="box">
<p>
Text is here
</p>
</div>
</div>
and in CSS
.box {
padding: 10px;
text-align: justify;
margin-top: 20px;
}
.box:first-child {
margin-top: none;
}
My problem was installing the Android SDK in Eclipse Helios on Windows 7 Enterprise 64bit, I was getting the following error:
Missing requirement: Android Development Tools 0.9.7.v201005071157-36220 (com.android.ide.eclipse.adt.feature.group 0.9.7.v201005071157-36220) requires 'org.eclipse.jdt.junit 0.0.0' but it could not be found
Having followed the advice above to ensure that the JDK was in my PATH variable (it wasn't), installation went smoothly. I guess the error was somewhat spurious (incidentally if you're looking for the JARs that correspond to that class, they were in my profile rather than the Eclipse installation directory)
So, check that PATH variable!
You should install this Apache mod, http://httpd.apache.org/docs/2.0/mod/mod_info.html, it basically gives you a run down of the mods you're using and the Apache settings. I have this enabled on my Apache and it gives me this info for my website,
Server Version: Apache/2.2.3 (Debian) mod_jk/1.2.18 PHP/5.2.0-8+etch13 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8
Option 1: Go to Settings-> search Reset advertising ID -> click on Reset advertising ID -> OK. You should start receiving Ads now
No search option? Try Option 2
Option 2: Go to Settings->Google->Ads->Reset advertising ID->OK
No Google options in Settings? Try Option 3
Option 3:Look for Google Settings (NOT THE SETTINGS)->Ads->Reset advertising ID
I had this problem with a a number of divs that were inserted in another div with position: absolute
, the inserted divs had no position attribute. When I changed this to position:relative
it worked fine. (was really hard to pinpoint the problem)
In my case the elements where inserted by Angular with ng-repeat
.
There already exists a function for this:
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
itemgetter
will return a tuple if more than one argument is passed. To pass a list to itemgetter
, use
itemgetter(*wanted_keys)(my_dict)
Keep in mind that itemgetter
does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.
Alternatively, you can pass an empty tick position and label as
# for matplotlib.pyplot
# ---------------------
plt.xticks([], [])
# for axis object
# ---------------
# from Anakhand May 5 at 13:08
# for major ticks
ax.set_xticks([])
# for minor ticks
ax.set_xticks([], minor=True)
I'm using OS X 10.10, open the shell, type
export PATH=$PATH:/usr/local/mysql/bin
it works temporary.if you use Command+T to open a new tab ,mysql command will not work anymore.
We need to create a .bash_profile file to make it work each time you open a new tab.
nano ~/.bash_profile
add the following line to the file.
# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc
Save the file, then open a new shell tab, it works like a charm..
by the way, why not try https://github.com/dbcli/mycli
pip install -U mycli
it's a tool way better than the mysqlcli.. A command line client for MySQL that can do auto-completion and syntax highlighting
"if you restore the primary key, you sure may revert it back to AUTO_INCREMENT"
There should be no question of whether or not it is desirable to "restore the PK property" and "restore the autoincrement property" of the ID column.
Given that it WAS an autoincrement in the prior definition of the table, it is quite likely that there exists some program that inserts into this table without providing an ID value (because the ID column is autoincrement anyway).
Any such program's operation will break by not restoring the autoincrement property.
Or you can always use the communicate method on the subprocess objects.
cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)
The communicate method returns a tuple of the standard output and the standard error.
You can run a batch file that calls your program, check out the discussion here for how to do it: http://www.pcworld.com/article/115628/windows_tips_make_windows_start_and_stop_the_way_you_want.html
(from google search: windows schedule task run at shut down)
Python added the @overload decorator with PEP-3124 to provide syntactic sugar for overloading via type inspection - instead of just working with overwriting.
Code example on overloading via @overload from PEP-3124
from overloading import overload
from collections import Iterable
def flatten(ob):
"""Flatten an object to its component iterables"""
yield ob
@overload
def flatten(ob: Iterable):
for o in ob:
for ob in flatten(o):
yield ob
@overload
def flatten(ob: basestring):
yield ob
is transformed by the @overload-decorator to:
def flatten(ob):
if isinstance(ob, basestring) or not isinstance(ob, Iterable):
yield ob
else:
for o in ob:
for ob in flatten(o):
yield ob
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
This should work for both strings and unicode objects in Python2, and both strings and bytes in Python3:
# python <3.0
def only_numerics(seq):
return filter(type(seq).isdigit, seq)
# python =3.0
def only_numerics(seq):
seq_type= type(seq)
return seq_type().join(filter(seq_type.isdigit, seq))
It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.
I came across this in PHP when using fopen()
on a file and then trying to unlink()
it before using fclose()
on it.
No good:
$handle = fopen('file.txt');
// do something
unlink('file.txt');
Good:
$handle = fopen('file.txt');
// do something
fclose($handle);
unlink('file.txt');
profile name is not valid [SQLSTATE 42000] (Error 14607)
This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.
in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)
Dim str as String = "Hello World"
Msgbox(Microsoft.VisualBasic.Right(str,5))
'World"
Same goes for Left() too.
None of the above helped me.
After a little research I found that as of M50 (April 2016) - Chrome now requires a secure origin (such as HTTPS) for Geolocation.
Deprecated Features on Insecure Origins
The host "localhost" is special b/c its "potentially secure". You may not see errors during development if you are deploying to your development machine.
I also was facing with the same issue still after adding path in environment variable and running it as a normal user in command prompt.
Then I opened command prompt and tried running as "Run as Administrator" and I was able to download all the packages with respect to the project.
You can use as an alternate solution:
SELECT * FROM TABLE_NAME WHERE `date` >= '1-jan-2013'
OR `date` <= '12-jan-2013'
I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:
First, insert a new row at the beginning of the sheet. Within that row, define the names you need:
Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now:
Now whenever you scroll down in the document, the first row will be "pinned" to the top:
To really get the latest revision ("head revision") number on your remote respository, use this:
svn info -r 'HEAD' | grep Revision | egrep -o "[0-9]+"
Outputs for example:
35669
Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.
You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:
$ sudo cpan WWW::Telegram::BotAPI
Hope this helps
Tab gravity only effects MODE_FIXED
.
One possible solution is to set your layout_width
to wrap_content
and layout_gravity
to center_horizontal
:
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
app:tabMode="scrollable" />
If the tabs are smaller than the screen width, the TabLayout
itself will also be smaller and it will be centered because of the gravity. If the tabs are bigger than the screen width, the TabLayout
will match the screen width and scrolling will activate.
To revert the revert without screwing up your workflow too much:
Your feature branch should now be able to be merged as normal when you're ready for it. The only downside here is that you'll a have a few extra merge/revert commits in your history.
from your query:
Select employee_id, count(*) From Employee
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95'
i think its not to display the number of employees that are hired after June 20, 1994. if you want show number of employees, you can use:
Select count(*) From Employee
Where to_char(employee_date_hired, 'YYYMMMDDD') > 19940620
I think for best practice to compare dates you can use:
employee_date_hired > TO_DATE('20-06-1994', 'DD-MM-YYYY');
or
to_char(employee_date_hired, 'YYYMMMDDD') > 19940620;
Another option compatible to 4.0:
Before committing the changes, you can recover the new CayenneDataObject
object(s) from the collection associated to the context, like this:
CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
then access the ObjectId
for each one in the collection, like:
ObjectId objectId = dataObject.getObjectId();
Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot()
, it contains also the column name(s) associated to the PK as key(s):
objectId.getIdSnapshot().values()
First of all print
isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing ,
(comma). Now a space will be used instead of a newline.
Demo:
print 1,
print 2
output:
1 2
Or use Python 3's print()
function:
from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)
As you can clearly see print()
function is much more powerful as we can specify any string to be used as end
rather a fixed space.