I had a similar problem with é char... I think the comment "it's possible that the text you're feeding it isn't UTF-8" is probably close to the mark here. I have a feeling the default collation in my instance was something else until I realized and changed to utf8... problem is the data was already there, so not sure if it converted the data or not when i changed it, displays fine in mysql workbench. End result is that php will not json encode the data, just returns false. Doesn't matter what browser you use as its the server causing my issue, php will not parse the data to utf8 if this char is present. Like i say not sure if it is due to converting the schema to utf8 after data was present or just a php bug. In this case use json_encode(utf8_encode($string));
Here are some ways of doing this:
For example, for using Roboto, install the package using
yarn add typeface-roboto
or
npm install typeface-roboto --save
In index.js:
import "typeface-roboto";
There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.
For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html
It'll be like
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Montserrat');
</style>
Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.
Move the font to fonts
directory in your src
directory
src
|
`----fonts
| |
| `-Lato/Lato-Black.ttf
| -Lato/Lato-BlackItalic.ttf
| -Lato/Lato-Bold.ttf
| -Lato/Lato-BoldItalic.ttf
| -Lato/Lato-Italic.ttf
| -Lato/Lato-Light.ttf
| -Lato/Lato-LightItalic.ttf
| -Lato/Lato-Regular.ttf
| -Lato/Lato-Thin.ttf
| -Lato/Lato-ThinItalic.ttf
|
`----App.css
Now, in App.css
, add this
@font-face {
font-family: 'Lato';
src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
}
For ttf
format, you have to mention format('truetype')
. For woff
, format('woff')
Now you can use the font in classes.
.modal-title {
font-family: Lato, Arial, serif;
font-weight: black;
}
Install package using
yarn add webfontloader
or
npm install webfontloader --save
In src/index.js
, you can import this and specify the fonts needed
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
try this. It will solve your problem.
var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.
Read to DataTable example:
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
using (var reader = new ExcelDataReader(@"data.xlsx"))
dt.Load(reader);
Console.WriteLine("done: " + dt.Rows.Count);
Console.ReadKey();
}
}
for me the "workaround" solution was to remove the "_normal" from the end of the string
Check it out below:
Swift You can use following function to open Settings App with Bluetooth Page
func openSettingsApp(){
if let settings = NSURL(string: "prefs:root=Bluetooth") {
UIApplication.sharedApplication().openURL(settings)
}
}
Again this would not open the App's Settings. This would open settings app with Bluetooth as this is deep linking to bluetooth.
put the table inside the div like this to make scrollable table vertically. change overflow-y
to overflow-x
to make table scrollable horizontally. just overflow
to make table scrollable both horizontal and vertical.
<div style="overflow-y: scroll;">
<table>
...
</table>
</div>
In list comprehension the loop variable i becomes global. After the iteration in the for loop it is a reference to the last element in your list.
If you want all matches then assign the list to a variable:
filtered = [ i for i in my_list if i=='two']
If you want only the first match you could use a function generator
try:
m = next( i for i in my_list if i=='two' )
except StopIteration:
m = None
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;
Found similar problem within student's work, script element was put after closing body tag, so, obviously, JavaScript could not find any HTML element.
But, there was one more serious error: there was a reference to an external javascript file with some code, which removed all contents of a certain HTML element before inserting new content. After commenting out this reference, everything worked properly.
So, sometimes the error might be that some previously called Javascript changed content or even DOM, so calling for instance getElementById later doesn't make sense, since that element was removed.
For those searching for a solution not based on jQuery, this is a plain JavaScript version of the solution provided by Thomas M:
window.addEventListener("storage", message_receive);
function message_broadcast(message) {
localStorage.setItem('message',JSON.stringify(message));
}
function message_receive(ev) {
if (ev.key == 'message') {
var message=JSON.parse(ev.newValue);
}
}
…another lambda
copying a new string from the original, but leaving out the character that is to delete
String text = "removing a special character from a string";
int delete = 'e';
int[] arr = text.codePoints().filter( c -> c != delete ).toArray();
String rslt = new String( arr, 0, arr.length );
gives: rmoving a spcial charactr from a string
Even though Sheena's answer does the job, pip
doesn't stop just there.
From Sheena's answer:
- Download the package
- unzip it if it is zipped
- cd into the directory containing setup.py
- If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
- type in
python setup.py install
At the end of this, you'll end up with a .egg
file in site-packages
.
As a user, this shouldn't bother you. You can import
and uninstall
the package normally. However, if you want to do it the pip
way, you can continue the following steps.
In the site-packages
directory,
unzip <.egg file>
EGG-INFO
directory as <pkg>-<version>.dist-info
<pkg-directory>
find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD
. The >>
is to prevent overwrite.Now, looking at the site-packages
directory, you'll never realize you installed without pip
. To uninstall
, just do the usual pip uninstall <pkg>
.
I faced the same problem, but on EclipseLink version 2.5.0.
I solved my problem by adding yet another jar file which was necessarily (javax.persistence_2.1.0.v201304241213.jar.jar);
Jars needed:
- javax.persistence_2.1.0.v201304241213.jar
- eclipselink.jar
- jdbc.jar (depending on the database used).
I hope this helps.
Try the following command iptables-save
.
(From the mailing list. I didn't come up with this answer.)
class _FooState extends State<Foo> {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: 'Initial value');
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new TextField(
// The TextField is first built, the controller has some initial text,
// which the TextField shows. As the user edits, the text property of
// the controller is updated.
controller: _controller,
),
new RaisedButton(
onPressed: () {
// You can also use the controller to manipuate what is shown in the
// text field. For example, the clear() method removes all the text
// from the text field.
_controller.clear();
},
child: new Text('CLEAR'),
),
],
);
}
}
@jolly.exe
Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.
HTML
<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div>
JS
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 30;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('stuff');
I tried the above solutions. None worked.
In the end I opened Makefile file and manually changed prefix path to desired installation path like below.
PREFIX ?= "installation path"
When I tried --prefix, "make" complained that there is not such command input. However, perhaps some packages accepts --prefix which is of course a cleaner solution.
Apart from a database, you can also have following options to save user related settings
registry under HKEY_CURRENT_USER
in a file in AppData
folder
using Settings
file in WPF and by setting its scope as User
On INNER JOIN
s they are interchangeable, and the optimizer will rearrange them at will.
On OUTER JOIN
s, they are not necessarily interchangeable, depending on which side of the join they depend on.
I put them in either place depending on the readability.
in my case this worked perfectly
<img style="border-radius: 50%;height: 50px;width: 80px;" src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">
this code is used to display image from folder
pluck(column_name)
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
Examples:
Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)
see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns
git stash apply
Just check out the branch you want your changes on, and then git stash apply
. Then use git diff
to see the result.
After you're all done with your changes—the apply
looks good and you're sure you don't need the stash any more—then use git stash drop
to get rid of it.
I always suggest using git stash apply
rather than git stash pop
. The difference is that apply
leaves the stash around for easy re-try of the apply
, or for looking at, etc. If pop
is able to extract the stash, it will immediately also drop
it, and if you the suddenly realize that you wanted to extract it somewhere else (in a different branch), or with --index
, or some such, that's not so easy. If you apply
, you get to choose when to drop
.
It's all pretty minor one way or the other though, and for a newbie to git, it should be about the same. (And you can skip all the rest of this!)
There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":
You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.
This is the easy case, described above. Run git stash save
(or plain git stash
, same thing). Check out the other branch and use git stash apply
. This gets git to merge in your earlier changes, using git's rather powerful merge mechanism. Inspect the results carefully (with git diff
) to see if you like them, and if you do, use git stash drop
to drop the stash. You're done!
You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.
Now you want to keep, or even move, these changes, and apply your stash too.
You can in fact git stash save
again, as git stash
makes a "stack" of changes. If you do that you have two stashes, one just called stash
—but you can also write stash@{0}
—and one spelled stash@{1}
. Use git stash list
(at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop
, it drops the newest, and the one that was stash@{1}
moves to the top of the stack. If you had even more, the one that was stash@{2}
becomes stash@{1}
, and so on.
You can apply
and then drop
a specific stash, too: git stash apply stash@{2}
, and so on. Dropping a specific stash, renumbers only the higher-numbered ones. Again, the one without a number is also stash@{0}
.
If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@{7}
or was it stash@{4}
? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December
means a lot more to me than stash@{12}
. (The git stash
command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch
.)
(Extra-advanced) You've used git stash save -p
, or carefully git add
-ed and/or git rm
-ed specific bits of your code before running git stash save
. You had one version in the stashed index/staging area, and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index
, and that sometimes fails with:
Conflicts in index. Try without --index.
You're using git stash save --keep-index
in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.
For complicated cases, I recommend starting in a "clean" working directory first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:
git status # see if there's anything you need to commit
# uh oh, there is - let's put it on a new temp branch
git checkout -b temp # create new temp branch to save stuff
git add ... # add (and/or remove) stuff as needed
git commit # save first set of changes
Now you're on a "clean" starting point. Or maybe it goes more like this:
git status # see if there's anything you need to commit
# status says "nothing to commit"
git checkout -b temp # optional: create new branch for "apply"
git stash apply # apply stashed changes; see below about --index
The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply
operation looks at what the commit changed, and tries to repeat it wherever you are now. The stash will still be there (apply
keeps it around), so you can look at it more, or decide this was the wrong place to apply
it and try again differently, or whatever.
Any time you have a stash, you can use git stash show -p
to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index
restores separately.) The command git stash apply
, without --index
, just tries to make those same changes in your work-directory now.
This is true even if you already have some changes. The apply
command is happy to apply a stash to a modified working directory (or at least, to try to apply it). You can, for instance, do this:
git stash apply stash # apply top of stash stack
git stash apply stash@{1} # and mix in next stash stack entry too
You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:
Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.
If you start with a clean directory and are just doing several git apply
operations, it's easy to back out: use git reset --hard
to get back to the clean state, and change your apply
operations. (That's why I recommend starting in a clean working directory first, for these complicated cases.)
Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index
, but it's no longer possible to apply the saved stash with --index
, because the branch has diverged too much since the time you saved it.
This is what git stash branch
is for.
If you:
stash
, thengit stash apply --index
the attempt to re-create the changes definitely will work. This is what git stash branch newbranch
does. (And it then drops the stash since it was successfully applied.)
--index
(what the heck is it?)What the --index
does is simple to explain, but a bit complicated internally:
git add
(or "stage") them before commit
ing.git stash
, you might have edited both files foo
and zorg
, but only staged one of those.git add
s the add
ed things and does not git add
the non-added things. That is, if you add
ed foo
but not zorg
back before you did the stash
, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.The --index
flag to apply
tries to set things up this way. If your work-tree is clean, this usually just works. If your work-tree already has stuff add
ed, though, you can see how there might be some problems here. If you leave out --index
, the apply
operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes git's merge machinery, using the work-tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index
makes it a lot easier for git stash apply
to do its thing.
The proposed combination of os.listdir
and sorted
commands generates the same result as ls -l
command under Linux. The following example verifies this assumption:
user@user-PC:/tmp/test$ touch 3a 4a 5a b c d1 d2 d3 k l p0 p1 p3 q 410a 409a 408a 407a
user@user-PC:/tmp/test$ ls -l
total 0
-rw-rw-r-- 1 user user 0 Feb 15 10:31 3a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 407a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 408a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 409a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 410a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 4a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 5a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 b
-rw-rw-r-- 1 user user 0 Feb 15 10:31 c
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d1
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d2
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d3
-rw-rw-r-- 1 user user 0 Feb 15 10:31 k
-rw-rw-r-- 1 user user 0 Feb 15 10:31 l
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p0
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p1
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p3
-rw-rw-r-- 1 user user 0 Feb 15 10:31 q
user@user-PC:/tmp/test$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir( './' )
['d3', 'k', 'p1', 'b', '410a', '5a', 'l', 'p0', '407a', '409a', '408a', 'd2', '4a', 'p3', '3a', 'q', 'c', 'd1']
>>> sorted( os.listdir( './' ) )
['3a', '407a', '408a', '409a', '410a', '4a', '5a', 'b', 'c', 'd1', 'd2', 'd3', 'k', 'l', 'p0', 'p1', 'p3', 'q']
>>> exit()
user@user-PC:/tmp/test$
So, for someone who wants to reproduce the result of the well-known ls -l
command in their python code, sorted( os.listdir( DIR ) )
works pretty well.
//use jquery
$select.trigger('mousedown')
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}
$fname = str_replace('/','',$fname);
Since users might use the slash to separate two words it would be better to replace with a dash instead of NULL
Try this MSDN blog
Also, try the following example:
Xaml:
<DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
<DataGrid.Columns>
<DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Account" IsReadOnly="True" Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
CS:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var data = new Test { Test1 = "Test1", Test2 = "Test2" };
DataGridTest.Items.Add(data);
}
}
public class Test
{
public string Test1 { get; set; }
public string Test2 { get; set; }
}
Do not use more than one style attribute. Just seperate styles in the style attribute with ;
It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.
So in this case its:
style="height:100px;width:100px;"
You can use this for any CSS style, so if you wanted to change the colour of the text to white:
style="height:100px;width:100px;color:#ffffff"
and so on.
However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
Update (2017):
In modern browsers which follow the ECMAScript 2016 (ES7) standard, you can use the function Array.prototype.includes, which makes it way more easier to check if an item is present in an array:
const array = [1, 2, 3];_x000D_
const value = 1;_x000D_
const isInArray = array.includes(value);_x000D_
console.log(isInArray); // true
_x000D_
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
Something like this should work:
INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...
UPDATE:
Apparently this syntax is only available starting on SQL Server 2008.
Another way to make it in Python 3:
numbers = [*map(int, numbers)]
The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.
#box {
background-color: #000;
position: relative;
padding: 10px;
width: 220px;
height:30px;
}
If you're going to be using arrays, consider the numpy or scipy packages, which give you arrays with a lot more flexibility.
Another answer: There's a bookmarklet called ReCSS. I haven't used it extensively, but seems to work.
There's a bookmarklet on that page to drag and drop onto your address bar (Can't seem to make one here). In case that's broke, here's the code:
javascript:void(function()%7Bvar%20i,a,s;a=document.getElementsByTagName('link');for(i=0;i%3Ca.length;i++)%7Bs=a[i];if(s.rel.toLowerCase().indexOf('stylesheet')%3E=0&&s.href)%20%7Bvar%20h=s.href.replace(/(&%7C%5C?)forceReload=%5Cd%20/,'');s.href=h%20(h.indexOf('?')%3E=0?'&':'?')%20'forceReload='%20(new%20Date().valueOf())%7D%7D%7D)();
There is another approach. It uses List.FindIndex
and List.RemoveAt
.
While I would probably use the solution presented by KeithS (just the simple Where
/ToList
) this approach differs in that it mutates the original list object. This can be a good (or a bad) "feature" depending upon expectations.
In any case, the FindIndex
(coupled with a guard) ensures the RemoveAt
will be correct if there are gaps in the IDs or the ordering is wrong, etc, and using RemoveAt
(vs Remove
) avoids a second O(n) search through the list.
Here is a LINQPad snippet:
var list = new List<int> { 1, 3, 2 };
var index = list.FindIndex(i => i == 2); // like Where/Single
if (index >= 0) { // ensure item found
list.RemoveAt(index);
}
list.Dump(); // results -> 1, 3
Happy coding.
If the program was written in C# you can get the source code in almost its original form using .NET Reflector. You won't be able to see comments and local variable names, but it is very readable.
If it was written C++ it's not so easy... even if you could decompile the code into valid C++ it is unlikely that it will resemble the original source because of inlined functions and optimizations which are hard to reverse.
Please note that by reverse engineering and modifying the source code you might breaking the terms of use of the programs unless you wrote them yourself or have permission from the author.
If you want to display links coming from your state or store in Vue 2.0, you can do like this:
<a v-bind:href="''">
{{ url_link }}
</a>
Oracle has two different ways of making views updatable:-
I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.
Just document it here
on Windows you need to escape the \
character:
"e:\\directory\\-"
If you want it to be List<string>
, get rid of the anonymous type and add a .ToList()
call:
List<string> list = (from char c in source
select c.ToString()).ToList();
You can cast the DATETIME field into DATE as:
SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'
This is very much efficient.
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
I had the same problem. Don't remember where I found it on the web, but here is what I did:
Click "Start button"
in the search box, enter "Turn windows features on or off"
in the features window, Click: "Internet Information Services"
Click: "World Wide Web Services"
Click: "Application Development Features"
Check (enable) the features. I checked all but CGI.
IIS - this configuration section cannot be used at this path (configuration locking?)
Commons-net surely. :) Most open source projects use it these days.
yc
The simplest way is to just redirect the output, like so:
Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt
>
will cause the output file to be overwritten if it already exists.
>>
will append new text to the end of the output file if it already exists.
Using JSTL:
<c:set var="message" value='${requestScope["Error_Message"]}' />
Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.
<c:out value="${message}"/>
Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.
<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td width="350" >
Foo
</td>
<td width="80" >
Foo1
</td>
<td width="65" >
Foo2
</td>
</tr>
<tr>
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
<tr >
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
</table>
</body>
</html>
Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.
Here's how I solved it:
using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
{
var hostname = HttpContext.Current.Request.UserHostAddress;
IPAddress ipAddress = IPAddress.Parse(hostname);
IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
...
Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?
A project is not exactly the same thing as an executable jar file.
For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
Python 3.5 + Use io module
import json
import io
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
fix_bytes_value = my_bytes_value.replace(b"'", b'"')
my_json = json.load(io.BytesIO(fix_bytes_value))
Since you need to accommodate many different phone number formats (and probably include things like extensions etc.) it may make the most sense to just treat it as you would any other varchar. If you could control the input, you could take a number of approaches to make the data more useful, but it doesn't sound that way.
Once you decide to simply treat it as any other string, you can focus on overcoming the inevitable issues regarding bad data, mysterious phone number formating and whatever else will pop up. The challenge will be in building a good search strategy for the data and not how you store it in my opinion. It's always a difficult task having to deal with a large pile of data which you had no control over collecting.
I was able to set the initial view controller on the summary screen of xcode.
Click on the top most project name in the left hand file explorer (it should have a little blueprint icon). In the center column click on your project name under 'TARGETS', (it should have a little pencil 'A' icon next to it). Look under 'iPhone / iPod Deployment Info' and look for 'Main Interface'. You should be able to select an option from the drop down.
Windows 7 32 - bit
I am using git for my Ruby on Rails application. First time so...
I created a .bat file for loading my RoR applications with the paths manually typed using this tutorial at "http://www.youtube.com/watch?v=-eFwV8lRu1w" If you are new to Ruby on Rails you might want to check it out as I followed all steps and it works flawlessly after a few trials and errors.
(The .bat file is editable using notepad++ hence no need for the long process whenever you need to edit a path, you can follow these simple process after creating a .bat file following the tutorials on the link above "file is called row.bat".)
insert path below the last path you inputted.
)
During the tutorials I don't remember anything said in regards to using the git command so when starting a new project I had this same problem after installing git. The main issue I had was locating the folder with the bin/git.exe (git.exe did not show up in search using start menu's "search programs and files" ) NOTE I now understood that the location might vary drastically --- see below.
To locate the bin/git.exe i followed this steps
1 left click start menu and locate ->> all programs ->> GitHub inc. 2 right click git shell and select open file location 3 click through folders in the file location for the folder "bin"
(I had 4 folders named 1. IgnoreTemplates_fdbf2020839cde135ff9dbed7d503f8e03fa3ab4 2. lfs-x86_0.5.1 3. PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad ("bin/exe, found here <<-") 4. PoshGit_869d4c5159797755bc04749db47b166136e59132 )
Copy the full link by clicking on the explorers url (mine was "C:\Users\username\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin") open .bat file in notepad++ and paste using instructions on how to add a path to your .bat file from tutorials above. Problem solved!
Ookii folder dialog can be found at Nuget.
PM> Install-Package Ookii.Dialogs.Wpf
And, example code is as below.
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
textBoxFolderPath.Text = dialog.SelectedPath;
}
More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf
How are you converting the submitted names to "a simple .txt list"? During that step, can you instead convert them into a simple HTML list or table? Then you could wrap that in a standard header which includes any styling you want.
If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.
sftp login@host < /path/to/command/list
You will then be asked to enter your password (as per normal) however all the commands in the script run after that.
This is clearly not a completely automated option that can be used in a cron
job, but it can be used from a terminal.
You can try this as well
df.drop_duplicates(subset='A', keep='last')
I referred this from https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html
The three most influential factors for Eclipse speed are:
The "same" workspace in Indigo (3.7.2) SR2 loads in 4 seconds, in Kepler SR2 (4.3.2) in 7 seconds and in Luna (4.4.0) in 10 seconds. All are Java EE bundles. Newer versions have more bundled plugins, but still the trend is obvious. (by "same" workspace I mean: same (additionally installed) plugins used, same projects checked out from version control).
Launching it with the latest JDK (Java 14 at the time of writing, which does not prevent you to compile in your Eclipse project with any other JDK you want: 1.4.2, 1.5, 1.6 older...)
-vm jdk1.6.0_10\jre\bin\client\jvm.dll
Configuring the eclipse.ini (see this question for a complete eclipse.ini)
-Xms512m
-Xmx4096m
[...]
The Xmx
argument is the amount of memory Eclipse will get (in simple terms). With -Xmx4g
, it gets 4 GB of RAM, etc.
Note:
Dec. 2020, Udo conforms in the comments
From version 4.8 (Photon) an up there was a steady speed gain after each version.
The main platform was optimized every release to load faster, enable more features for the dark theme and to add more features for newer Java versions for the Java development tools.
Especially with-in the last 3 versions the startup time was increased a lot. There should be a significant increase in start-up time with the newest version of Eclipse 2020-12.In my experience it started a lot faster with each new version.
But: There are still plug-ins which do not follow the new way of using the Eclipse API and are therefore still slow to start.
Since the change to Java 11 as the minimum runtime version starting from Eclipse version 2020-09 at least the core system uses the newer features of the JVM. It is up to the providers of the other plug-ins to upgrade to newer APIs and to use the full power of modern CPUs (e.g. concurrent programming model).
One way to check for the installed Office version would be to check the InstallRoot
registry keys for the Office applications of interest.
For example, if you would like to check whether Word 2007 is installed you should check for the presence of the following Registry key:
HKLM\Software\Microsoft\Office\12.0\Word\InstallRoot::Path
This entry contains the path to the executable.
Replace 12.0 (for Office 2007) with the corresponding version number:
Office 97 - 7.0 Office 98 - 8.0 Office 2000 - 9.0 Office XP - 10.0 Office 2003 - 11.0 Office 2007 - 12.0 Office 2010 - 14.0 (sic!) Office 2013 - 15.0 Office 2016 - 16.0 Office 2019 - 16.0 (sic!)
The other applications have similar keys:
HKLM\Software\Microsoft\Office\12.0\Excel\InstallRoot::Path
HKLM\Software\Microsoft\Office\12.0\PowerPoint\InstallRoot::Path
Or you can check the common root path of all applications:
HKLM\Software\Microsoft\Office\12.0\Common\InstallRoot::Path
Another option, without using specific Registry keys would be to query the MSI database using the MSIEnumProducts
API as described here.
As an aside, parallel installations of different Office versions are not officially supported by Microsoft. They do somewhat work, but you might get undesired effects and inconsistencies.
Update: Office 2019 and Office 365
As of Office 2019, MSI-based setup are no longer available, Click-To-Run is the only way to deploy Office now. Together with this change towards the regularly updated Office 365, also the major/minor version numbers of Office are no longer updated (at least for the time being). That means that – even for Office 2019 – the value used in Registry keys and the value returned by Application.Version
(e.g. in Word) still is 16.0
.
For the time being, there is no documented way to distinguish the Office 2016 from Office 2019. A clue might be the file version of the winword.exe; however, this version is also incremented for patched Office 2016 versions (see the comment by @antonio below).
If you need to distinguish somehow between Office versions, e.g. to make sure that a certain feature is present or that a minimum version of Office is installed, probably the best way it to look at the file version of one of the main Office applications:
// Using the file path to winword.exe
// Retrieve the path e.g. from the InstallRoot Registry key
var fileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
var version = new Version(fileVersionInfo.FileVersion);
// On a running instance using the `Process` class
var process = Process.GetProcessesByName("winword").First();
string fileVersionInfo = process.MainModule.FileVersionInfo.FileVersion;
var version = Version(fileVersionInfo);
The file version of Office 2019 is 16.0.10730.20102, so if you see anything greater than that you are dealing with Office 2019 or a current Office 365 version.
If you want to apply styles only to an element which is its parents' first child, is it better to use :first-child
pseudo-class
.social:first-child{
border-bottom: dotted 1px #6d6d6d;
padding-top: 0;
}
.social{
border: 0;
width: 330px;
height: 75px;
float: right;
text-align: left;
padding: 10px 0;
}
Then, the rule .social
has both common styles and the last element's styles.
And .social:first-child
overrides them with first element's styles.
You could also use :last-child
selector, but :first-child
is more supported by old browsers: see
https://developer.mozilla.org/en-US/docs/CSS/:first-child#Browser_compatibility and https://developer.mozilla.org/es/docs/CSS/:last-child#Browser_compatibility.
This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.
For those who reached this post for Answer:
This happens mainly because the InputStream
the DOM parser is consuming is empty
So in what I ran across, there might be two situations:
InputStream
you passed into the parser has been used and thus emptied.File
or whatever you created the InputStream
from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream
.Try this:
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
and
// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
if (!string.IsNullOrEmpty(Request.Form["username"])) { ... }
username is the name of the input on the submitting page. The password can be obtained the same way. If its not null or empty, it exists, then log in the user (I don't recall the exact steps for ASP.NET Membership, assuming that's what you're using).
To resolve 'ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly' error when opening a solution we can:
1 Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click 'Turn Windows Featrues on. Then in the IIS --> WWW servers --> App Dev Features ensure that ASP.NET is checked.
2 And run the following cmd line to install
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i
Hope this helps
I'm unable to comment due to my rep, but I just wanted to add: for VSCode users, you can change CRLF line endings to LF by clicking on CRLF in the status bar, then select LF and save the file.
Using LINQ to xml if you are using framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
I came up with something using HTML + CSS only. Hope it works for you
.mzhrttltp {
position: relative;
display: inline-block;
}
.mzhrttltp .hrttltptxt {
visibility: hidden;
width: 120px;
background-color: #040505;
font-size:13px;color:#fff;font-family:IranYekanWeb;
text-align: center;
border-radius: 3px;
padding: 4px 0;
position: absolute;
z-index: 1;
top: 105%;
left: 50%;
margin-left: -60px;
}
.mzhrttltp .hrttltptxt::after {
content: "";
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent #040505 transparent;
}
.mzhrttltp:hover .hrttltptxt {
visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????‌????‌??</div></div>
_x000D_
res.status(500).jsonp(dataRes);
An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/
Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).
Just reciprocating Alex's answer but with jQuery:
var e = $('#myFrame');
e.attr("src", e.attr("src"));
Or you can use small function:
function iframeRefresh(e) {
var c = $(e);
c.attr("src", c.attr("src"));
}
I hope it helps.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
You have to additionally use the tokens=1,2,...
part of the options that the for
loop allows. This here will do what you possibly want:
for /f "tokens=1,2,3,4,5,6,7,8,9,10,11,12 delims=;" %a in ("%PATH%") ^
do ( ^
echo. %b ^
& echo. %a ^
& echo. %c ^
& echo. %d ^
& echo. %e ^
& echo. %f ^
& echo. %g ^
& echo. %h ^
& echo. %i ^
& echo. %j ^
& echo. %k ^
& echo. ^
& echo. ...and now for some more... ^
& echo. ^
& echo. %a ^| %b ___ %c ... %d ^
& dir "%e" ^
& cd "%f" ^
& dir /tw "%g" ^
& echo. "%h %i %j %k" ^
& cacls "%f")
This example processes the first 12 tokens (=directories from %path%) only. It uses explicit enumeration of each of the used tokens. Note, that the token names are case sensitive: %a is different from %A.
To be save for paths with spaces, surround all %x with quotes like this "%i". I didn't do it here where I'm only echoing the tokens.
You could also do s.th. like this:
for /f "tokens=1,3,5,7-26* delims=;" %a in ("%PATH%") ^
do ( ^
echo. %c ^
& echo. %b ^
& echo. %a ^
& echo. %d ^
& echo. %e ^
& echo. %f ^
& echo. %g ^
& echo. %h ^
& echo. %i ^
& echo. %j ^
& echo. %k )
This one skips tokens 2,4,6 and uses a little shortcut ("7-26
") to name the rest of them. Note how %c, %b, %a are processed in reverse order this time, and how they now 'mean' different tokens, compared to the first example.
So this surely isn't the concise explanation you asked for. But maybe the examples help to clarify a little better now...
You can actually accomplish this without JavaScript, using only JSF's rendered
attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:
<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
<f:selectItem itemValue="O" itemLabel="Originator" />
<f:selectItem itemValue="R" itemLabel="Role" />
<f:selectItem itemValue="E" itemLabel="Employee" />
<f:ajax event="change" execute="@this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
<h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
rendered="#{workflowProcEditBean.performedBy eq 'R'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.roles}" />
</h:selectOneMenu>
<h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
rendered="#{workflowProcEditBean.performedBy eq 'E'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.employees}" />
</h:selectOneMenu>
</h:panelGroup>
Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?
public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(SelectTitle);
builder.setItems(SelectList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
EditTextItem.setText(SelectList[item]);
}
});
builder.create().show();
return false;
}
});
}
return
means, "output this value from this function".
print
means, "send this value to (generally) stdout"
In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).
This is an example of print:
>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
This is an example of return:
>>> def getN():
... return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);
Try to use:
mvn jacoco:report -debug
to see the details about your reporting process.
I configured my jacoco like this:
<configuration>
<dataFile>~/jacoco.exec</dataFile>
<outputDirectory>~/jacoco</outputDirectory>
</configuration>
Then mvn jacoco:report -debug
shows it using the default configuration, which means jacoco.exec
is not in ~/jacoco.exec
. The error says missing execution data file
.
So just use the default configuration:
<execution>
<id>default-report</id>
<goals>
</goals>
<configuration>
<dataFile>${project.build.directory}/jacoco.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
And everything works fine.
Simply type python -m django --version
or type pip freeze
to see all the versions of installed modules including Django.
Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )
Use https://search.maven.org/ manually with the prefix fc: to search for class names. Both Netbeans and Eclipse seem to be too stupid to use that search interface and the gigabytes of downloaded repository indexes seem to not contain any class information. Total waste of disk space. Those IDE projects are so badly maintained lately, I wish they would move development to GitHub.
{{ app.user.username|default('') }}
Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.
(EDIT: As pointed out by the OP, the using a java.net.Authenticator
is required too. I'm updating my answer accordingly for the sake of correctness.)
(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic
auth scheme from jdk.http.auth.tunneling.disabledSchemes
property)
For authentication, use java.net.Authenticator
to set proxy's configuration and set the system properties http.proxyUser
and http.proxyPassword
.
final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
}
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
SimpleDateFormat sdf=new SimpleDateFormat("EEE");
EEE stands for day of week for example Thursday is displayed as Thu.
This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
please note: Directory with NewFolder name should exist in C:\
The internals of the GUI system call that method, and they pass in the Graphics
parameter as a graphics context onto which you can draw.
There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).
This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.
For Android development, I use:
int color = Color.parseColor("#123456");
Check you class name first. It should be p1 as per your batch file instruction. And then check you package of that class, if it is inside any package, specify when you run.
If package is x.y
java x.y.p1
This will insert a new element after the input field with id "password".
$(document).ready(function(){
var newInput = $("<input name='new_field' type='text'>");
$('input#password').after(newInput);
});
Not sure if this answers your question.
I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:
Range
should be assigned to myRange
. Since a Range
type is an object in VBA it needs to be Set
, like this: Set myRange = Range("A:A")
CountA()
should be called with .WorksheetFunction
If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim
statements, as I have done below.
The following code works for me in 2010. Hopefully it works for you too:
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
Good Luck.
This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:
netstat -ntulp
telnet LISTENING_IP LISTENING_PORT
should do the joband then let us know the findings.
Various forms depending on type of List, for Array List:
val myList = mutableListOf<Kolory>()
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()
For LinkedList:
val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()
For other list types, will be assumed Mutable if you construct them directly:
val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()
This holds true for anything implementing the List
interface (i.e. other collections libraries).
No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:
val myList: List<Kolory> = ArrayList()
GOPATH
is discussed in the cmd/go
documentation:
The
GOPATH
environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.
GOPATH
must be set to get, build and install packages outside the standard Go tree.
GOROOT
is discussed in the installation instructions:
The Go binary distributions assume they will be installed in
/usr/local/go
(orc:\Go
under Windows), but it is possible to install the Go tools to a different location. In this case you must set theGOROOT
environment variable to point to the directory in which it was installed.For example, if you installed Go to your home directory you should add the following commands to
$HOME/.profile
:export GOROOT=$HOME/go export PATH=$PATH:$GOROOT/bin
Note:
GOROOT
must be set only when installing to a custom location.
(updated version of Chris Bunch's answer.)
I found this nice video on the Clojure subreddit about FRP. It is pretty easy to understand even if you don't know Clojure.
Here's the video: http://www.youtube.com/watch?v=nket0K1RXU4
Here's the source the video refers to in the 2nd half: https://github.com/Cicayda/yolk-examples/blob/master/src/yolk_examples/client/autocomplete.cljs
As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
if __name__ == "__main__":
for word in read_words('./very_large_file.txt'):
process(word)
While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:
Makefile support plugin for IntelliJ IDEA
You can install directly from the official repository:
Settings > Plugins > search for makefile
> Search in repositories > Install > Restart
There are at least three different ways to run:
It opens a pane named Run target with the output.
Found a great plugin that works in Juno and Kepler. It puts shortcuts on the quick access bar for increasing or decreasing text size.
Install New Software -> http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/
You confuse how browsers renders the elements when there are floating elements. If one block element is floating (your inner div in your case), other block elements will ignore it because browser removes floating elements from the normal flow of the web page. Then, because the floated div has been removed from the normal flow, the outside div is filled in, like the inner div isn't there. However, inline elements (images, links, text, blackquotes) will respect the boundaries of the floating element. If you introduce text in the outside div, the text will place arround de inner div.
In other words, block elements (headers, paragraphs, divs, etc) ignore floating elements and fill in, and inline elements (images, links, text, etc) respect boundaries of floating elements.
<body>
<div style="float:right; background-color:blue;width:200px;min-height:400px;margin-right:20px">
floating element
</div>
<h1 style="background-color:red;"> this is a big header</h1>
<p style="background-color:green"> this is a parragraph with text and a big image. The text places arrounds the floating element. Because of the image is wider than space between paragrah and floating element places down the floating element. Try to make wider the viewport and see what happens :D
<img src="http://2.bp.blogspot.com/_nKxzQGcCLtQ/TBYPAJ6xM4I/AAAAAAAAAC8/lG6XemOXosU/s1600/css.png">
</p>
If you wanted to load message files for different languages, just use the shared.loader= of catalina.properties... for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
function HashTable() {
this.length = 0;
this.items = new Array();
for (var i = 0; i < arguments.length; i += 2) {
if (typeof (arguments[i + 1]) != 'undefined') {
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
this.removeItem = function (in_key) {
var tmp_previous;
if (typeof (this.items[in_key]) != 'undefined') {
this.length--;
var tmp_previous = this.items[in_key];
delete this.items[in_key];
}
return tmp_previous;
}
this.getItem = function (in_key) {
return this.items[in_key];
}
this.setItem = function (in_key, in_value) {
var tmp_previous;
if (typeof (in_value) != 'undefined') {
if (typeof (this.items[in_key]) == 'undefined') {
this.length++;
} else {
tmp_previous = this.items[in_key];
}
this.items[in_key] = in_value;
}
return tmp_previous;
}
this.hasItem = function (in_key) {
return typeof (this.items[in_key]) != 'undefined';
}
this.clear = function () {
for (var i in this.items) {
delete this.items[i];
}
this.length = 0;
}
}
As of feb 2019 .addEventListener()
is not currently work with jQuery .trigger()
or .change()
, you can test it below using Chrome or Firefox.
txt.addEventListener('input', function() {_x000D_
console.log('not called?');_x000D_
})_x000D_
$('#txt').val('test').trigger('input');_x000D_
$('#txt').trigger('input');_x000D_
$('#txt').change();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" id="txt">
_x000D_
you have to use .dispatchEvent()
instead.
txt.addEventListener('input', function() {_x000D_
console.log('it works!');_x000D_
})_x000D_
$('#txt').val('yes')_x000D_
txt.dispatchEvent(new Event('input'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" id="txt">
_x000D_
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
Try this
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
// $(".tab").addClass("active"); // instead of this do the below
$(this).addClass("active");
});
});
when you are using $(".tab").addClass("active");
, it targets all the elements with class name .tab
. Instead when you use this
it looks for the element which has an event, in your case the element which is clicked.
Hope this helps you.
tx, found the workaround I needed:
constructor(private zone:NgZone) {
// enable to for time travel
this.appStore.subscribe((state) => {
this.zone.run(() => {
console.log('enabled time travel');
});
});
running zone.run will force the component to re-render
I checked your code and think you should try this:
if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name']))
{
echo 'No upload';
}
else
echo 'upload';
Additionally, os.access()
:
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
Being R_OK
, W_OK
, and X_OK
the flags to test for permissions (doc).
Actually you don't have to create an image at all. drawImage()
will accept a Canvas
as well as an Image
object.
//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
Way faster than using an ImageData
object or Image
element.
Note that sourceCanvas
can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas
.
Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element
$('li').last().addClass('someClass');
if you have multiple
You could write a function that converts a scientific notation to regular, something like
def sc2std(x):
s = str(x)
if 'e' in s:
num,ex = s.split('e')
if '-' in num:
negprefix = '-'
else:
negprefix = ''
num = num.replace('-','')
if '.' in num:
dotlocation = num.index('.')
else:
dotlocation = len(num)
newdotlocation = dotlocation + int(ex)
num = num.replace('.','')
if (newdotlocation < 1):
return negprefix+'0.'+'0'*(-newdotlocation)+num
if (newdotlocation > len(num)):
return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
else:
return s
Right from the docs:
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
Bottom line: don't use it unless you know what you are doing!
Install mysql via homebrew, then you can install mysql python via pip.
pip install MySQL-python
It works for me.
I was having this same issue while my JAVA_HOME system variable was pointing to C:\Program Files\Java\jdk1.8.0_171\bin and my PATH entry consisted of just %JAVA_HOME%.
I changed my JAVA_HOME variable to exclude the bin folder (C:\Program Files\Java\jdk1.8.0_171), and added the bin folder to the system PATH variable: %JAVA_HOME%\bin,
Using javascript, you can set tooltips for all the images on the page.
<!DOCTYPE html>
<html>
<body>
<img src="http://sushmareddy.byethost7.com/dist/img/buffet.png" alt="Food">
<img src="http://sushmareddy.byethost7.com/dist/img/uthappizza.png" alt="Pizza">
<script>
//image objects
var imageEls = document.getElementsByTagName("img");
//Iterating
for(var i=0;i<imageEls.length;i++){
imageEls[i].title=imageEls[i].alt;
//OR
//imageEls[i].title="Title of your choice";
}
</script>
</body>
</html>
_x000D_
I faced the same problem. Renaming the file worked for me.
This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.
import datetime
dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))
In your class, you may overload the "<" operator.
class MyClass
{
bool operator <(const MyClass& rhs)
{
return this->key < rhs.key;
}
}
I adopted the script from shiplu.mokadd.im to fit my needs. Whom it interests:
#!/bin/bash
if [ "$#" -lt 2 ]; then
if [ "$#" -lt 1 ]; then
echo "usage: $0 [path to csv file] <table name> > [sql filename]"
exit 1
fi
TABLENAME=$1
else
TABLENAME=$2
fi
echo "CREATE TABLE $TABLENAME ( "
FIRSTLINE=$(head -1 $1)
# convert lowercase characters to uppercase
FIRSTLINE=$(echo $FIRSTLINE | tr '[:lower:]' '[:upper:]')
# remove spaces
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/ /_/g')
# add tab char to the beginning of line
FIRSTLINE=$(echo "\t$FIRSTLINE")
# add tabs and newline characters
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/,/,\\n\\t/g')
# add VARCHAR
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/,/ VARCHAR(255),/g')
# print out result
echo -e $FIRSTLINE" VARCHAR(255));"
You can use code like:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>window.jQuery || document.write('<script type="text/javascript" src="./scripts/jquery.min.js">\x3C/script>')</script>
But also there are libraries you can use to setup several possible fallbacks for your scripts and optimize the loading process:
Examples:
basket.js I think the best variant for now. Will cach your script in the localStorage, that will speed up next loadings. The simplest call:
basket.require({ url: '/path/to/jquery.js' });
This will return a promise and you can do next call on error, or load dependencies on success:
basket
.require({ url: '/path/to/jquery.js' })
.then(function () {
// Success
}, function (error) {
// There was an error fetching the script
// Try to load jquery from the next cdn
});
RequireJS
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
'//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
//If the CDN location fails, load from this location
'js/jquery-2.0.0.min'
]
}
});
//Later
require(['jquery'], function ($) {
});
yepnope
yepnope([{
load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('js/jquery-2.0.0.min.js');
}
}
}]);
tee is perfect for this, but this will also do the job
ls -lr / > output | cat output
The number of CPUs is insufficient. Select 1 CPU in Genymotion and restart the device.
Why not just use a library routine wcstombs
.
From java 7 I would prefer to use Path. You only need to put path into:
Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.java");
and create some get method:
public String getLastDirectoryName(Path directoryPath) {
int nameCount = directoryPath.getNameCount();
return directoryPath.getName(nameCount - 1);
}
if you are using 1.3.x, you can use the following
{{ orderBy_expression | orderBy : expression : reverse}}
Example List books by published date in descending order
<div ng-repeat="book in books|orderBy:'publishedDate':true">
Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:
list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'),
('2', '3', '4', '5', '2345'),
('3', '4', '5', '6', '3456'),
('4', '5', '6', '7', '4567')]
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
1.From my experience. I would say REST gives you option to access the URL which is already built. eg-> a word search in google. That URL could be used as webservice for REST. In SOAP, you can create your own web service and access it through SOAP client.
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
Edit Since version 26 of the support library (or androidx) you no longer need to implement a custom OnLongClickListener
to display the tooltip. Simply call this:
TooltipCompat.setTooltipText(menu_hotlist, getString(R.string.hint_show_hot_message));
I'll just share my code in case someone wants something like this:
layout/menu/menu_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
...
<item android:id="@+id/menu_hotlist"
android:actionLayout="@layout/action_bar_notifitcation_icon"
android:showAsAction="always"
android:icon="@drawable/ic_bell"
android:title="@string/hotlist" />
...
</menu>
layout/action_bar_notifitcation_icon.xml
Note style and android:clickable properties. these make the layout the size of a button and make the background gray when touched.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center"
android:clickable="true"
style="@android:style/Widget.ActionButton">
<ImageView
android:id="@+id/hotlist_bell"
android:src="@drawable/ic_bell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_margin="0dp"
android:contentDescription="bell"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hotlist_hot"
android:layout_width="wrap_content"
android:minWidth="17sp"
android:textSize="12sp"
android:textColor="#ffffffff"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@null"
android:layout_alignTop="@id/hotlist_bell"
android:layout_alignRight="@id/hotlist_bell"
android:layout_marginRight="0dp"
android:layout_marginTop="3dp"
android:paddingBottom="1dp"
android:paddingRight="4dp"
android:paddingLeft="4dp"
android:background="@drawable/rounded_square"/>
</RelativeLayout>
drawable-xhdpi/ic_bell.png
A 64x64 pixel image with 10 pixel wide paddings from all sides. You are supposed to have 8 pixel wide paddings, but I find most default items being slightly smaller than that. Of course, you'll want to use different sizes for different densities.
drawable/rounded_square.xml
Here, #ff222222 (color #222222 with alpha #ff (fully visible)) is the background color of my Action Bar.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="#ffff0000" />
<stroke android:color="#ff222222" android:width="2dp"/>
</shape>
com/ubergeek42/WeechatAndroid/WeechatActivity.java
Here we make it clickable and updatable! I created an abstract listener that provides Toast creation on onLongClick, the code was taken from from the sources of ActionBarSherlock.
private int hot_number = 0;
private TextView ui_hot = null;
@Override public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater menuInflater = getSupportMenuInflater();
menuInflater.inflate(R.menu.menu_actionbar, menu);
final View menu_hotlist = menu.findItem(R.id.menu_hotlist).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_hot);
updateHotCount(hot_number);
new MyMenuItemStuffListener(menu_hotlist, "Show hot message") {
@Override
public void onClick(View v) {
onHotlistSelected();
}
};
return super.onCreateOptionsMenu(menu);
}
// call the updating code on the main thread,
// so we can call this asynchronously
public void updateHotCount(final int new_hot_number) {
hot_number = new_hot_number;
if (ui_hot == null) return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (new_hot_number == 0)
ui_hot.setVisibility(View.INVISIBLE);
else {
ui_hot.setVisibility(View.VISIBLE);
ui_hot.setText(Integer.toString(new_hot_number));
}
}
});
}
static abstract class MyMenuItemStuffListener implements View.OnClickListener, View.OnLongClickListener {
private String hint;
private View view;
MyMenuItemStuffListener(View view, String hint) {
this.view = view;
this.hint = hint;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
@Override abstract public void onClick(View v);
@Override public boolean onLongClick(View v) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int width = view.getWidth();
final int height = view.getHeight();
final int midy = screenPos[1] + height / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
Toast cheatSheet = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
if (midy < displayFrame.height()) {
cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT,
screenWidth - screenPos[0] - width / 2, height);
} else {
cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
}
cheatSheet.show();
return true;
}
}
.dockerignore
file in build path, the files or dir you want to copy may be in the ignore file list!Please update your php.ini with
default_socket_timeout = 120
You can create your own php.ini if php is installed a CGI instead of a Apache module
Just add : @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
works for me.
I was getting same error I tried with @EnableAutoConfiguration(exclude=...)
didn't work.
You can use itoa function to convert the integer to a string.
You can use strcat function to append characters in a string at the end of another string.
If you want to convert a integer to a character, just do the following -
int a = 65;
char c = (char) a;
Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned
in this case (though you may still lose data).
To do a light reading about type conversion, go here.
If you are still having trouble, comment on this answer.
Edit
Go here for a more suitable example of joining characters.
Also some more useful link is given below -
Second Edit
char msg[200];
int msgLength;
char rankString[200];
........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id
strncat( msg, rankString, (200 - msgLength) ); // msg now contains previous msg + id
// You may loose some portion of id if message length + id string length is greater than 200
Third Edit
Go to this link. Here you will find an implementation of itoa
. Use that instead.
Getting the friends like @nfvs describes is a good way. It outputs a multi-dimensional array with all friends with attributes id and name (ordered by id). You can see the friends photos like this:
foreach ($friends as $key=>$value) {
echo count($value) . ' Friends';
echo '<hr />';
echo '<ul id="friends">';
foreach ($value as $fkey=>$fvalue) {
echo '<li><img src="https://graph.facebook.com/' . $fvalue->id . '/picture" title="' . $fvalue->name . '"/></li>';
}
echo '</ul>';
}
You should be able to do this with the keyup event. To be specific, event.target
should point at the selected element and event.target.href
will give you the href-value of that element. See mdn for more information.
The following code is jQuery, but apart from the boilerplate code, the rest is the same in pure javascript. This is a keyup
handler that is bound to every link tag.
$('a').on( 'keyup', function( e ) {
if( e.which == 9 ) {
console.log( e.target.href );
}
} );
jsFiddle: http://jsfiddle.net/4PqUF/
you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs)
and pass in a dictionary with the dtypes you want to dtype
here's an example:
import pandas as pd
wheel_number = 5
car_name = 'jeep'
minutes_spent = 4.5
# set the columns
data_columns = ['wheel_number', 'car_name', 'minutes_spent']
# create an empty dataframe
data_df = pd.DataFrame(columns = data_columns)
df_temp = pd.DataFrame([[wheel_number, car_name, minutes_spent]],columns = data_columns)
data_df = data_df.append(df_temp, ignore_index=True)
In [11]: data_df.dtypes
Out[11]:
wheel_number float64
car_name object
minutes_spent float64
dtype: object
data_df = data_df.astype(dtype= {"wheel_number":"int64",
"car_name":"object","minutes_spent":"float64"})
now you can see that it's changed
In [18]: data_df.dtypes
Out[18]:
wheel_number int64
car_name object
minutes_spent float64
Try this one with #Input field
<?php
//checking even and odd
echo '<form action="" method="post">';
echo "<input type='text' name='num'>\n";
echo "<button type='submit' name='submit'>Check</button>\n";
echo "</form>";
$num = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["num"])) {
$numErr = "<span style ='color: red;'>Number is required.</span>";
echo $numErr;
die();
} else {
$num = $_POST["num"];
}
$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);
if ($num > 0){
if($even){
echo "Number is even.";
} else {
echo "Number is odd.";
}
} else {
echo "Not a number.";
}
}
?>
The proper way to invoke javascript code when clicking a link would be to add an onclick
handler:
<a href="#" onclick="myFunction()">LinkText</a>
Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])
In [3]: df
Out[3]:
0
0 a
1 b
2 c
3 d
4 a
5 b
In [4]: df[df.duplicated(keep=False)]
Out[4]:
0
0 a
1 b
4 a
5 b
$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);
Where 86400 is the # of seconds in a day.
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
$arr = array ( 0 => "lorem", 1 => "ipsum", 2 => "dolor");
$str = implode (", ", $arr);
You can define assertNotRaises
by reusing about 90% of the original implementation of assertRaises
in the unittest
module. With this approach, you end up with an assertNotRaises
method that, aside from its reversed failure condition, behaves identically to assertRaises
.
It turns out to be surprisingly easy to add an assertNotRaises
method to unittest.TestCase
(it took me about 4 times as long to write this answer as it did the code). Here's a live demo of the assertNotRaises
method in action. Just like assertRaises
, you can either pass a callable and args to assertNotRaises
, or you can use it in a with
statement. The live demo includes a test cases that demonstrates that assertNotRaises
works as intended.
The implementation of assertRaises
in unittest
is fairly complicated, but with a little bit of clever subclassing you can override and reverse its failure condition.
assertRaises
is a short method that basically just creates an instance of the unittest.case._AssertRaisesContext
class and returns it (see its definition in the unittest.case
module). You can define your own _AssertNotRaisesContext
class by subclassing _AssertRaisesContext
and overriding its __exit__
method:
import traceback
from unittest.case import _AssertRaisesContext
class _AssertNotRaisesContext(_AssertRaisesContext):
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
self.exception = exc_value.with_traceback(None)
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
if self.obj_name:
self._raiseFailure("{} raised by {}".format(exc_name,
self.obj_name))
else:
self._raiseFailure("{} raised".format(exc_name))
else:
traceback.clear_frames(tb)
return True
Normally you define test case classes by having them inherit from TestCase
. If you instead inherit from a subclass MyTestCase
:
class MyTestCase(unittest.TestCase):
def assertNotRaises(self, expected_exception, *args, **kwargs):
context = _AssertNotRaisesContext(expected_exception, self)
try:
return context.handle('assertNotRaises', args, kwargs)
finally:
context = None
all of your test cases will now have the assertNotRaises
method available to them.
A problem that has not been mentioned with using magic numbers...
If you have very many of them, the odds are reasonably good that you have two different purposes that you're using magic numbers for, where the values happen to be the same.
And then, sure enough, you need to change the value... for only one purpose.
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
For Mysql8.0.18:
CURRENT_TIMESTAMP([fsp])
Remove "([fsp])", resolved my problem.
To fix this error on Centos 7:
Install PHP extension:
sudo yum install php-xml
Restart your web server. In my case it's php-fpm:
services php-fpm restart
First of all scipy.misc.imread and PIL are no longer available. Instead use imageio library but you need to install Pillow for that as a dependancy
pip install Pillow imageio
Then use the following code to load the image and get the details about it.
import imageio
import tensorflow as tf
path = 'your_path_to_image' # '~/Downloads/image.png'
img = imageio.imread(path)
print(img.shape)
or
img_tf = tf.Variable(img)
print(img_tf.get_shape().as_list())
both work fine.
Alternative answer to the original problem discussed - Owin "not firing." In my case I spent hours thinking it wasn't firing due to being unable to set a breakpoint in it.
When debugging OWIN startup in visual studio
IIS Express - Running "F5" will break on the OWIN startup code
IIS - Running "F5" will not break until after OWIN (and global.asax) code is loaded. If you attach to W3P.exe you will be able to step into it.
//to get day of any date
import java.util.Scanner;
import java.util.Calendar;
import java.util.Date;
public class Show {
public static String getDay(String day,String month, String year){
String input_date = month+"/"+day+"/"+year;
Date now = new Date(input_date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
int final_day = (calendar.get(Calendar.DAY_OF_WEEK));
String finalDay[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
System.out.println(finalDay[final_day-1]);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
getDay(day, month, year);
}
}
Found an interesting and neat way to export environment variables from a file:
in env.vars
:
foo=test
test script:
eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # =>
export eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
# a better one. "--" stops processing options,
# key=value list given as params
export -- `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
use a case into the select and use in the where close a OR
something like this, I didn't tested it but it should work, I think...
select case when CCC='D' then 'test1' else 'test2' end, *
from table
where (CCC='D' AND DDD='X') or (CCC<>'D' AND DDD='X')
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
In python a list knows its length, so you can just do len(sys.argv)
to get the number of elements in argv
.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.
from:
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
to:
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
Screenshot showing problem in JRE:
The center class must have a width in order to make auto margin work:
.center { margin: 0 auto; width: 400px; }
Then I would apply the center class to the video itself, not a container:
<video class='center' …>…</video>
For linebreaks, PHP as "\n"
(see double quote strings) and PHP_EOL
.
Here, you are using <br />
, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br()
function, which inserts <br>
before \n
.
Please note that the focus styles are there for a reason: if you decide to remove them, people who navigate via the keyboard only don't know what's in focus anymore, so you're hurting the accessibility of your website.
(Keeping them in place also helps power users that don't like to use their mouse)
you can use this code
holder.img_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.swipeRevealLayout.close(true);
list.remove(position);
notifyDataSetChanged();
}});
When using LEFT JOIN
or RIGHT JOIN
, it makes a difference whether you put the filter in the WHERE
or into the JOIN
.
See this answer to a similar question I wrote some time ago:
What is the difference in these two queries as getting two different result set?
In short:
WHERE
clause (like you did, the results that aren't associated with that computer are completely filtered outJOIN
instead, the results that aren't associated with that computer appear in the query result, only with NULL
valuesjson.dumps()
converts a dictionary to str
object, not a json(dict)
object! So you have to load your str
into a dict
to use it by using json.loads()
method
See json.dumps()
as a save method and json.loads()
as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
this is what worked for me:
<div [style.visibility]="showThis ? 'visible' : 'hidden'">blah</div>
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
sttr1.search(str2);
it will return the position of the match, or -1 if it isn't found.
I prefer a simple adaptation of csgillespie's method, foregoing the need of a function definition:
d[apply(d!=0, 1, all),]
where d
is your data frame.
This depends on the language being used. You wrote 'language-agnostic', so I'll give some examples.
In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls.
In functional programming language implementations, sometimes, iteration can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.
I know that in some Scheme implementations, recursion will generally be faster than looping.
In short, the answer depends on the code and the implementation. Use whatever style you prefer. If you're using a functional language, recursion might be faster. If you're using an imperative language, iteration is probably faster. In some environments, both methods will result in the same assembly being generated (put that in your pipe and smoke it).
Addendum: In some environments, the best alternative is neither recursion nor iteration but instead higher order functions. These include "map", "filter", and "reduce" (which is also called "fold"). Not only are these the preferred style, not only are they often cleaner, but in some environments these functions are the first (or only) to get a boost from automatic parallelization — so they can be significantly faster than either iteration or recursion. Data Parallel Haskell is an example of such an environment.
List comprehensions are another alternative, but these are usually just syntactic sugar for iteration, recursion, or higher order functions.
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}
$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor
#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.
Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
I use this. It works in Internet Explorer 8 and later:
height:268px
- for display:table
acts like min-height.
CSS:
* {
padding: 0;
margin: 0;
}
body {
background: #cc9999;
}
p {
background: #f0ad4e;
}
#all {
margin: 200px auto;
}
.ff-valign-wrap {
display: table;
width: 100%;
height: 268px;
background: #ff00ff;
}
.ff-valign {
display: table-cell;
height: 100%;
vertical-align: middle;
text-align: center;
background: #ffff00;
}
HTML:
<body>
<div id="all">
<div class="ff-valign-wrap">
<div class="ff-valign">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
</div>
</div>
</div>
</body>
If using Nginx
and getting a similar problem, then this might help:
Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.
If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
You're using the wrong method calls. A viewport is the "window" that's open on the document: how much of it you can see and where.
Using $(window).height()
will not give you the viewport size it will give you the size of the entire window, which is usually the size of the entire document though the document could be even larger.
To get the size of the actual viewport use window.innerHeight
and window.innerWidth
.
https://gist.github.com/bohman/1351439
Do not use the jQuery methods, e.g. $(window).innerHeight()
, as these give the wrong numbers. They give you the window's height, not innerHeight
.
I solved these problem by deleting the ADT Bundle which was showing an error.
Then I extracted the new ADT bundle to solve these problems. After that, I just updated the Android 4.4.2(API 19) in Android SDK Manager.
You are getting these errors because of updating the Android SDK Tools 22.6.2. Below I show the screenshot of it.
Install everything as shown in the screenshot itself. Then these problems will not occur again.
You can try this also
SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
Indeed, in the latest version of Spring Data, findOne returns an optional. If you want to retrieve the object from the Optional, you can simply use get() on the Optional. First of all though, a repository should return the optional to a service, which then handles the case in which the optional is empty. afterwards, the service should return the object to the controller.
String str = "saveMe"
compareString(str)
def compareString(String str){
def str2 = "saveMe"
// using single quotes
println 'single quote string class' + 'String.class'.class
println str + ' == ' + str2 + " ? " + (str == str2)
println ' str = ' + '$str' // interpolation not supported
// using double quotes, Interpolation supported
println "double quoted string with interpolation " + "GString.class $str".class
println "double quoted string without interpolation " + "String.class".class
println "$str equals $str2 ? " + str.equals(str2)
println '$str == $str2 ? ' + "$str==$str2"
println '${str == str2} ? ' + "${str==str2} ? "
println '$str equalsIgnoreCase $str2 ? ' + str.equalsIgnoreCase(str2)
println '''
triple single quoted Multi-line string, Interpolation not supported $str ${str2}
Groovy has also an operator === that can be used for objects equality
=== is equivalent to o1.is(o2)
'''
println '''
triple quoted string
'''
println 'triple single quoted string ' + '''' string '''.class
println """
triple double quoted Multi-line string, Interpolation is supported $str == ${str2}
just like double quoted strings with the addition that they are multiline
'\${str == str2} ? ' ${str == str2}
"""
println 'triple double quoted string ' + """ string """.class
}
output:
single quote string classclass java.lang.String
saveMe == saveMe ? true
str = $str
double quoted string with interpolation class org.codehaus.groovy.runtime.GStringImpl
double quoted string without interpolation class java.lang.String
saveMe equals saveMe ? true
$str == $str2 ? saveMe==saveMe
${str == str2} ? true ?
$str equalsIgnoreCase $str2 ? true
triple single quoted Multi-line string, Interpolation not supported $str ${str2}
Groovy has also an operator === that can be used for objects equality
=== is equivalent to o1.is(o2)
triple quoted string
triple single quoted string class java.lang.String
triple double quoted Multi-line string, Interpolation is supported saveMe == saveMe
just like double quoted strings with the addition that they are multiline
'${str == str2} ? ' true
triple double quoted string class java.lang.String
This is the steps that worked for me (For both Mac and Windows):
This one worked for me.
<td style="border-top: none;">;
The key is you need to add border-top to the <td>
I know this is an old question but I thought I would provide an example using the srcdoc
attribute as this is now widely supported and this is question is viewed often.
Using the srcdoc
attribute, you can provide inline HTML to embed. It overrides the src
attribute if supported. The browser will fall back to the src
attribute if unsupported.
I would also recommend using the sandbox
attribute to apply extra restrictions to the content in the frame. This is especially important if the HTML is not your own.
const iframe = document.createElement('iframe');_x000D_
const html = '<body>Foo</body>';_x000D_
iframe.srcdoc = html;_x000D_
iframe.sandbox = '';_x000D_
document.body.appendChild(iframe);
_x000D_
If you need to support older browsers, you can check for srcdoc
support and fallback to one of the other methods from other answers.
function setIframeHTML(iframe, html) {_x000D_
if (typeof iframe.srcdoc !== 'undefined') {_x000D_
iframe.srcdoc = html;_x000D_
} else {_x000D_
iframe.sandbox = 'allow-same-origin';_x000D_
iframe.contentWindow.document.open();_x000D_
iframe.contentWindow.document.write(html);_x000D_
iframe.contentWindow.document.close();_x000D_
}_x000D_
}_x000D_
_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.sandbox = '';_x000D_
var html = '<body>Foo</body>';_x000D_
_x000D_
document.body.appendChild(iframe);_x000D_
setIframeHTML(iframe, html);
_x000D_
Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.
Please see the below example code for Windows IIS Servers with Web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="1024" maxUrl="2048">
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
This would also work on a server level using machine.config.
Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.
There is a scala way (if you have a enough memory on working machine):
val arr = df.select("column").rdd.collect
println(arr(100))
If dataframe schema is unknown, and you know actual type of "column"
field (for example double), than you can get arr
as following:
val arr = df.select($"column".cast("Double")).as[Double].rdd.collect
Here is what I do on my projects in jupyter notebook,
import sys
sys.path.append("../") # go to parent dir
from customFunctions import *
Then, to affect changes in customFunctions.py
,
%load_ext autoreload
%autoreload 2
you can also use gcc -v
command that works like gcc --version
and if you would like to now where gcc
is you can use whereis gcc
command
I hope it'll be usefull
I think this has been officially implemented now: https://jenkins.io/blog/2017/09/25/declarative-1/
I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
then the software keyboard will be displayed once again.
To export db rather it is SQLITE or ROOM:
Firstly, add this permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Secondly, we drive to code the db functions:
private void exportDB() {
try {
File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = DirectoryName + File.separator +
DATABASE_NAME + ".db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (IOException e) {
Log.e("dbBackup:", e.getMessage());
}
}
Create Folder on Daily basis with name of folder is Current date:
public void createBackup() {
sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
editor = sharedPref.edit();
String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
editor.commit();
}
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
folder = new File(DirectoryName);
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
exportDB();
}
} else {
Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
}
}
Assign the DATABASE_NAME without .db extension and its data type is string
This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos
$_SERVER["PHP_SELF"];
will give you the current filename and its path, but basename(__FILE__)
should give you the filename that it is called from.
So
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
should do it.
If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:
int x;
char c = '0' + x;
Now, if you want a character string, just add a terminating '\0' char:
char s[] = {'0' + x, '\0'};
Note that: