I met the same problem. (Window 10 environment) I solved it by deleting the JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\bin" in the User Variables instead of adding to the System Variables directly.
Then I test that editing JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\" worked too. When I run "mvn -version" in command prompt window, it shows "Java home: C:\Program Files\Java\jdk1.8.0_161\jre".
In conclusion, I guess the JAVA_HOME shouldn't include bin directory.
Remove everything exclude file.name:
ls -d /path/to/your/files/* |grep -v file.name|xargs rm -rf
egrep
-- extended grep -- will help here
ls | egrep '\.mp4$|\.mp3$|\.exe$'
should do the job.
Solved the issue by adding .conf
extension to site configuration files.
Apache a2ensite
results in:
Error! Site Does Not Exist
Problem; If you found the error while trying to enable a site using:
sudo a2ensite example.com
but it returns:
Error: example.com does not exist
a2ensite
is simply a Perl script that only works with filenames ending .conf
Therefore, I have to rename my setting file for example.com
to example.com.conf
as might be achieved as follows:
mv /etc/apache2/sites-available/example.com /etc/apache2/sites-available/example.com.conf
Success
Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.
>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04\x1a\xa3\xff'
>>> for b in bytelist:
... print(b) # 64 4 26 163 255
>>> [b for b in bytelist] # [64, 4, 26, 163, 255]
>>> bytelist[2] # 26
It is probably quite fast. Why not create it as a sql function.
CREATE FUNCTION [dbo].[GetFirstDayOfMonth] ( @InputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CAST(CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' +
CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01' AS DATETIME)
END
GO
In objective C variables with no value were equal to 'nil'(it was also possible to use 'nil' values same as 0 and false), hence it was possible to use variables in conditional statements (Variables having values are same as 'TRUE' and those with no values were equal to 'FALSE').
Swift provides type safety by providing 'optional value'. i.e. It prevents errors formed from assigning variables of different types.
So in Swift, only booleans can be provided on conditional statements.
var hw = "Hello World"
Here, even-though 'hw' is a string, it can't be used in an if statement like in objective C.
//This is an error
if hw
{..}
For that it needs to be created as,
var nhw : String? = "Hello World"
//This is correct
if nhw
{..}
In your project folder, the vendor folder is missing so you got this error:
Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in
When you download the project through git, the project is downloaded without the vendor folder
You need /vendor
because all your packages are there, including all the classes Laravel uses. The vendor directory contains your Composer dependencies.
The solution is simple, Just run this command:
composer update --no-scripts
composer update
composer update --no-scripts
It will Skips execution of scripts defined in composer.json
file.composer update
It will update your depencencies as they are specified in composer.json
file.With this command, you will re-create the vendor folder in your project and after that your project will start working normally.
I think, UNSIGNED
would be the best option to store something like time_duration
(Eg: resolved_call_time = resolved_time(DateTime)-creation_time(DateTime)
) value in minutes or hours or seconds format which will definitely be a non-negative number
I'm working on a Yocto Linux system that has a limited set of available Linux tools. I wanted to kill the process that was using a particular port (1883).
First, to see what ports we are listening to I used the following command:
root@root:~# netstat -lt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:hostmon 0.0.0.0:* LISTEN
tcp 0 0 localhost.localdomain:domain 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:9080 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:1883 0.0.0.0:* LISTEN
tcp 0 0 :::hostmon :::* LISTEN
tcp 0 0 localhost:domain :::* LISTEN
tcp 0 0 :::ssh :::* LISTEN
tcp 0 0 :::1883 :::* LISTEN
Next, I found the name of the process using port 1883 in the following way:
root@root:~# fuser 1883/tcp
290
root@root:~# ps | grep 290
290 mosquitt 25508 S /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
12141 root 8444 S grep 290
As we can see above, it's the program /usr/sbin/mosquitto
that's using port 1883.
Lastly, I killed the process:
root@root:~# systemctl stop mosquitto
I used systemctl
becuase in this case it was a systemd service.
This should do it
RedirectPermanent /contact.php /contact-us.php
Driver.getPageSource() is a bad way to verify text present. Suppose you say, driver.getPageSource().contains("input");
That doesn't verify "input" is present on the screen, only that "input" is present in the html, like an input tag.
I usually verify text on an element by using xpath:
boolean textFound = false;
try {
driver.findElement(By.xpath("//*[contains(text(),'someText')]"));
textFound = true;
} catch (Exception e) {
textFound = false;
}
If you want an exact text match, just remove the contains function:
driver.findElement(By.xpath("//*[text()='someText']));
For me, it was not using authentication in the request.
It works for me:
just go to '/home/your-user/.gradle/wrapper/dists/'
delete everything inside of this
It will be replaced by android studio
on terminal run: ionic emulate android
Its all...
We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works
with summary as (
Select Dbms_Random.Random As Ran_Number,
colmn1,
colm2,
colm3
Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
From table1, table2
Where Table1.Id = Table2.Id
Order By Dbms_Random.Random Asc)
Select tab1.col2,
tab1.col4,
tab1.col5,
From Summary s
Where s.Rank <= 2;
Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
Unfortunately, Ruby does not support such passing mechanism as e.g. AWK:
> awk -v a=1 'BEGIN {print a}'
> 1
It means you cannot pass named values into your script directly.
Using cmd options may help:
> ruby script.rb val_0 val_1 val_2
# script.rb
puts ARGV[0] # => val_0
puts ARGV[1] # => val_1
puts ARGV[2] # => val_2
Ruby stores all cmd arguments in the ARGV
array, the scriptname itself can be captured using the $PROGRAM_NAME
variable.
The obvious disadvantage is that you depend on the order of values.
If you need only Boolean switches use the option -s
of the Ruby interpreter:
> ruby -s -e 'puts "So do I!" if $agreed' -- -agreed
> So do I!
Please note the --
switch, otherwise Ruby will complain about a nonexistent option -agreed
, so pass it as a switch to your cmd invokation. You don't need it in the following case:
> ruby -s script_with_switches.rb -agreed
> So do I!
The disadvantage is that you mess with global variables and have only logical true/false values.
You can access values from environment variables:
> FIRST_NAME='Andy Warhol' ruby -e 'puts ENV["FIRST_NAME"]'
> Andy Warhol
Drawbacks are present here to, you have to set all the variables before the script invocation (only for your ruby process) or to export them (shells like BASH):
> export FIRST_NAME='Andy Warhol'
> ruby -e 'puts ENV["FIRST_NAME"]'
In the latter case, your data will be readable for everybody in the same shell session and for all subprocesses, which can be a serious security implication.
And at least you can implement an option parser using getoptlong and optparse.
Happy hacking!
A servlet at its very core is a java class; which can handle HTTP requests. Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).
Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).
Assuming you have a container, your servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you. You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc. Look at Resource 3.
Here is a fun exercise for you. Create a simple servlet like in Resource 3 and write a few System.out.println() statements in it's constructor method (Yes you can have a constructor of a servlet), init(), doGet(), doPost() methods and run the servlet in tomcat. See the console logs and tomcat logs.
Hope this helps, happy learning.
Resources
Look how the HTTP servlet looks here(Tomcat example).
Servlet Specification.
Simple Servlet example.
Start reading the book online/PDF It also provides you download of the whole book. May be this will help. if you are just starting servlets may be it's a good idea to read the material along with the servlet API. it's a slower process of learning, but is way more helpful in getting the basics clear.
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue
) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue
) if you are not careful.
And you can use Nullable
:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
Run R in emacs with ESS (Emacs Speaks Statistics) r-mode. I have one window open with my script and R code. Another has R running. Code is sent from the syntax window and evaluated. Commands, output, errors, and warnings all appear in the running R window session. At the end of some work period, I save all the output to a file. My own naming system is *.R for scripts and *.Rout for save output files. Here's a screenshot with an example.
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined
.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:
<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video
id="Video"
class="video-js vjs-default-skin vjs-big-play-centered"
controls
preload="none"
width="auto"
height="auto"
poster="poster.jpg"
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>
As Already mentioned we have two ways!
And it's done interactively! And take effect immediately!
CTRL + A followed by : And we type scrollback 1000000
And hit ENTER
You detach from the screen and come back! It will be always the same.
You open another new screen! And the value is reset again to default! So it's not a global setting!
Which is done by adding defscrollback 1000000
to .screenrc
(in home)
defscrollback
and not scrollback
(def stand for default)
What you need to know is if the file is not created ! You create it !
> cd ~ && vim .screenrc
And you add defscrollback 1000000
to it!
Or in one command
> echo "defscrollback 1000000" >> .screenrc
(if not created already)
When you add the default to .screenrc
! The already running screen at re-attach will not take effect! The .screenrc
run at the screen creation! And it make sense! Just as with a normal console and shell launch!
And all the new created screens will have the set value!
To check type CTRL + A followed by i
And The result will be as
Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)
Note too that when you change it interactively! The effect is immediate and take over the default value!
CTRL+ A followed by ESC (to enter the copy mode).
Then navigate with Up,Down or PgUp PgDown
And ESC again to quit that mode.
(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)
Now the buffer is bigger!
And that's sum it up for the important details!
Deleting node modules folder worked for me.
npm install
.I had the same question, but I also wanted the first line (header) to stay on top. So I needed to use the power of awk
cat dax-weekly.csv | awk '1 { last = NR; line[last] = $0; } END { print line[1]; for (i = last; i > 1; i--) { print line[i]; } }'
PS also works in cygwin or gitbash
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.
Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). Because the Tuple is only holding a reference to that kind of object.
Also - a tuple has its own constructor tuple()
which you can give any iterator. Which means that to create a tuple, you could do:
tuple(i for i in (1,2,3))
If you're leveraging React Hooks, you can take advantage of the useHistory
API that comes from React Router v5.
import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';
export default function StackOverflowExample() {
const history = useHistory();
const handleOnClick = useCallback(() => history.push('/sample'), [history]);
return (
<button type="button" onClick={handleOnClick}>
Go home
</button>
);
}
Another way to write the click handler if you don't want to use useCallback
const handleOnClick = () => history.push('/sample');
The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).
import { Redirect } from 'react-router';
// ... your class implementation
handleOnClick = () => {
// some action...
// then redirect
this.setState({redirect: true});
}
render() {
if (this.state.redirect) {
return <Redirect push to="/sample" />;
}
return <button onClick={this.handleOnClick} type="button">Button</button>;
}
Reference: https://reacttraining.com/react-router/web/api/Redirect
You can also take advantage of Router
's context that's exposed to the React component.
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired
}).isRequired,
staticContext: PropTypes.object
}).isRequired
};
handleOnClick = () => {
this.context.router.push('/sample');
}
This is how <Redirect />
works under the hood.
If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter
then expose the history
as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.
// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';
export const history = createHistory();
export default class BrowserRouter extends Component {
render() {
return <Router history={history} children={this.props.children} />
}
}
// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';
render(
<BrowserRouter>
<App/>
</BrowserRouter>
);
// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';
history.push('/sample');
Latest BrowserRouter
to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js
Push a new state to the browserHistory
instance:
import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');
Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
SHOW CREATE PROCEDURE proc_name;
returns the definition of proc_name
If you get sort column name and sort direction as string and don't want to use switch or if\else syntax to determine column, then this example may be interesting for you:
private readonly Dictionary<string, Expression<Func<IuInternetUsers, object>>> _sortColumns =
new Dictionary<string, Expression<Func<IuInternetUsers, object>>>()
{
{ nameof(ContactSearchItem.Id), c => c.Id },
{ nameof(ContactSearchItem.FirstName), c => c.FirstName },
{ nameof(ContactSearchItem.LastName), c => c.LastName },
{ nameof(ContactSearchItem.Organization), c => c.Company.Company },
{ nameof(ContactSearchItem.CustomerCode), c => c.Company.Code },
{ nameof(ContactSearchItem.Country), c => c.CountryNavigation.Code },
{ nameof(ContactSearchItem.City), c => c.City },
{ nameof(ContactSearchItem.ModifiedDate), c => c.ModifiedDate },
};
private IQueryable<IuInternetUsers> SetUpSort(IQueryable<IuInternetUsers> contacts, string sort, string sortDir)
{
if (string.IsNullOrEmpty(sort))
{
sort = nameof(ContactSearchItem.Id);
}
_sortColumns.TryGetValue(sort, out var sortColumn);
if (sortColumn == null)
{
sortColumn = c => c.Id;
}
if (string.IsNullOrEmpty(sortDir) || sortDir == SortDirections.AscendingSort)
{
contacts = contacts.OrderBy(sortColumn);
}
else
{
contacts = contacts.OrderByDescending(sortColumn);
}
return contacts;
}
Solution based on using Dictionary that connects needed for sort column via Expression> and its key string.
Here is how to build a function that returns a result set that can be queried as if it were a table:
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
if (addr == null || addr.trim() === ''){
//...
}
A null
comparison will also catch undefined
. If you want false
to pass too, use !addr
. For backwards browser compatibility swap addr.trim()
for $.trim(addr)
.
It's also possible to emulate innerText
behavior in other browsers:
if (((typeof window.HTMLElement) !== "undefined") && ((typeof HTMLElement.prototype.__defineGetter__) !== "undefined")) {
HTMLElement.prototype.__defineGetter__("innerText", function () {
if (this.textContent) {
return this.textContent;
} else {
var r = this.ownerDocument.createRange();
r.selectNodeContents(this);
return r.toString();
}
});
HTMLElement.prototype.__defineSetter__("innerText", function (str) {
if (this.textContent) {
this.textContent = str;
} else {
this.innerHTML = str.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/\n/g, "<br />\n");
}
});
}
Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx
EDIT:
You need to put the protocol prefix in front the address, i.e. in your case "ftp://"
Several people misread this as a question about how to store passwords in a database. That is wrong. It is about how to store the password that lets you get to the database.
The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.
This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.
$.ajaxPrefilter( "json script", function( options ) {
options.crossDomain = true;
});
While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print
, or otherwise send Unicode strings to stdout
, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use:
File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
This means the charset is cp850
.
You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850')
. Or you can look up cp850 online (e.g., at Wikipedia).
It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'
.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)
But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:
>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'
So, how do you print a string that won't print on your console?
You can replace every print
function with something like this:
>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?
… but that's going to get pretty tedious pretty fast.
The simple thing to do is to just set the error handler on sys.stdout
:
>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?
For printing to a file, things are pretty much the same, except that you don't have to set f.errors
after the fact, you can set it at construction time. Instead of this:
with open('path', 'w', encoding='cp850') as f:
Do this:
with open('path', 'w', encoding='cp850', errors='replace') as f:
… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
with open('path', 'w', encoding='utf-8') as f:
I did it using Angular 2 Location since I didn't want to manipulate the global window object myself.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor
It can be done like this:
import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({selector: 'app-component'})
class AppCmp {
constructor(location: Location) {
location.go('/foo');
}
}
The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.
or edit this parameter on your application.properties
server.tomcat.uri-encoding=utf-8
struct
and typedef
are two very different things.
The struct
keyword is used to define, or to refer to, a structure type. For example, this:
struct foo {
int n;
};
creates a new type called struct foo
. The name foo
is a tag; it's meaningful only when it's immediately preceded by the struct
keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespace
s.)
A typedef
, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:
typedef int my_int;
my_int
is a new name for int
; my_int
and int
are exactly the same type. Similarly, given the struct
definition above, you can write:
typedef struct foo foo;
The type already has a name, struct foo
. The typedef
declaration gives the same type a new name, foo
.
The syntax allows you to combine a struct
and typedef
into a single declaration:
typedef struct bar {
int n;
} bar;
This is a common idiom. Now you can refer to this structure type either as struct bar
or just as bar
.
Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct
version to refer to it:
typedef struct node {
int data;
struct node *next; /* can't use just "node *next" here */
} node;
Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:
typedef struct node_s {
/* ... */
} node;
(Personally, I prefer to omit the typedef
and refer to the type as struct bar
. The typedef
save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n
by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)
(C++ has different rules. Given a declaration of struct blah
, you can refer to the type as just blah
, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)
future.utils
allows for python 2 and 3 compatibility.
# Python 2 and 3: option 3
from future.utils import iteritems
heights = {'man': 185,'lady': 165}
for (key, value) in iteritems(heights):
print(key,value)
>>> ('lady', 165)
>>> ('man', 185)
See this link: https://python-future.org/compatible_idioms.html
This is a nice way to do it:
Double d = 0.5;
float f = d.floatValue();
if you have d as a primitive type just add one line:
double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();
I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.
SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.
This article explains a bit:
"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."
Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.
try
subtotal.value= 5 // some value
proc = async function(x,y) {_x000D_
let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
_x000D_
let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
console.log(r);_x000D_
_x000D_
subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid" value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy" value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal" value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:
$('#textareaID').on('input change keyup', function () {
if (this.value.length) {
// textarea has content
} else {
// textarea is empty
}
});
For outdated browsers you might also add selectionchange
and propertychange
(as mentioned in other answers). But selectionchange
didn't work for me in IE9. That's why I added keyup
.
From my understanding of the code provided above, it loads the file and does map operation and saves it back. There is no operation that requires shuffle. Also, there is no operation that requires data to be brought to the driver hence tuning anything related to shuffle or driver may have no impact. The driver does have issues when there are too many tasks but this was only till spark 2.0.2 version. There can be two things which are going wrong.
Here is a simple way of running MySQL queries in the bash shell
mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"
Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:
gcc -static -L/usr/lib -I/usr/lib main.c -ltommath
All of the above answer are only partially correct. Specially in region like Australia, they always include pole and calculate a very large rectangle even for 10kms.
Specially the algorithm by Jan Philip Matuschek at http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#UsingIndex included a very large rectangle from (-37, -90, -180, 180) for almost every point in Australia. This hits a large users in database and distance have to be calculated for all of the users in almost half the country.
I found that the Drupal API Earth Algorithm by Rochester Institute of Technology works better around pole as well as elsewhere and is much easier to implement.
https://www.rit.edu/drupal/api/drupal/sites%21all%21modules%21location%21earth.inc/7.54
Use earth_latitude_range
and earth_longitude_range
from the above algorithm for calculating bounding rectangle
And use the distance calculation formula documented by google maps to calculate distance
To search by kilometers instead of miles, replace 3959 with 6371. For (Lat, Lng) = (37, -122) and a Markers table with columns lat and lng, the formula is:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
Read my detailed answer at https://stackoverflow.com/a/45950426/5076414
This can be achieved in a very simple way 1. Write this in the view.
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHide}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.
public bool _isHide = false;
public bool IsHide
{
get { return _isHide; }
set
{
_isHide = value;
OnPropertyChanged("IsHide");
}
}
This is the way the IsHide property gets the value.
userNote.IsHide = userNote.IsNoteDeleted;
The simple difference between select Into and Insert Into is: --> Select Into don't need existing table. If you want to copy table A data, you just type Select * INTO [tablename] from A. Here, tablename can be existing table or new table will be created which has same structure like table A.
--> Insert Into do need existing table.INSERT INTO [tablename] SELECT * FROM A;. Here tablename is an existing table.
Select Into is usually more popular to copy data especially backup data.
You can use as per your requirement, it is totally developer choice which should be used in his scenario.
Performance wise Insert INTO is fast.
References :
https://www.w3schools.com/sql/sql_insert_into_select.asp https://www.w3schools.com/sql/sql_select_into.asp
Another solution for copying files into a running container is using tar:
tar -c foo.sh | docker exec -i theDockerContainer /bin/tar -C /tmp -x
Copies the file foo.sh
into /tmp
of the container.
Edit: Remove reduntant -f
, thanks to Maartens comment.
My solution, as a jQuery extension based on Robert Koritnik's answer:
$.fn.fitToWidth=function(){
$(this).wrapInner("<span style='display:inline;font:inherit;white-space:inherit;'></span>").each(function(){
var $t=$(this);
var a=$t.outerWidth(),
$s=$t.children("span"),
f=parseFloat($t.css("font-size"));
while($t.children("span").outerWidth() > a) $t.css("font-size",--f);
$t.html($s.html());
});
}
This actually creates a temporary span inheriting important properties, and compares the width difference. Granted, the while loop needs to be optimised (reduce by a percentage difference calculated between the two sizes).
Example usage:
$(function(){
$("h1").fitToWidth();
});
If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character
public void switchToNextTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void closeAndSwitchToNextTab() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void switchToPreviousTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void closeTabAndReturn() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void switchToPreviousTabAndClose() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
driver.close();
}
just put it in a <p>
or <font>
and grab that $('#listItem font').text()
First thing that came to mind
<li id="listItem">
<font>This is some text</font>
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
Try:
td, th {
white-space: nowrap;
overflow: hidden;
}
Place this line before the closing script tag,writing from memory:
window.onload = GetTimeZoneOffset;
i think the question is how to call the javascript function on pageload
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description) where T : Enum
{
foreach(var field in typeof(T).GetFields())
{
if (Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", nameof(description));
// Or return default(T);
}
}
Usage:
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
Also you can use DownloadFileAsync
method in WebClient
class. It downloads to a local file the resource with the specified URI
. Also this method does not block the calling thread.
Sample:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
For more information:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
Construct the first parameter as an instance of Action
, e.g.
var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
() => CheckFiles(inputID, col),
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:
a = []
p = input()
p = p.split()
for i in p:
a.append(int(i))
Also a list comprehension can be used
p = input().split("whatever the seperator is")
And to convert all the inputs from string to int we do the following
x = [int(i) for i in p]
print(x, end=' ')
shall print the list elements in a straight line.
Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
You can't do this within the Python program, because the shell decides which version to use if you a shebang line.
If you aren't using a shell with a shebang line and just type python myprogram.py
it uses the default version unless you decide specifically which Python version when you type pythonXXX myprogram.py
which version to use.
Once your Python program is running you have already decided which Python executable to use to get the program running.
virtualenv
is for segregating python versions and environments, it specifically exists to eliminate conflicts.
This will do the trick. Note the use of display()
instead of print.
with pd.option_context('display.max_rows', 5, 'display.max_columns', None):
display(my_df)
EDIT:
The use of display
is required because pd.option_context
settings only apply to display
and not to print
.
It does not work because sequence does not work in following scenarios:
Source: http://www.orafaq.com/wiki/ORA-02287
However this does work:
insert into table_name
(col1, col2)
select my_seq.nextval, inner_view.*
from (select 'some value' someval
from dual
union all
select 'another value' someval
from dual) inner_view;
Try it out:
create table table_name(col1 varchar2(100), col2 varchar2(100));
create sequence vcert.my_seq
start with 1
increment by 1
minvalue 0;
select * from table_name;
Add -t
install flag, as on the screenshot below:
Why I prefer Fragment over Activity in ALL CASES.
Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack
, its views will be destroyed. So you can stack much more Fragments than Activity.
Backstack
manipulation. With FragmentManager
, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.
A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments()
to find specific Fragment (not encouraged).
In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.
I think you can also execute the pwd() function on the particular node:
node {
def PWD = pwd();
...
}
As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.
I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.
You can make this bit more cleaner by using:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
Similar to @this.lau_ answer, different approach.
I'm using Visual Studio 2017 Community Edition.
I solved this problem by making a directory called tessdata in the Debug directory of my project. Then I put the eng.traineddata file into said directory.
your <%= //map.size() %>
doesnt simply work because it should have been
<% //= map.size() %>
I’m surprised no-one answered with this code:
for(var child=elt.firstChild;
child;
child=child.nextSibling){
do_thing(child);
}
Or, if you only want children which are elements, this code:
for(var child=elt.firstElementChild;
child;
child=child.nextElementSibling){
do_thing(child);
}
Use os.path.getsize(path)
which will
Return the size, in bytes, of path. Raise
OSError
if the file does not exist or is inaccessible.
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')
Or use os.stat(path).st_size
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
Or use Path(path).stat().st_size
(Python 3.4+)
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
It means that the field is (part of) a non-unique index. You can issue
show create table <table>;
To see more information about the table structure.
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
You can add onclick=""
to hovered element. Hover will work after that.
Edit: But you really shouldn't add anything style related to your markup, just posted it as an alternative.
I ran through similar problem and found that I was trying to get the offset of footer but I was loading my script inside a div before the footer. It was something like this:
<div> I have some contents </div>
<script>
$('footer').offset().top;
</script>
<footer>This is footer</footer>
So, the problem was, I was calling the footer element before the footer was loaded.
I pushed down my script below footer and it worked fine!
Try this one:
string strDate = DateTime.Now.ToString("MM/01/yyyy");
Just an additional note here as I found this when looking for a solution for a fixed div that I want to scroll. For my scenario I found that its preferable to take into account the padding on the div so I can hit the end exactly. So expanding on @Dr.Molle's answer I add the following
$('#flux').bind('scroll', function() {
var scrollPosition = $(this).scrollTop() + $(this).outerHeight();
var divTotalHeight = $(this)[0].scrollHeight
+ parseInt($(this).css('padding-top'), 10)
+ parseInt($(this).css('padding-bottom'), 10)
+ parseInt($(this).css('border-top-width'), 10)
+ parseInt($(this).css('border-bottom-width'), 10);
if( scrollPosition == divTotalHeight )
{
alert('end reached');
}
});
That'll give you the precise location, including padding and borders
Also, if you don't have the gradlew file in your current directory:
You can install gradle with homebrew with the following command:
$ brew install gradle
As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):
$ gradle test
Note: if you choose to hide the badge, please use
.grecaptcha-badge { visibility: hidden; }
You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text:
This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and
<a href="https://policies.google.com/terms">Terms of Service</a> apply.
more details here reCaptacha
ViewPagerIndicator
has not been updated since 2012 and got several bugs that were never fixed.
I finally found an alternative with this light library that displays nice dots for the viewpager
, here is the link:
https://github.com/ongakuer/CircleIndicator
Easy to implement!
In your string I see: 15.5859949000000662452.23862099999999
which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?
You may also want to figure out if your last String
will be empty, and account for that situation.
Try .NET Checker
by Scott Hanselman.
Creating firewall rules
Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.
For Cloud Console:
Specify the Targets of the rule.
For an ingress rule, specify the Source filter:
For an egress rule, specify the Destination filter:
Define the Protocols and ports to which the rule will apply:
Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.
Define specific protocols and ports:
(Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.
(Optional) You can enable firewall rules logging:
Click Create.
Link: [1] https://cloud.google.com/vpc/docs/firewalls#firewall_rule_components
number.parseFloat(2)
works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost
,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me.
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
Esperento57's script doesn't work in older PowerShell versions. This example does:
Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
You must create a MySQL database first. Then go to settings.py
file and edit the 'DATABASES'
dictionary with your MySQL credentials:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'YOUR_DATABASE_NAME',
'USER': 'YOUR_MYSQL_USER',
'PASSWORD': 'YOUR_MYSQL_PASS',
'HOST': 'localhost', # Or an IP that your DB is hosted on
'PORT': '3306',
}
}
Here is a complete installation guide for setting up Django to use MySQL on a virtualenv:
http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/
Yes.
Constructors are nothing more than special methods, and can throw exceptions like any other method.
String res =" Application " res=res.trim();
o/p: Application
Note: White space ,blank space are trim or removed
You can use a CASE
statement with an aggregate function. This is basically the same thing as a PIVOT
function in some RDBMS:
SELECT distributor_id,
count(*) AS total,
sum(case when level = 'exec' then 1 else 0 end) AS ExecCount,
sum(case when level = 'personal' then 1 else 0 end) AS PersonalCount
FROM yourtable
GROUP BY distributor_id
You need to remove the <a>
tag to get rid of this.
or try using :-
<a href="/" onclick="return false;">123n</a>
Firstly to answer your question, when we don't declare SerialVersionUID in our class, Java runtime generates it for us, but that process is sensitive to many class meta data including number of fields, type of fields, access modifier of fields, interface implemented by class etc. Therefore it is recommended to declare it ourselves and Eclipse is warning you about the same.
Serialization: We often work with important objects whose state (data in the variables of the object) is so important that we can not risk to lose it due to power/system failures (or) network failures in case of sending the object state to other machine. The solution for this problem is named "Persistence" which simply means persisting (holding/saving) the data. Serialization is one of many other ways to achieve persistence (by saving data to disk/memory). When saving the state of the object, it is important to create an identity for the object, to be able to properly read it back (de-serialization). This unique identification is ID is SerialVersionUID.
The main reason is that deflate is faster to encode than gzip and on a busy server that might make a difference. With static pages it's a different question, since they can easily be pre-compressed once.
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Make a custom ImageView
that maintains its aspect ratio:
src/com/example/graphicstest/SquareImageView.java
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:
res/layout/grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.graphicstest.SquareImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000"/>
</FrameLayout>
Now make some sort of adapter for your GridView
:
src/com/example/graphicstest/MyAdapter.java
private final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mItems.add(new Item("Red", R.drawable.red));
mItems.add(new Item("Magenta", R.drawable.magenta));
mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
mItems.add(new Item("Gray", R.drawable.gray));
mItems.add(new Item("Green", R.drawable.green));
mItems.add(new Item("Cyan", R.drawable.cyan));
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Item getItem(int i) {
return mItems.get(i);
}
@Override
public long getItemId(int i) {
return mItems.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private static class Item {
public final String name;
public final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
Set that adapter to your GridView
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
And enjoy the results:
If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.
Sample Url: http://user:[email protected]/url
URL url = new URL("http://user:[email protected]/url");
URLConnection urlConnection = url.openConnection();
if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
InputStream inputStream = urlConnection.getInputStream();
Please note in the comment, from valerybodak, below how it is done in an Android development environment.
Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:
Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)
or like this:
Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)
encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.
You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/
var a = { what: "A regular JS object" },
b = $('body');
if ( a.jquery ) { // falsy, since it's undefined
alert(' a is a jQuery object! ');
}
if ( b.jquery ) { // truthy, since it's a string
alert(' b is a jQuery object! ');
}
you can find Java Communications API 2.0 in below link
My suggestion:
using System.Linq;
string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());
reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c
Another way is:
Characters="TESTING"
index=1
while [ $index -le ${#Characters} ]
do
echo ${Characters} | cut -c${index}-${index}
index=$(expr $index + 1)
done
This just happened to me.
Solution: Pull down my own branch so I get that extra commit. Then push it back to my remote branch.
literally what I did on my branch was:
git pull
git push
You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.
If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.
Accept: application/xml
You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1
EDIT: based on your edited question with code:
Simple return list of string, instead of converting it to XML. try it using Fiddler.
public List<string> Get(int tenantID, string dataType, string ActionName)
{
List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
return SQLResult;
}
For example if your list is like:
List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;
and you specify Accept: application/xml
the output will be:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Test1</string>
<string>Test2</string>
<string>Test3</string>
</ArrayOfstring>
and if you specify 'Accept: application/json' in the request then the output will be:
[
"Test1",
"Test2",
"Test3"
]
So let the client request the content type, instead of you sending the customized xml.
If running on Windows try running R or R Studio as administrator to avoid Windows OS file system constraints.
Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.
https://maps.google.com/?parameter=value
q=
Used to specify the search query in Google maps search.
eg :
https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679
near=
Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.
z=
Zoom level. Can be set 19 normally, but in certain cases can go up to 23.
ll=
Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.
sll=
Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.
t=
Sets the kind of map shown. Can be set to:
m – normal map
k – satellite
h – hybrid
p – terrain
saddr=
Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.
daddr=
Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.
via=
Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.
doflg=
Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.
msa=
Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.
reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Let's measure the performance by using the following piece of code.
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
a = time.clock()
res = (A==B).all()
b = time.clock()
exec_time0.append( b - a )
a = time.clock()
res = np.array_equal(A,B)
b = time.clock()
exec_time1.append( b - a )
a = time.clock()
res = np.array_equiv(A,B)
b = time.clock()
exec_time2.append( b - a )
print 'Method: (A==B).all(), ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)
Output
Method: (A==B).all(), 0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515
According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
Just solved this problem. In my case it was domain controller is not accessible, because both dns servers was google dns.
I just add to checklist for this problem:
In Sql Server:
insert into Table_Name(PersonName,PersonEmail) values(NULL,'[email protected]')
PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.
Code Behind:
string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
string email = txtEmail.Text;
insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')
You might be interested in itertools.product
, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)
yields all values of the form (a, b)
, where the a
values come from A
and the b
values come from B
. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product
is the "inner" one. Generally, itertools.product(a0, a1, ... an)
is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]
The problem id because of inp.read();
method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.
What you can do simply
for(int i=0;i<T;i++) {
String s= inp.readLine();
String[] intValues = inp.readLine().split(" ");
int[] m= new int[2];
m[0]=Integer.parseInt(intValues[0]);
m[1]=Integer.parseInt(intValues[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName)
.
For instance
if $(ConfigurationName) == Debug xcopy something somewhere
This also works (taken a hint from this question)
.image_block {
height: 175px;
width:175px;
position:relative;
}
.image_block a img{
margin:auto; /* Required */
position:absolute; /* Required */
bottom:0; /* Aligns at the bottom */
left:0;right:0; /* Aligns horizontal center */
max-height:100%; /* images bigger than 175 px */
max-width:100%; /* will be shrinked to size */
}
Instead of using <source>
tag, use <src>
attribute of <video>
as below and you will see the action.
<video width="320" height="240" src="mov1.mov"></video>
or
you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:
<video id="sampleMovie" width="640" height="360" preload controls>
<source src="HTML5Sample_H264.mov" />
<source src="HTML5Sample_Ogg.ogv" />
<source src="HTML5Sample_WebM.webm" />
</video>
If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.
You can also use get(). Initially I believed it to only check if key existed.
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.
Just in case you have pre-stored the values in an array, you can call them in the following format:
for i in range(0,n):
print arr[i],
Just had a similar issue when I ran pod install
, I saw the following warnings/errors (related to CLANG_CXX_LIBRARY
):
[!] The `Project [Debug]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
[!] The `Project [Release]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
Project
so you can see the Build Settings
.Target
(AppName
under Targets
)C++ Standard Library
(It will probably be in BOLD - This means it's overridden).The line should not be bolded anymore and if you run pod install
the warnings/errors should have disappeared.
For Bootstrap 3, there is
placement: 'auto right'
which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:
$('.infopoint').popover({
trigger:'hover',
animation: false,
placement: 'auto right'
});
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
table {
border-spacing: 10px;
}
This worked for me once I removed
border-collapse: separate;
from my table tag.
Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.
In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:
' Integer array
Dim i as Integer() = {1, 2, 3, 4}
' Object array
Dim o() = {1, 2, 3}
Check more info:
May also want to use "documentElement":
var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);
In my case carate table script is:
CREATE TABLE public."Survey_symptom_binds"
(
id integer NOT NULL DEFAULT nextval('"Survey_symptom_binds_id_seq"'::regclass),
survey_id integer,
"order" smallint,
symptom_id integer,
CONSTRAINT "Survey_symptom_binds_pkey" PRIMARY KEY (id)
)
SO:
SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass),
MAX(id)
FROM public."Survey_symptom_binds";
SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass) less than MAX(id) !!!
Try to fix the proble:
SELECT setval('"Survey_symptom_binds_id_seq"', (SELECT MAX(id) FROM public."Survey_symptom_binds")+1);
Good Luck every one!
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.
function stripTrailingSlash(str) {
if(str.substr(-1) === '/') {
return str.substr(0, str.length - 1);
}
return str;
}
Note: IE8 and older do not support negative substr offsets. Use str.length - 1
instead if you need to support those ancient browsers.
Probably less elegant than other approaches here, but I've always used get reset --hard HEAD~N
to undo multiple commits, where N
is the number of commits you want to go back.
Or, if unsure of the exact number of commits, just running git reset --hard HEAD^
(which goes back one commit) multiple times until you reach the desired state.
If you are asking about actual command line makefiles then you can export a makefile, or you can call MSBuild on a solution file from the command line. What exactly do you want to do with the makefile?
You can do a search on SO for MSBuild for more details.
You can do this way
a, b = map(int, input().split())
OR
a, b = input().split()
print(int(a))
OR
MyList = list(map(int, input().split()))
a = MyList[0]
b = MyList[1]
for me, this worked
exec utl_mail.send@myotherdb(
sender => '[email protected]',recipients => '[email protected],
cc => null, subject => 'my subject', message => 'my message'
);
From an SEO perspective, hyphens are preferred over underscores. Convert to lowercase, remove all apostrophes, then replace all non-alphanumeric strings of characters with a single hyphen. Trim excess hyphens off the start and finish.
You can try this if you want :)
private void ClearControls(Control.ControlCollection c)
{
foreach (Control control in c)
{
if (control.HasChildren)
{
ClearControls(control.Controls);
}
else
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
txt.Clear();
}
if (control is ComboBox)
{
ComboBox cmb = (ComboBox)control;
if (cmb.Items.Count > 0)
cmb.SelectedIndex = -1;
}
if (control is CheckBox)
{
CheckBox chk = (CheckBox)control;
chk.Checked = false;
}
if (control is RadioButton)
{
RadioButton rdo = (RadioButton)control;
rdo.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearControls((ControlCollection)this.Controls);
}
https://drive.google.com/open?id=0BzBKpZ4nzNzUR05nVUI1aVF6N1k
package com.keshav.speechtotextexample;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
====================================================
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_gradient"
android:orientation="vertical">
<TextView
android:id="@+id/txtSpeechInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:textColor="@color/white"
android:textSize="26dp"
android:textStyle="normal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:gravity="center"
android:orientation="vertical">
<ImageButton
android:id="@+id/btnSpeak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:src="@drawable/ico_mic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/tap_on_mic"
android:textColor="@color/white"
android:textSize="15dp"
android:textStyle="normal" />
</LinearLayout>
</RelativeLayout>
===============================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Speech To Text</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="speech_prompt">Say something…</string>
<string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
<string name="tap_on_mic">Tap on mic to speak</string>
</resources>
===============================================================
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
I think using the STL method 'remove_if
' from could help to prevent some weird issue when trying to attempt to delete the object that is wrapped by the iterator.
This solution may be less efficient.
Let's say we have some kind of container, like vector or a list called m_bullets:
Bullet::Ptr is a shared_pr<Bullet>
'it
' is the iterator that 'remove_if
' returns, the third argument is a lambda function that is executed on every element of the container. Because the container contains Bullet::Ptr
, the lambda function needs to get that type(or a reference to that type) passed as an argument.
auto it = std::remove_if(m_bullets.begin(), m_bullets.end(), [](Bullet::Ptr bullet){
// dead bullets need to be removed from the container
if (!bullet->isAlive()) {
// lambda function returns true, thus this element is 'removed'
return true;
}
else{
// in the other case, that the bullet is still alive and we can do
// stuff with it, like rendering and what not.
bullet->render(); // while checking, we do render work at the same time
// then we could either do another check or directly say that we don't
// want the bullet to be removed.
return false;
}
});
// The interesting part is, that all of those objects were not really
// completely removed, as the space of the deleted objects does still
// exist and needs to be removed if you do not want to manually fill it later
// on with any other objects.
// erase dead bullets
m_bullets.erase(it, m_bullets.end());
'remove_if
' removes the container where the lambda function returned true and shifts that content to the beginning of the container. The 'it
' points to an undefined object that can be considered garbage. Objects from 'it' to m_bullets.end() can be erased, as they occupy memory, but contain garbage, thus the 'erase' method is called on that range.
You just need to clear the table and call the function that generates the filling of the table.
ButtonRefresh.setOnAction((event) -> { tacheTable.getItems().clear(); PopulateTable(); });
Open a command prompt window (press Windows + R, type in cmd
, and hit Enter).
Type python.exe
If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:
MyClass varClass = new MyClass();
varClass.propObjectProperty = new { Id = 1, Description = "test" };
//if you need to treat the class as an object
var varObjectProperty = ((dynamic)varClass).propObjectProperty;
((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };
//if your property is an object, instead
var varObjectProperty = varClass.propObjectProperty;
varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };
With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the
new { ... }
syntax.
In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.
What type of granularity are you looking for? You can typically get by with:
$http.get(url).then(
//success function
function(results) {
//do something w/results.data
},
//error function
function(err) {
//handle error
}
);
I've found that "finally" and "catch" are better off when chaining multiple promises.
You can try as follows it works for me
select * from nm_admission where trunc(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
OR
select * from nm_admission where trunc(entry_timestamp) = '09-SEP-2018';
You can also try using to_char but remember to_char is too expensive
select * from nm_admission where to_char(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
The TRUNC(17-SEP-2018 08:30:11) will give 17-SEP-2018 00:00:00 as a result, you can compare the only date portion independently and time portion will skip.
url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi
Both your queries are correct and should give you the right answer.
I would suggest the following query to troubleshoot your problem.
SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc
That is add count(*) field. This will give you idea how many rows were eliminated using the group command.
This should make it seamless:
public static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
public static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
private void test() {
String [] a = {"Hello", "Goodbye"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
You should also look at new triggers.
MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:
use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;
delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row
begin
insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//
/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');
Use append method, eg:
lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)
for existing repository
type in terminal
$ heroku git:remote -a example
Here is the code to check if AZ module is installed or not:
$checkModule = "AZ"
$Installedmodules = Get-InstalledModule
if ($Installedmodules.name -contains $checkModule)
{
"$checkModule is installed "
}
else {
"$checkModule is not installed"
}
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
you have to do some changes by applying group by or query with in query.
"SELECT CITY,LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;"
it will return longest cityname from city.
Create a cronjob like this to work on every minute
* * * * * /usr/bin/php path/to/cron.php &> /dev/null
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven't found any bugs in the functions; After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
Solved this by doing a few things, first getting the height
of my TextView
and diving it by the text size
to get the total amount of lines possible with the TextView
.
int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize();
After you get this value you need to set your TextView
maxLines
to this new value.
TextView.setMaxLines(maxLines);
Set the Gravity
to Bottom
once the maximum amount of lines has been exceeded and it will scroll down automatically.
if (TextView.getLineCount() >= maxLines) {
TextView.setGravity(Gravity.BOTTOM);
}
In order for this to work correctly, you must use append()
to the TextView
, If you setText()
this will not work.
TextView.append("Your Text");
The benefit of this method is that this can be used dynamically regardless of the height
of your TextView
and the text size
. If you decide to make modifications to your layout this code would still work.
This code checks if the number is odd or even in PHP. In the example $a
is 2
and you get even number. If you need odd then change the $a
value
$a=2;
if($a %2 == 0){
echo "<h3>This Number is <b>$a</b> Even</h3>";
}else{
echo "<h3>This Number is <b>$a</b> Odd</h3>";
}
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
It was solved with:
script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';
I'm interested in this as well. The only explanation I've found is that xsd:include
is used for intra-namespace inclusions, while xsd:import
is for inter-namespace inclusion.
As of version 17.0, you can format with the dt
accessor:
dates.dt.strftime('%Y-%m-%d')
SELECT * FROM (
SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;
You may try using this
<?php
$json = json_decode(file_get_contents('./prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>
The "./" allows to search url from current directory. You may use
chdir($_SERVER["DOCUMENT_ROOT"]);
to change current working directory to root of your website if path is relative from root directory.
There are three tables: persons, schools and persons_schools, which connects persons to the schools they study in. A reference to the person with id=6 is absent in the table persons_schools. However the person with id=6 is presented in the result lef-joined grid.
List<Person> persons = new List<Person>
{
new Person { id = 1, name = "Alex", phone = "4235234" },
new Person { id = 2, name = "Bob", phone = "0014352" },
new Person { id = 3, name = "Sam", phone = "1345" },
new Person { id = 4, name = "Den", phone = "3453452" },
new Person { id = 5, name = "Alen", phone = "0353012" },
new Person { id = 6, name = "Simon", phone = "0353012" }
};
List<School> schools = new List<School>
{
new School { id = 1, name = "Saint. John's school"},
new School { id = 2, name = "Public School 200"},
new School { id = 3, name = "Public School 203"}
};
List<PersonSchool> persons_schools = new List<PersonSchool>
{
new PersonSchool{id_person = 1, id_school = 1},
new PersonSchool{id_person = 2, id_school = 2},
new PersonSchool{id_person = 3, id_school = 3},
new PersonSchool{id_person = 4, id_school = 1},
new PersonSchool{id_person = 5, id_school = 2}
//a relation to the person with id=6 is absent
};
var query = from person in persons
join person_school in persons_schools on person.id equals person_school.id_person
into persons_schools_joined
from person_school_joined in persons_schools_joined.DefaultIfEmpty()
from school in schools.Where(var_school => person_school_joined == null ? false : var_school.id == person_school_joined.id_school).DefaultIfEmpty()
select new { Person = person.name, School = school == null ? String.Empty : school.name };
foreach (var elem in query)
{
System.Console.WriteLine("{0},{1}", elem.Person, elem.School);
}
There is a python package for this Autopy
The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).
Call this before the query:
set define off;
Alternatively, hacky:
update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';
From Tuning SQL*Plus:
SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.
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))
I know it is a very old post, but since this appears in the top search results hence adding the latest update for those using SQL Server 2016 SP1 -
create or alter procedure procTest
as
begin
print (1)
end;
go
This creates a Stored Procedure if does not already exist, but alters it if exists.
I have tested both Jackson and BeanUtils and found out that BeanUtils is much faster.
In my machine(Windows8.1 , JDK1.7) I got this result.
BeanUtils t2-t1 = 286
Jackson t2-t1 = 2203
public class MainMapToPOJO {
public static final int LOOP_MAX_COUNT = 1000;
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("success", true);
map.put("data", "testString");
runBeanUtilsPopulate(map);
runJacksonMapper(map);
}
private static void runBeanUtilsPopulate(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
try {
TestClass bean = new TestClass();
BeanUtils.populate(bean, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
long t2 = System.currentTimeMillis();
System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));
}
private static void runJacksonMapper(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
ObjectMapper mapper = new ObjectMapper();
TestClass testClass = mapper.convertValue(map, TestClass.class);
}
long t2 = System.currentTimeMillis();
System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));
}}
if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:
set.seed(10)
x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]
cor(x)
Error in cor(x) : 'x' must be numeric
but
cor(x[sapply(x, is.numeric)])
V1 V2 V3 V4 V5 V6 V7
V1 1.00000000 0.3025766 -0.22473884 -0.72468776 0.18890578 0.14466161 0.05325308
V2 0.30257657 1.0000000 -0.27871430 -0.29075170 0.16095258 0.10538468 -0.15008158
V3 -0.22473884 -0.2787143 1.00000000 -0.22644156 0.07276013 -0.35725182 -0.05859479
V4 -0.72468776 -0.2907517 -0.22644156 1.00000000 -0.19305921 0.16948333 -0.01025698
V5 0.18890578 0.1609526 0.07276013 -0.19305921 1.00000000 0.07339531 -0.31837954
V6 0.14466161 0.1053847 -0.35725182 0.16948333 0.07339531 1.00000000 0.02514081
V7 0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954 0.02514081 1.00000000
V8 0.44705527 0.1698571 0.39970105 -0.42461411 0.63951574 0.23065830 -0.28967977
V9 0.21006372 -0.4418132 -0.18623823 -0.25272860 0.15921890 0.36182579 -0.18437981
V10 0.02326108 0.4618036 -0.25205899 -0.05117037 0.02408278 0.47630138 -0.38592733
V8 V9 V10
V1 0.447055266 0.210063724 0.02326108
V2 0.169857120 -0.441813231 0.46180357
V3 0.399701054 -0.186238233 -0.25205899
V4 -0.424614107 -0.252728595 -0.05117037
V5 0.639515737 0.159218895 0.02408278
V6 0.230658298 0.361825786 0.47630138
V7 -0.289679766 -0.184379813 -0.38592733
V8 1.000000000 0.001023392 0.11436143
V9 0.001023392 1.000000000 0.15301699
V10 0.114361431 0.153016985 1.00000000
Answering late since I recently had the same question when reading text from file; tried several options such as:
with open('verdict.txt') as f:
First option below produces a list called alist
, with '\n'
stripped, then joins back into full text (optional if you wish to have only one text):
alist = f.read().splitlines()
jalist = " ".join(alist)
Second option below is much easier and simple produces string of text called atext
replacing '\n'
with space;
atext = f.read().replace('\n',' ')
It works; I have done it. This is clean, easier, and efficient.
Whenever possible, you should avoid parsing the output of ls
(see Greg's wiki on the subject). Basically, the output of ls
will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */
, what happens is that the shell expands */
to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d
, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls
command isn't doing anything useful!
Well, ok, it is doing one thing that's useful: if there are no subdirectories, */
will get left as is, ls
will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).
The cleaner way to make an array of subdirectory names is to use the glob (*/
) without passing it to ls
. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):
shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}" # Note double-quotes to avoid extra parsing of funny characters in filenames
If you want to print an error message if there are no subdirectories, you're better off doing it yourself:
if (( ${#array[@]} == 0 )); then
echo "No subdirectories found" >&2
fi
If you are using this in the Reflection C#, you can get the guid from the property attribute as follows
var propertyAttributes= property.GetCustomAttributes();
foreach(var attribute in propertyAttributes)
{
var myguid= Guid.Parse(attribute.Id.ToString());
}
Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using
System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()
np.isnan
can be applied to NumPy arrays of native dtype (such as np.float64):
In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)
but raises TypeError when applied to object arrays:
In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Since you have Pandas, you could use pd.isnull
instead -- it can accept NumPy arrays of object or native dtypes:
In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)
In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)
Note that None
is also considered a null value in object arrays.
I found this quite frustrating given that my timezone is Australian and that strtotime()
hates UK dates.
If the current day is a Sunday, then strtotime("monday this week")
will return the day after.
To overcome this:
Caution: This is only valid for Australian/UK dates
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything.
You need to declare and initialize the x
and y
members.
Explicitly:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly:
export class Pixel {
constructor(public x: number, public y: number) {}
}
Below is working solution using NgModel
Add variable
public Phone:string;
In html add
<input class="input-width" [(ngModel)]="Phone" (keyup)="keyUpEvent($event)"
type="text" class="form-control" placeholder="Enter Mobile Number">
In Ts file
keyUpEvent(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.keyCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
if(this.Phone.length>0)
{
this.Phone= this.Phone.substr(0,this.Phone.length-1);
}
}
}
The most efficient way is to take input make the logic and run
so the code is like this to make your own space maker
need = input("Write a string:- ")
result = ''
for character in need:
result = result + character + ' '
print(result) # to rid of space after O
but if you want to use what python give then use this code
need2 = input("Write a string:- ")
print(" ".join(need2))
Beamer just delegates responsibility for managing layout of itemize
environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.
Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.
There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.
itemize
In the following code snippet, you can change the value of \itemindent
from 0em
to whatever you please, including negative values. 0em
is the default item indentation.
The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize
and \item
means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.
\begin{itemize}
\setlength{\itemindent}{0em}
\item This is a normally-indented item.
\end{itemize}
list
In the following code snippet, the second parameter to \list
is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin
parameter adjusts the indentation of the entire list item and all of its rows; \itemindent
alters the indentation of subsequent lines.
The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.
\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
\item This item uses the margin and indentation provided above.
\end{list}
customlist
environmentThe shortcomings of the list
solution can be ameliorated by defining a new customlist
environment that basically redefines the itemize
environment from Beamer but also incorporates the \leftmargin
and \itemindent
(etc.) parameters. Put the following in your preamble:
\makeatletter
\newenvironment{customlist}[2]{
\ifnum\@itemdepth >2\relax\@toodeep\else
\advance\@itemdepth\@ne%
\beamer@computepref\@itemdepth%
\usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
\usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
\begin{list}
{
\usebeamertemplate{itemize \beameritemnestingprefix item}
}
{ \leftmargin=#1 \itemindent=#2
\def\makelabel##1{%
{%
\hss\llap{{%
\usebeamerfont*{itemize \beameritemnestingprefix item}%
\usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
}%
}%
}
\fi
}
{
\end{list}
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother
Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin
and the second is for \itemindent
. The default values are 2.5em and 0em respectively.
\begin{customlist}{2.5em}{0em}
\item Any normal item can go here.
\end{customlist}
A custom bullet style can be incorporated into the customlist
solution using the standard Beamer mechanism of \setbeamertemplate
. (See the answers to this question on the TeX Stack Exchange for more information.)
Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item}
with whatever bullet style you'd like to use (e.g. $\square$
).
There is an event Page.Unload
. At that moment page is already rendered in HTML and HTML can't be modified. Still, all page objects are available.
public static void main(String[] args) {
List<String> ls=new ArrayList<String>();
ls.add("1");
ls.add("2");
ls.add("3");
ls.add("4");
//Then you can use "foreache" loop to iterate.
for(String item:ls){
System.out.println(item);
}
}
Use below css to align Label with Checkbox
.chkbox label
{
position: relative;
top: -2px;
}
<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>
I would recommend node-cron
. It allows to run tasks using Cron patterns e.g.
'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)
But also more complex schedules e.g.
'00 30 11 * * 1-5' - Runs every weekday (Monday through Friday) at 11:30:00 AM. It does not run on Saturday or Sunday.
Sample code: running job every 10 minutes:
var cron = require('cron');
var cronJob = cron.job("0 */10 * * * *", function(){
// perform operation e.g. GET request http.get() etc.
console.info('cron job completed');
});
cronJob.start();
You can find more examples in node-cron wiki
More on cron configuration can be found on cron wiki
I've been using that library in many projects and it does the job. I hope that will help.
I had to:
Commands
git rm -f .idea/workspace.xml
git remote | xargs -L1 git push --all
Other committers should run
git pull
Use git rebase
. Specifically:
git stash
to store the changes you want to add.git rebase -i HEAD~10
(or however many commits back you want to see).a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]git stash pop
git add <file>
.git commit --amend --no-edit
.git rebase --continue
which will rewrite the rest of your commits against the new one.[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.