The Chosen plugin does not automatically update its list of options when the OPTION elements in the DOM change. You have to send it an event to trigger the update:
Pre Chosen 1.0:
$('.chzn-select').trigger("liszt:updated");
Chosen 1.0
$('.chosen-select').trigger("chosen:updated");
If you are dynamically managing the OPTION elements, then you'll have to do this whenever the OPTIONs change. The way you do this will vary - in AngularJS, try something like this:
$scope.$watch(
function() {
return element.find('option').map(function() { return this.value }).get().join();
},
function() {
element.trigger('liszt:updated');
}
}
Assuming SQL Server
(based on your previous questions):
ALTER TABLE Merchant_Pending_Functions ALTER COLUMN NumberOfLocations INT NULL
Replace INT
with your actual datatype.
Here are some ways to change Navigation Bar color.
By the XML
1- values-v21/style.xml
<item name="android:navigationBarColor">@color/navigationbar_color</item>
Or if you want to do it only using the values/ folder then-
2- values/style.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<item name="android:navigationBarColor" tools:targetApi="21">@color/navigationbar_color</item>
You can also change navigation bar color By Programming.
if (Build.VERSION.SDK_INT >= 21)
getWindow().setNavigationBarColor(getResources().getColor(R.color.navigationbar_color));
By Using Compat Library-
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}
please find the link for more details- http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)
You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
Here is a more concise version of the accepted answer which avoids repeating the NoteProperty identifiers and the [pscustomobject]
-cast:
$myItems = ("Joe",32,"something about him"), ("Sue",29,"something about her")
| ForEach-Object {[pscustomobject]@{name = $_[0]; age = $_[1]; info = $_[2]}}
Result:
> $myItems
name age info
---- --- ----
Joe 32 something about him
Sue 29 something about her
Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:
long content = 212000607777l;
byte[] numberByte = Longs.toByteArray(content);
logger.info(Longs.fromByteArray(numberByte));
I've made some small modifications to Travis's code (just to avoid any unnecessary redeclaration - but it's working great for my needs, so nice job!):
function linkify(inputText) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.
It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.
You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
The string
class's Replace
method can also be used to remove multiple characters from a string:
Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")
You just need to query the TotalMinutes
property like this varTime.TotalMinutes
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.
Is there any equivalent for the truststore? How can I view the trusted certificates?
Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)
No other difference
People often talk about performance, reads vs. writes, foreign keys, etc. but there's one other must-have feature for a storage engine in my opinion: atomic updates.
Try this:
killall -9 mysqld
to simulate a crash.Performance is desirable of course, but not losing data should trump that.
In this case I believe that the following is equivalent:
l = sum([1,2,3,4]) % 2
The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?
Wrap a div around the image and the span and add the following to CSS like so:
HTML
<li id="CN2787">
<div><img class="fav_star" src="images/fav.png"></div>
<div><span>Text, text and more text</span></div>
</li>
CSS
#CN2787 > div {
display: inline-block;
vertical-align: top;
}
#CN2787 > div:first-of-type {
width: 35%;
}
#CN2787 > div:last-of-type {
width: 65%;
}
LESS
#CN2787 {
> div {
display: inline-block;
vertical-align: top;
}
> div:first-of-type {
width: 35%;
}
> div:last-of-type {
width: 65%;
}
}
I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
Google Gson supports generics and nested beans. The []
in JSON represents an array and should map to a Java collection such as List
or just a plain Java array. The {}
in JSON represents an object and should map to a Java Map
or just some JavaBean class.
You have a JSON object with several properties of which the groups
property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson()
.
This works fine for me . [Ref: the very nice plug in by Gavin G]
(function($){
$.fn.focusTextToEnd = function(){
this.focus();
var $thisVal = this.val();
this.val('').val($thisVal);
return this;
}
}(jQuery));
$('#mytext').focusTextToEnd();
An alternative way:
Here is a working example and here is the code, you should also use prop.
$('input[type="checkbox"]').mouseenter(function() {
if ($(this).is(':checked')) {
//$(this).prop('checked',false);
alert("is checked");
} else {
//$(this).prop('checked',true);
alert("not checked");
}
});?
I commented out the way to toggle the checked attribute.
Increased cohesion and decreased coupling do lead to good software design.
Cohesion partitions your functionality so that it is concise and closest to the data relevant to it, whilst decoupling ensures that the functional implementation is isolated from the rest of the system.
Decoupling allows you to change the implementation without affecting other parts of your software.
Cohesion ensures that the implementation more specific to functionality and at the same time easier to maintain.
The most effective method of decreasing coupling and increasing cohesion is design by interface.
That is major functional objects should only 'know' each other through the interface(s) that they implement. The implementation of an interface introduces cohesion as a natural consequence.
Whilst not realistic in some senarios it should be a design goal to work by.
Example (very sketchy):
public interface IStackoverFlowQuestion
void SetAnswered(IUserProfile user);
void VoteUp(IUserProfile user);
void VoteDown(IUserProfile user);
}
public class NormalQuestion implements IStackoverflowQuestion {
protected Integer vote_ = new Integer(0);
protected IUserProfile user_ = null;
protected IUserProfile answered_ = null;
public void VoteUp(IUserProfile user) {
vote_++;
// code to ... add to user profile
}
public void VoteDown(IUserProfile user) {
decrement and update profile
}
public SetAnswered(IUserProfile answer) {
answered_ = answer
// update u
}
}
public class CommunityWikiQuestion implements IStackoverflowQuestion {
public void VoteUp(IUserProfile user) { // do not update profile }
public void VoteDown(IUserProfile user) { // do not update profile }
public void SetAnswered(IUserProfile user) { // do not update profile }
}
Some where else in your codebase you could have a module that processes questions regardless of what they are:
public class OtherModuleProcessor {
public void Process(List<IStackoverflowQuestion> questions) {
... process each question.
}
}
There is the function in guava libraries:
LongMath.log2()
So I suggest to use it.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.
In the first example the StackTrace will be changed to reflect the current method.
Example:
static string ReadAFile(string fileName) {
string result = string.Empty;
try {
result = File.ReadAllLines(fileName);
} catch(Exception ex) {
throw ex; // This will show ReadAFile in the StackTrace
throw; // This will show ReadAllLines in the StackTrace
}
Just make sure that you have one root div and put everything inside this root
<div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>
and so on
I was able to find my version of Xcode on maxOS Sierra using this command:
pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version
as per this answer.
The question is how to pass argument from child to parent component. This example is easy to use and tested:
//Child component
class Child extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (<div><button onClick={() => handleToUpdate('someVar')}>Push me</button></div>
)
}
}
//Parent component
class Parent extends React.Component {
constructor(props) {
super(props);
var handleToUpdate = this.handleToUpdate.bind(this);
}
handleToUpdate(someArg){
alert('We pass argument from Child to Parent: \n' + someArg);
}
render() {
var handleToUpdate = this.handleToUpdate;
return (<div>
<Child handleToUpdate = {handleToUpdate.bind(this)} />
</div>)
}
}
if(document.querySelector("#demo")){
ReactDOM.render(
<Parent />,
document.querySelector("#demo")
);
}
Concatenation:
The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).
If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.
To avoid entering username, but still be prompted to enter a password, then you can simply clone your repository including the username:
git clone [email protected]/my_repo.git
For me creating a python file named template_filters.py
in my App with below content did the job
# coding=utf-8
from django.template.base import Library
register = Library()
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
usage is like what culebrón said :
{{ mydict|get_item:item.NAME }}
I'd use request for this:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:
var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
var csv = body;
// Continue with your processing here.
}
});
etc.
You can set in the config.inc.php file of your phpMyAdmin installation.
$cfg['Servers'][$i]['host'] = '';
I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).
The easiest solution that I have found is to do the following:
In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.
Example:
'use strict';
//my data variable that I need access to.
var data = null;
angular.module('sample', [])
Then in your controller:
.controller('SampleApp', function ($scope, $location) {
$scope.availableList = [];
$scope.init = function () {
$scope.availableList = data;
}
Finally, you have to init everything (order matters):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="/path/to/your/angular/js/sample.js"></script>
<script type="text/javascript">
data = <?= json_encode($cproducts); ?>
</script>
Finally initialize your controller and init function.
<div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">
By doing this you will now have access to whatever data you stuffed into the global variable.
WHERE p.[Type] = isnull(@SearchType, p.[Type])
To supplement the other answers: If the remote has for some reason been changed and so doesn't reflect the original origin, the very first entry in the reflog (i.e. the last entry displayed by the command git reflog
) should indicate where the repo was originally cloned from.
e.g.
$ git reflog | tail -n 1
f34be46 HEAD@{0}: clone: from https://github.com/git/git
$
(Bear in mind that the reflog may be purged, so this isn't guaranteed to work.)
The Statistic plugin worked for me.
To install it from Intellij:
File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.
Access the 'statistic' toolbar via tabs in bottom left of project
OLDER VERSIONS: Open statistics window from:
View -> Tool Windows -> Statistic
I would answer this with multiple options actually, the some of which actually render in the body.
<input onclick="myfunction()"/>
- better to put it in event handlers in your script body instead.Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).
EDIT: references:
Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; }
on the div)
Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html
EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.
In my eclipse Luna faced the same issue because of this URL https://sourceforge.net/projects/restfulplugin/files/site/
So i just Disabled the URL that was Shown in the Error From the Available Software Sites.
You may Check the URL or Try with the Updated URL reg to that Exception :)
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
Break-down:
8
says that you want to show 8 digits0
that you want to prefix with 0
's instead of just blank spacesx
that you want to print in lower-case hexadecimal.Quick example (thanks to Grijesh Chauhan):
#include <stdio.h>
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf("%0x\n", data); // just print data ('0' on its own has no effect)
printf("%8x\n", data); // print in 8 width and pad with blank spaces
printf("%08x\n", data); // print in 8 width and pad with 0's
return 0;
}
Output:
1d
1d
1d
0000001d
Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.
A character might appear multiple times in a string. For example in a string sentence
, position of e
is 1, 4, 7
(because indexing usually starts from zero). but what I find is both of the functions find()
and index()
returns first position of a character. So, this can be solved doing this:
def charposition(string, char):
pos = [] #list to store positions for each 'char' in 'string'
for n in range(len(string)):
if string[n] == char:
pos.append(n)
return pos
s = "sentence"
print(charposition(s, 'e'))
#Output: [1, 4, 7]
Change the field back to numeric and use ZEROFILL
to keep the zeros
or
use LPAD()
SELECT LPAD('1234567', 8, '0');
$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:
I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.
Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have
if/elses
always look the same (and always be compiled into an expression).So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:
if sunny go_outside() else read_a_book(). if sunny then go_outside() else read_a_book()
Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".
Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802
In case you know the password of that user, or you would like to guess it, do the following:
connect user/password
If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:
alter user NAME_OF_THE_USER identified by OLD_PASSWORD;
and this will reset the password to the same password as before and also reset the account_status for that user.
Mootools also has a nice 'Tips' class available in their 'more builder'.
I'm guessing this is a homework question, so you probably want to go here. It has a tutorial explaining linked lists, gives good pseudocode and also has a C++ implementation you can download.
I'd recommend reading through the explanation and understanding the pseudocode before blindly using the implementation. This is a topic that you really should understand in depth if you want to continue on in CS.
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
Array into table. Array into div. JSON into table. JSON into div.
All are nicely handle this class. Click here to get a class
How to use it?
Just get and object
$obj = new Arrayinto();
Create an array you want to convert
$obj->array_object = array("AAA" => "1111",
"BBB" => "2222",
"CCC" => array("CCC-1" => "123",
"CCC-2" => array("CCC-2222-A" => "CA2",
"CCC-2222=B" => "CB2"
)
)
);
If you want to convert Array into table. Call this.
$result = $obj->process_table();
If you want to convert Array into div. Call this.
$result = $obj->process_div();
Let suppose if you have a JSON
$obj->json_string = '{
"AAA":"11111",
"BBB":"22222",
"CCC":[
{
"CCC-1":"123"
},
{
"CCC-2":"456"
}
]
}
';
You can convert into table/div like this
$result = $obj->process_json('div');
OR
$result = $obj->process_json('table');
A possible solution is:
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myFrame.toFront();
myFrame.repaint();
}
});
Most updated way to achieve this is:
Add this to your EditText in XML:
android:imeOptions="actionSearch"
Then in your Activity/Fragment:
EditText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// Do what you want here
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
Another one answer
static class ImmutableArray<T> {
private final T[] array;
private ImmutableArray(T[] a){
array = Arrays.copyOf(a, a.length);
}
public static <T> ImmutableArray<T> from(T[] a){
return new ImmutableArray<T>(a);
}
public T get(int index){
return array[index];
}
}
{
final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}
Put your JavaScript code after your tag <canvas></canvas>
Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.
For this particular purpose one can introduce a composite key like this:
CREATE TABLE IF NOT EXISTS `test`.`user` (
`username` VARCHAR(45) NOT NULL,
`firstname` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`username`, `firstname`))
Mapping:
@Embeddable
public class UserKey implements Serializable {
protected String username;
protected String firstname;
public UserKey() {}
public UserKey(String username, String firstname) {
this.username = username;
this.firstname = firstname;
}
// equals, hashCode
}
Here is how to use it:
@Entity
public class UserEntity implements Serializable {
@EmbeddedId
private UserKey primaryKey;
private String description;
//...
}
JpaRepository would look like this:
public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>
Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.
Assuming you have a button/link inside of a data cell in your table, something like this would do the trick...
$(".delete").live('click', function(event) {
$(this).parent().parent().remove();
});
This will remove the parent of the parent of the button/link that is clicked. You need to use parent() because it is a jQuery object, not a normal DOM object, and you need to use parent() twice, because the button lives inside a data cell, which lives inside a row....which is what you want to remove. $(this) is the button clicked, so simply having something like this will remove only the button:
$(this).remove();
While this will remove the data cell:
$(this).parent().remove();
If you want to simply click anywhere on the row to remove it something like this would work. You could easily modify this to prompt the user or work only on a double-click:
$(".delete").live('click', function(event) {
$(this).parent().remove();
});
Hope that helps...I struggled on this a bit myself.
Try adding this line to your script. This worked for me!
$mail->Mailer = “smtp”;
These are class stereotypes used in analysis.
boundary classes are ones at the boundary of the system - the classes that you or other systems interact with
entity classes classes are your typical business entities like "person" and "bank account"
control classes implement some business logic or other
Here u Go
f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)
In my case (IntelliJ), I needed to check if I had the right Runner for maven:
If you're using jackson, better to convert directly to ObjectNode.
//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();
//pass it your payload
public static ObjectNode convObjToONode(Object o) {
StringWriter stringify = new StringWriter();
ObjectNode objToONode = null;
try {
mapper.writeValue(stringify, o);
objToONode = (ObjectNode) mapper.readTree(stringify.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(objToONode);
return objToONode;
}
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'name_of_your_table'
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
It works for me in all the browsers:
document.onkeydown = function(){
switch (event.keyCode){
case 116 : //F5 button
event.returnValue = false;
event.keyCode = 0;
return false;
case 82 : //R button
if (event.ctrlKey){
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
}
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
The problem here seems to be that you're reassigning $today
by assigning a string to it:
$today = $dd+'/'+$mm+'/'+$yyyy;
Strings don't have getDate
.
Also, $today.getDate()-1
just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.
Then just apply the formatting code you wrote:
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;
Because of the last statement, $yesterday
is now a String
(not a Date
) containing the formatted date.
In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:
template <class IntegerType>
class smart_integer {
public:
typedef integer_traits<Integer> traits;
IntegerType operator+=(IntegerType value){
typedef typename traits::larger_integer_t larger_t;
larger_t interm = larger_t(myValue) + larger_t(value);
if(interm > traits::max() || interm < traits::min())
throw overflow();
myValue = IntegerType(interm);
}
}
larger_integer_t
is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t
is a type. class, on the otherhand, has no such overloaded meaning.
That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaThis is easily done by replacing the frame's content pane with a JPanel which draws your image:
try {
final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
setContentPane(new JPanel(new BorderLayout()) {
@Override public void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
This example also sets the panel's layout to BorderLayout to match the default content pane layout.
(If you have any trouble seeing the image, you might need to call setOpaque(false)
on some other components so that you can see through to the background.)
Late reply, but adding that Mongoose also has the concept of Subdocuments
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
you need to prevent the default behavior of your form when submitting
by adding this:
$("#postcontent").on('submit' , function(e) {
e.preventDefault();
//then the rest of your code
}
SELECT cols
FROM table
WHERE cols IS NULL
If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.
Or, in one command: git checkout -b newBranch
As mentioned in the git reset
man page:
$ git branch topic/wip # (1)
$ git reset --hard HEAD~3 # (2) NOTE: use $git reset --soft HEAD~3 (explanation below)
$ git checkout topic/wip # (3)
master
" branch. You want to continue polishing them in a topic branch, so create "topic/wip
" branch off of the current HEAD
.master
branch to get rid of those three commits.topic/wip
" branch and keep working.Note: due to the "destructive" effect of a git reset --hard
command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit>
are discarded), I would rather go with:
$ git reset --soft HEAD~3 # (2)
This would make sure I'm not losing any private file (not added to the index).
The --soft
option won't touch the index file nor the working tree at all (but resets the head to <commit>
, just like all modes do).
With Git 2.23+, the new command git switch
would create the branch in one line (with the same kind of reset --hard
, so beware of its effect):
git switch -f -c topic/wip HEAD~3
To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// get the applications dir path and expose it to QML
QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);
// Get the QStandardPaths home location and expose it to QML
QUrl userPath;
const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (usersLocation.isEmpty())
userPath = appPath.resolved(QUrl("/home/"));
else
userPath = QString("%1").arg(usersLocation.first());
engine.rootContext()->setContextProperty("userPath", userPath);
QUrl imagePath;
const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
if (picturesLocation.isEmpty())
imagePath = appPath.resolved(QUrl("images"));
else
imagePath = QString("%1").arg(picturesLocation.first());
engine.rootContext()->setContextProperty("imagePath", imagePath);
QUrl videoPath;
const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
if (moviesLocation.isEmpty())
videoPath = appPath.resolved(QUrl("./"));
else
videoPath = QString("%1").arg(moviesLocation.first());
engine.rootContext()->setContextProperty("videoPath", videoPath);
QUrl homePath;
const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (homesLocation.isEmpty())
homePath = appPath.resolved(QUrl("/"));
else
homePath = QString("%1").arg(homesLocation.first());
engine.rootContext()->setContextProperty("homePath", homePath);
QUrl desktopPath;
const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
if (desktopsLocation.isEmpty())
desktopPath = appPath.resolved(QUrl("/"));
else
desktopPath = QString("%1").arg(desktopsLocation.first());
engine.rootContext()->setContextProperty("desktopPath", desktopPath);
QUrl docPath;
const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
if (docsLocation.isEmpty())
docPath = appPath.resolved(QUrl("/"));
else
docPath = QString("%1").arg(docsLocation.first());
engine.rootContext()->setContextProperty("docPath", docPath);
QUrl tempPath;
const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
if (tempsLocation.isEmpty())
tempPath = appPath.resolved(QUrl("/"));
else
tempPath = QString("%1").arg(tempsLocation.first());
engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Using it in QML
....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}
Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust
Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.
You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings
Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.
Click Ok Come back to anaconda terminal and you can try install commands
Here is an example of how to overwrite Logger configuration from the code. Does not require external configuration file ..
FileLoggerTest.java:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class FileLoggerTest {
public static void main(String[] args) {
try {
String h = MyLogHandler.class.getCanonicalName();
StringBuilder sb = new StringBuilder();
sb.append(".level=ALL\n");
sb.append("handlers=").append(h).append('\n');
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
} catch (IOException | SecurityException ex) {
// Do something about it
}
Logger.getGlobal().severe("Global SEVERE log entry");
Logger.getLogger(FileLoggerTest.class.getName()).log(Level.SEVERE, "This is a SEVERE log entry");
Logger.getLogger("SomeName").log(Level.WARNING, "This is a WARNING log entry");
Logger.getLogger("AnotherName").log(Level.INFO, "This is an INFO log entry");
Logger.getLogger("SameName").log(Level.CONFIG, "This is an CONFIG log entry");
Logger.getLogger("SameName").log(Level.FINE, "This is an FINE log entry");
Logger.getLogger("SameName").log(Level.FINEST, "This is an FINEST log entry");
Logger.getLogger("SameName").log(Level.FINER, "This is an FINER log entry");
Logger.getLogger("SameName").log(Level.ALL, "This is an ALL log entry");
}
}
MyLogHandler.java
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
public final class MyLogHandler extends FileHandler {
public MyLogHandler() throws IOException, SecurityException {
super("/tmp/path-to-log.log");
setFormatter(new SimpleFormatter());
setLevel(Level.ALL);
}
@Override
public void publish(LogRecord record) {
System.out.println("Some additional logic");
super.publish(record);
}
}
yes you can, just set the NODE_PATH env variable :
export NODE_PATH='yourdir'/node_modules
According to the doc :
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)
Additionally, node will search in the following locations:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.
These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.
You can do that using CSS's background
propieties. There are few ways to do it:
HTML:
<div id="div-with-bg"></div>
CSS:
#div-with-bg
{
background: color url('path') others;
}
HTML:
<div class="div-with-bg"></div>
CSS:
.div-with-bg
{
background: color url('path') others;
}
HTML:
<div style="background: color url('path')"></div>
Where:
background
CSS Property is a connection of all background-xxx propieties in that syntax:
background: background-color background-image background-repeat background-attachment background-position;
Source: w3schools
if you do not want to delete all NaN, use
df[~df.C.str.contains("XYZ") == True]
I used a slightly modified version:
with open(file_name, 'w', encoding = 'utf-8') as f:
for rec_index, rec in df.iterrows():
f.write(rec['<field>'] + '\n')
I had to write the contents of a dataframe field (that was delimited) as a text file.
If you are trying to do redirect in beforeAction() you should use send() method
return $this->redirect('/some/url',302)->send();
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
To time task in CMD is as simple as
echo %TIME% && your_command && cmd /v:on /c echo !TIME!
I have used a syntax like this before:
$(ProjectDir)..\headers
or
..\headers
As other have pointed out, the starting directory is the one your project file is in(vcproj
or vcxproj
), not where your main code is located.
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
Please refer "Date and Time Patterns" here. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class DateConversionExample{
public static void main(String arg[]){
try{
SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");
SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetDateFormat.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
Why all the other answers use slideUp
is just beyond me. As I'm using the fade
and in
classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.
Besides the slideUp
method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:
$(document).ready(function() {
// show the alert
setTimeout(function() {
$(".alert").alert('close');
}, 2000);
});
It is most efficient to do your aggregation by integer and then convert back to datetime for presentation.
select
cast(daybucket - 1 as datetime) as count_date,
counted_leads
from
(select
cast(created_date as int) as DayBucket,
count(*) as counted_leads
from mytable
group by cast(created_date as int) ) as countByDay
Check if you don't have a ScrollView wrapping your Webview.
In my case that was the problem. It seems ScrollView gets in the way of the pinch gesture.
To fix it, just take your Webview outside the ScrollView.
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
In addition to the other answers here showing you how to git checkout <the-hash-you-want>
it's worth knowing you can switch back to where you were using:
git checkout @{-1}
This is often more convenient than:
git checkout what-was-that-original-branch-called-again-question-mark
As you might anticipate, git checkout @{-2}
will take you back to the branch you were at two git checkout
s ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.
Sadly for productivity, git checkout @{1}
does not take you to the branch you will be on in future, which is a shame.
Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.
The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.
select_related
performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.
Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related
to relations that won't unexpectedly result in a massive join.
The "join in python" for prefetch_related
is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:
SELECT "credential"."id",
"credential"."uuid",
"credential"."identity_id"
FROM "credential"
WHERE "credential"."identity_id" IN
(84706, 48746, 871441, 84713, 76492, 84621, 51472);
Rather than performing a single join with potentially too many rows, each table is split into a separate query.
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
This code works!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title></title>
<script>
function addRow() {
$('.displaynone').show();
$('.displaynone td')
.wrapInner('<div class="innerDiv" style="height:0" />');
$('div').animate({"height":"20px"});
}
</script>
<style>
.mycolumn{border: 1px solid black;}
.displaynone{display: none;}
</style>
</head>
<body>
<table align="center" width="50%">
<tr>
<td class="mycolumn">Row 1</td>
</tr>
<tr>
<td class="mycolumn">Row 2</td>
</tr>
<tr class="displaynone">
<td class="mycolumn">Row 3</td>
</tr>
<tr>
<td class="mycolumn">Row 4</td>
</tr>
</table>
<br>
<button onclick="addRow();">add</button>
</body>
</html>
If this error occurs when you want to use a classvariable in a new form, you should put the class definition in the
Formname.Designer.cs
instead of the Formname.cs file.
make sure you have these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then make some activity and register a LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.
I used (num-0.05).toFixed(1)
to get the second decimal floored.
Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.
In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.
To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:
SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)
If you are using Mongoose,
try {
const data = await GPSDatas.aggregate([
{
$match: { createdAt : { $gt: new Date() }
},
{
$sort: { createdAt: 1 }
}
])
console.log(data)
} catch(error) {
console.log(error)
}
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
I was face same problem when I am going to delete my record than some issue was occur , for this issue solution is that when you are going to delete your record than you missing some thing before deleting header/master record you must write to code for delete its detail before header/Master I hope you issue will be resolve.
I wanted to achieve the same goal as you, so I wrote the following method which does exactly that if you pass it an ImageView and a list of references to image drawables.
ImageView demoImage = (ImageView) findViewById(R.id.DemoImage);
int imagesToShow[] = { R.drawable.image1, R.drawable.image2,R.drawable.image3 };
animate(demoImage, imagesToShow, 0,false);
private void animate(final ImageView imageView, final int images[], final int imageIndex, final boolean forever) {
//imageView <-- The View which displays the images
//images[] <-- Holds R references to the images to display
//imageIndex <-- index of the first image to show in images[]
//forever <-- If equals true then after the last image it starts all over again with the first image resulting in an infinite loop. You have been warned.
int fadeInDuration = 500; // Configure time values here
int timeBetween = 3000;
int fadeOutDuration = 1000;
imageView.setVisibility(View.INVISIBLE); //Visible or invisible by default - this will apply when the animation ends
imageView.setImageResource(images[imageIndex]);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
fadeIn.setDuration(fadeInDuration);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
fadeOut.setStartOffset(fadeInDuration + timeBetween);
fadeOut.setDuration(fadeOutDuration);
AnimationSet animation = new AnimationSet(false); // change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
animation.setRepeatCount(1);
imageView.setAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(Animation animation) {
if (images.length - 1 > imageIndex) {
animate(imageView, images, imageIndex + 1,forever); //Calls itself until it gets to the end of the array
}
else {
if (forever){
animate(imageView, images, 0,forever); //Calls itself to start the animation all over again in a loop if forever = true
}
}
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
});
}
You can try to clone using the HTTPS
protocol. Terminal command:
git clone https://github.com/RestKit/RestKit.git
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office
combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
in your tsconfig you have to add: "esModuleInterop": true - it should help.
Create a stored procedure that does something like the following:
declare @startDate date;
declare @endDate date;
select @startDate = '20150528';
select @endDate = '20150531';
with dateRange as
(
select dt = dateadd(dd, 1, @startDate)
where dateadd(dd, 1, @startDate) < @endDate
union all
select dateadd(dd, 1, dt)
from dateRange
where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange
Or better still create a calendar table and just select from that.
Comment by @Niagaradad helped me. I was entering the wrong password the whole time.
Notice the error message
ERROR 1045 (28000): Access denied for user 'ayaz'@'localhost' (using password: YES)
It says, Password: Yes. That means I am sending the password to SQL and that is wrong.
Usually root account doesn't have password if you haven't set one. If you have installed mysql via homebrew then root account won't have a password.
Here is the comment.
so, not exactly the same then. NO means you are not sending a password to MySQL. YES means you are sending a password to MySQL but the incorrect one. Did you specifically set a password for the mysql root user when you installed MySQL? By default there is no password so you can use mysql -u root -p and hit enter.
A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.
<?php
final class MyParentClass
{
/**
* @return MyStruct[]
*/
public function getData(): array
{
return array(
$this->createMyObject("One", 1.0, new DateTime("now")),
$this->createMyObject("Two", 2.0, new DateTime("tommorow"))
);
}
private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
{
return new class(func_get_args()) extends MyStruct {
protected function __construct(array $args)
{
$this->description = $args[0];
$this->magnitude = $args[1];
$this->timeStamp = $args[2];
}
};
}
}
abstract class MyStruct
{
public string $description;
public float $magnitude;
public DateTime $timeStamp;
}
I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }
Ahem u_u
As i've stated the back button is for every one of us a pain in some place... that said...
As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this
The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.
But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.
It might help if you say what your preferred logger is exactly, and what you did to try and install it. Anyway, Spring Boot tries to work with whatever is in the classpath, so if you don't want logback, take it off the classpath. There are instructions for log4j in the docs, but the same thing would apply to other supported logging systems (anything slf4j, log4j or java util).
And make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
Examples:
class Dog
{
public:
barkAt( const std::string& pOtherDog ); // const reference
barkAt( std::string pOtherDog ); // value
};
const &
is generally best. You don't incur the construction and destruction penalty. If the reference isn't const your interface is suggesting that it will change the passed in data.
Another simple alternative:
<input ng-model="edItem" type="text"
ng-keypress="($event.which === 13)?foo(edItem):0"/>
And the ng-ui alternative:
<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
Beautiful soup does convert html entities. It's probably your best bet considering HTML is often buggy and filled with unicode and html encoding issues. This is the code I use to convert html to raw text:
import BeautifulSoup
def getsoup(data, to_unicode=False):
data = data.replace(" ", " ")
# Fixes for bad markup I've seen in the wild. Remove if not applicable.
masssage_bad_comments = [
(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1)),
(re.compile('<!WWWAnswer T[=\w\d\s]*>'), lambda match: '<!--' + match.group(0) + '-->'),
]
myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(masssage_bad_comments)
return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage,
convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES
if to_unicode else None)
remove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else ""
You could use a CURSOR in this case:
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
FETCH NEXT
FROM @getid INTO @id, @name
END
CLOSE @getid
DEALLOCATE @getid
Modified to show multiple parameters from the table.
Using function Find is cleaner way.
MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
....
}
Note that as of Angular 1.4, you can serialize the form data without using jQuery.
In the app.js:
module.run(function($http, $httpParamSerializerJQLike) {
$http.defaults.transformRequest.unshift($httpParamSerializerJQLike);
});
Then in your controller:
$http({
method: 'POST',
url: myUrl',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: myData
});
Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.
The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
WHERE a.x = b.x(+)
Or
WHERE a.x *= b.x
Or
WHERE a.x = b.x or a.x not in (select x from b)
var content = new JsonContent();
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("charset", "utf-8"));
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("IEEE754Compatible", "true"));
It's all what you need.
With using Newtonsoft.Json, if you need a content as json string.
public class JsonContent : HttpContent
{
private readonly MemoryStream _stream = new MemoryStream();
~JsonContent()
{
_stream.Dispose();
}
public JsonContent(object value)
{
Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (var contexStream = new MemoryStream())
using (var jw = new JsonTextWriter(new StreamWriter(contexStream)) { Formatting = Formatting.Indented })
{
var serializer = new JsonSerializer();
serializer.Serialize(jw, value);
jw.Flush();
contexStream.Position = 0;
contexStream.WriteTo(_stream);
}
_stream.Position = 0;
}
private JsonContent(string content)
{
Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (var contexStream = new MemoryStream())
using (var sw = new StreamWriter(contexStream))
{
sw.Write(content);
sw.Flush();
contexStream.Position = 0;
contexStream.WriteTo(_stream);
}
_stream.Position = 0;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
length = _stream.Length;
return true;
}
public static HttpContent FromFile(string filepath)
{
var content = File.ReadAllText(filepath);
return new JsonContent(content);
}
public string ToJsonString()
{
return Encoding.ASCII.GetString(_stream.GetBuffer(), 0, _stream.GetBuffer().Length).Trim();
}
}
I've used this function to merge objects in the past, I use it to add or update existing properties on obj1
with values from obj2
:
var _mergeRecursive = function(obj1, obj2) {
//iterate over all the properties in the object which is being consumed
for (var p in obj2) {
// Property in destination object set; update its value.
if ( obj2.hasOwnProperty(p) && typeof obj1[p] !== "undefined" ) {
_mergeRecursive(obj1[p], obj2[p]);
} else {
//We don't have that level in the heirarchy so add it
obj1[p] = obj2[p];
}
}
}
It will handle multiple levels of hierarchy as well as single level objects. I used it as part of a utility library for manipulating JSON objects. You can find it here.
The answers above did not work for me because in my project, the ngIf is on an input element. I needed access to the nativeElement attribute in order to focus on the input when ngIf is true. There seems to be no nativeElement attribute on ViewContainerRef. Here is what I did (following @ViewChild documentation):
<button (click)='showAsset()'>Add Asset</button>
<div *ngIf='showAssetInput'>
<input #assetInput />
</div>
...
private assetInputElRef:ElementRef;
@ViewChild('assetInput') set assetInput(elRef: ElementRef) {
this.assetInputElRef = elRef;
}
...
showAsset() {
this.showAssetInput = true;
setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });
}
I used setTimeout before focusing because the ViewChild takes a sec to be assigned. Otherwise it would be undefined.
$> mysql -u root -p -e 'Select user from mysql.user' > allUsersOnDatabase.txt
Executing this command on linux prompt will first ask for the password of mysql root user, on providing correct password it will print all the database users to the text file.
I know this has already been answered, but just for the sake of a purely pandas solution to this specific question as opposed to the general description from Aman (which was wonderful) and in case anyone else happens upon this:
import pandas as pd
df = df[pd.notnull(df['EPS'])]
Why not...
bool isEmpty = !list.Any();
if(isEmpty)
{
// error message
}
else
{
// show grid
}
The GridView
has also an EmptyDataTemplate
which is shown if the datasource is empty. This is an approach in ASP.NET:
<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataErrorImg"
imageurl="~/images/NoDataError.jpg" runat="server"/>
No Data Found!
</emptydatatemplate>
$ find proj
proj
proj/src
proj/src/index.js
$ cat proj/src/index.js
console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);
$ cd proj; node src/index.js
process.cwd() = /tmp/proj
__dirname = /tmp/proj/src
I am going to add another answer here, because I have come up with a different approach to my previous one, and that is to use locale facets.
The basics are here
Essentially what you do is:
std::locale::facet
. The slight downside is that you will need a compilation unit somewhere to hold its id. Let's call it MyPrettyVectorPrinter. You'd probably give it a better name, and also create ones for pair and map.std::has_facet< MyPrettyVectorPrinter >
std::use_facet< MyPrettyVectorPrinter >( os.getloc() )
operator<<
) provides default ones. Note you can do the same thing for reading a vector.I like this method because you can use a default print whilst still being able to use a custom override.
The downsides are needing a library for your facet if used in multiple projects (so can't just be headers-only) and also the fact that you need to beware about the expense of creating a new locale object.
I have written this as a new solution rather than modify my other one because I believe both approaches can be correct and you take your pick.
Lots of ways to do this. The most reliable is find.
Dim rLastCell As Range
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
MsgBox ("The last used column is: " & rLastCell.Column)
If you want to find the last column used in a particular row you can use:
Dim lColumn As Long
lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Using used range (less reliable):
Dim lColumn As Long
lColumn = ws.UsedRange.Columns.Count
Using used range wont work if you have no data in column A. See here for another issue with used range:
See Here regarding resetting used range.
$ git clone --no-hardlinks /path/to/repo
The above command uses POSIX path notation for the directory with your git repository. For Windows it is (directory C:/path/to/repo
contains .git
directory):
C:\some\dir\> git clone --local file:///C:/path/to/repo my_project
The repository will be clone to C:\some\dir\my_project
. If you omit file:///
part then --local
option is implied.
https://github.com/angular/angular-cli#updating-angular-cli
If you're using Angular CLI 1.0.0-beta.28 or less, you need to uninstall angular-cli package first.
npm uninstall -g angular-cli
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Then when it gets done successfully you may try:
ng --version
I agree with bizl
[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }
also if you need to apply this included class to an object item you can do like that
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
Sometimes I use an attribute of a function for caching already computed values. You can also have a generic decorator that generalizes this approach. Be aware of concurrency issues and side effects of such functions!
At the Menu > Visual Studio (mac) > Preferences > Publishing > Apple Developer Accounts > [Select your apple id] > View Details > Create Certificate
To delete unused/invalid certificates, go to website: https://developer.apple.com/account/resources/certificates/list
delete any unwanted certificate there
Next is to create App ID (identifiers), go to website:
https://developer.apple.com/account/resources/identifiers/list
Next, go to website to create provisioning profiles:
https://developer.apple.com/account/resources/profiles/add
use the certificate to bind with your app id.
Next is to download the profiles:
At your mac > At the Menu > Visual Studio (mac) > Preferences > Publishing > Apple Developer Accounts > [Select your apple id] > View Details > Download All Profiles
I got it too, for me the problem got resolved after deleting the m2 folder (C:\Users\username.m2) and updating the maven project.
Look into python wheels to solve your problem. The best part of python wheels is that they let you install C extensions with no compilers. I just installed numpy and scipy using pip in a clean python install and they both worked fine.
From the GNU Make documentation,
5.3.1 Choosing the Shell
------------------------
The program used as the shell is taken from the variable `SHELL'. If
this variable is not set in your makefile, the program `/bin/sh' is
used as the shell.
So put SHELL := /bin/bash
at the top of your makefile, and you should be good to go.
BTW: You can also do this for one target, at least for GNU Make. Each target can have its own variable assignments, like this:
all: a b
a:
@echo "a is $$0"
b: SHELL:=/bin/bash # HERE: this is setting the shell for b only
b:
@echo "b is $$0"
That'll print:
a is /bin/sh
b is /bin/bash
See "Target-specific Variable Values" in the documentation for more details. That line can go anywhere in the Makefile, it doesn't have to be immediately before the target.
write your self a filter function
public List<T> filter(Predicate<T> criteria, List<T> list) {
return list.stream().filter(criteria).collect(Collectors.<T>toList());
}
And then use
list = new Test().filter(x -> x > 2, list);
This is the most neat version in Java, but needs JDK 1.8 to support lambda calculus
JAVA HOME
is used for setting up the environment variable for JAVA. It means that you are providing a path for compiling a JAVA program and also running the same. So, if you do not set the JAVA HOME( PATH ) and try to run a java or any dependent program in the command prompt.
You will deal with an error as
javac : not recognized as internal or external command
.
Now to set this, Just open your Java jdk then open bin folder then copy the PATH of that bin folder.
Now, go to My computer right click on it----> select properties-----> select Advanced system settings----->Click on Environment Variables------>select New----->give a name in the text box Variable Name and then paste the path in Value.
That's All!!
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
You need to use setInterval
to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
(throws IOException)
Image image = null;
try {
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
image = ImageIO.read(url);
} catch (IOException e) {
}
See javax.imageio
package for more info. That's using the AWT image. Otherwise you could do:
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
And you may then want to save the image so do:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
You can use StringUtils’s TraditionalBinarPrefix
:
public static String humanReadableInt(long number) {
return TraditionalBinaryPrefix.long2String(number, ””, 1);
}
Since pandas
has to find this out for DataFrame.dropna()
, I took a look to see how they implement it and discovered that they made use of DataFrame.count()
, which counts all non-null values in the DataFrame
. Cf. pandas source code. I haven't benchmarked this technique, but I figure the authors of the library are likely to have made a wise choice for how to do it.
Check this out: http://www.tamirgal.com/home/dev.aspx?Item=sharpSsh
SharpSSH is a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and can be integrated into any .NET application.
The library is a C# port of the JSch project from JCraft Inc. and is released under BSD style license.
SharpSSH allows you to read/write data and transfer files over SSH channels using an API similar to JSch's API. In addition, it provides some additional wrapper classes which offer even simpler abstraction for SSH communication.
SharpSSH project page at source forge: http://sourceforge.net/projects/sharpssh
Another approach to sort HTML table. (based on W3.JS HTML Sort)
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
element.addEventListener("click", function() {_x000D_
w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
});_x000D_
});
_x000D_
th {_x000D_
cursor: pointer;_x000D_
background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
<!-- _x000D_
<tr>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
</tr> _x000D_
-->_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Address</th>_x000D_
<th>Sales Person</th>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>user:2911002</td>_x000D_
<td>UK</td>_x000D_
<td>Melissa</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2201002</td>_x000D_
<td>France</td>_x000D_
<td>Justin</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901092</td>_x000D_
<td>San Francisco</td>_x000D_
<td>Judy</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2801002</td>_x000D_
<td>Canada</td>_x000D_
<td>Skipper</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901009</td>_x000D_
<td>Christchurch</td>_x000D_
<td>Alex</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
If it is a Maven project then sometimes re-importing of it helps:
Hope it will resolve the issue.
It's even simpler than that. Just did this (on Windows, but it should work on other OS):
Git just sees you added a directory and renamed a bunch of files. No biggie.
Sending multiple file for file we have to use enctype="multipart/form-data"
and to send multiple file use multiple="multiple"
in input tag
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileattachments" multiple="multiple"/>
<input type="submit" />
</form>
When doing a clean HTML Structure, you can use this.
//Jquery Code_x000D_
$('a#link_1').click(function(e){_x000D_
e . preventDefault () ;_x000D_
var a = e . target ;_x000D_
window . open ( '_top' , a . getAttribute ('href') ) ;_x000D_
});_x000D_
_x000D_
//Normal Code_x000D_
element = document . getElementById ( 'link_1' ) ;_x000D_
element . onClick = function (e) {_x000D_
e . preventDefault () ;_x000D_
_x000D_
window . open ( '_top' , element . getAttribute ('href') ) ;_x000D_
} ;
_x000D_
<a href="#Foo" id="link_1">Do it!</a>
_x000D_
I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX
You can find complete project here: github-link
MainActivity.kt
class MainActivity : AppCompatActivity() {
val position = LatLng(-33.920455, 18.466941)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(mapView) {
// Initialise the MapView
onCreate(null)
// Set the map ready callback to receive the GoogleMap object
getMapAsync{
MapsInitializer.initialize(applicationContext)
setMapLocation(it)
}
}
}
private fun setMapLocation(map : GoogleMap) {
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
addMarker(MarkerOptions().position(position))
mapType = GoogleMap.MAP_TYPE_NORMAL
setOnMapClickListener {
Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API_KEY_HERE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/mapView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
For the simple reason:
Andy-B-MacBook:~ l.admin$ brew install sshpass
Error: No available formula with the name "sshpass"
We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security.
Thus, the answer to do the curl / configure / install worked great for me on Mac.
The compiler replaces null comparisons with a call to HasValue
, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
An alternative to measure-time is simply "Get-Date". You don't have that hassle with forwarding output and so on.
$start = Get-Date
[System.Threading.Thread]::Sleep(1500)
$(Get-Date) - $start
Output:
Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 506
Ticks : 15060003
TotalDays : 1.74305590277778E-05
TotalHours : 0.000418333416666667
TotalMinutes : 0.025100005
TotalSeconds : 1.5060003
TotalMilliseconds : 1506.0003
As RAND
produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND
to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
import pyaudio
import wave
from array import array
FORMAT=pyaudio.paInt16
CHANNELS=2
RATE=44100
CHUNK=1024
RECORD_SECONDS=15
FILE_NAME="RECORDING.wav"
audio=pyaudio.PyAudio() #instantiate the pyaudio
#recording prerequisites
stream=audio.open(format=FORMAT,channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
#starting recording
frames=[]
for i in range(0,int(RATE/CHUNK*RECORD_SECONDS)):
data=stream.read(CHUNK)
data_chunk=array('h',data)
vol=max(data_chunk)
if(vol>=500):
print("something said")
frames.append(data)
else:
print("nothing")
print("\n")
#end of recording
stream.stop_stream()
stream.close()
audio.terminate()
#writing to file
wavfile=wave.open(FILE_NAME,'wb')
wavfile.setnchannels(CHANNELS)
wavfile.setsampwidth(audio.get_sample_size(FORMAT))
wavfile.setframerate(RATE)
wavfile.writeframes(b''.join(frames))#append frames recorded to file
wavfile.close()
I think this will help.It is a simple script which will check if there is a silence or not.If silence is detected it will not record otherwise it will record.
here is one more way to do this if you want to delete a element by finding this with its value in vector,you just need to do this on vector.
vector<int> ar(n);
ar.erase(remove(ar.begin(), ar.end()), (place your value here from vector array));
it will remove your value from here. thanks
Another way to do this would be to add this line to the assembly info of the web application:
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Similar to Shriek's.
Not with pure HTML as far as I know.
But with JS or PHP or another scripting language such as JSP, you can do it very easily with a for loop.
Example in PHP:
<select>
<?php
for ($i=1; $i<=100; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
The simple and best way to delete all files from a folder in PHP
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/
You can do this easier.
Source: http://www.tutorialspoint.com/android/android_loading_spinner.htm
It helped me.
Layout:
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below:
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below:
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
This script works on Windows, and should work on other OSes : It works on Windows, Debian, and macosx, need a test on solaris.
import os
import platform
def isUp(hostname):
giveFeedback = False
if platform.system() == "Windows":
response = os.system("ping "+hostname+" -n 1")
else:
response = os.system("ping -c 1 " + hostname)
isUpBool = False
if response == 0:
if giveFeedback:
print hostname, 'is up!'
isUpBool = True
else:
if giveFeedback:
print hostname, 'is down!'
return isUpBool
print(isUp("example.com")) #Example domain
print(isUp("localhost")) #Your computer
print(isUp("invalid.example.com")) #Unresolvable hostname: https://tools.ietf.org/html/rfc6761
print(isUp("192.168.1.1")) #Pings local router
print(isUp("192.168.1.135")) #Pings a local computer - will differ for your network
What I do is:
array="$(echo $array | tr ' ' '\n' | sed "/itemtodelete/d")"
BAM, that item is removed.
I used !important
after the border-collapse like
border-collapse: collapse !important;
and it works for me in IE7. It seems to override the cellspacing attribute.
You can use line-height
for that. Just set it up to the exact height of your p
tag.
p.event_desc {
line-height:35px;
}
look also hier:
NET START | FIND "Service name" > nul IF errorlevel 1 ECHO The service is not running
just copied from: http://ss64.com/nt/sc.html
Maybe the following helps you.
arraylistname.get(position);
The 'ours' in Git is referring to the original working branch which has authoritative/canonical part of git history.
The 'theirs' refers to the version that holds the work in order to be rebased (changes to be replayed onto the current branch).
This may appear to be swapped to people who are not aware that doing rebasing (e.g. git rebase
) is actually taking your work on hold (which is theirs) in order to replay onto the canonical/main history which is ours, because we're rebasing our changes as third-party work.
The documentation for git-checkout
was further clarified in Git >=2.5.1 as per f303016
commit:
--ours
--theirs
When checking out paths from the index, check out stage #2 ('ours') or #3 ('theirs') for unmerged paths.
Note that during
git rebase
andgit pull --rebase
, 'ours' and 'theirs' may appear swapped;--ours
gives the version from the branch the changes are rebased onto, while--theirs
gives the version from the branch that holds your work that is being rebased.This is because
rebase
is used in a workflow that treats the history at the remote as the shared canonical one, and treats the work done on the branch you are rebasing as the third-party work to be integrated, and you are temporarily assuming the role of the keeper of the canonical history during the rebase. As the keeper of the canonical history, you need to view the history from the remote asours
(i.e. "our shared canonical history"), while what you did on your side branch astheirs
(i.e. "one contributor's work on top of it").
For git-merge
it's explain in the following way:
ours
This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
This should not be confused with the ours merge strategy, which does not even look at what the other tree contains at all. It discards everything the other tree did, declaring our history contains all that happened in it.
theirs
This is the opposite of ours.
Further more, here is explained how to use them:
The merge mechanism (
git merge
andgit pull
commands) allows the backend merge strategies to be chosen with-s
option. Some strategies can also take their own options, which can be passed by giving-X<option>
arguments togit merge
and/orgit pull
.
So sometimes it can be confusing, for example:
git pull origin master
where -Xours
is our local, -Xtheirs
is theirs (remote) branchgit pull origin master -r
where -Xours
is theirs (remote), -Xtheirs
is oursSo the 2nd example is opposite to the 1st one, because we're rebasing our branch on top of the remote one, so our starting point is remote one, and our changes are treated as external.
Similar for git merge
strategies (-X ours
and -X theirs
).
If I understand correctly you want then
of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.
Updated code would look something like this:
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
return new Promise(function(resolve, reject) {
axios(config).then(
function (response) {
resolve(response.data)
}
).catch(
function (error) {
console.log('Show error notification!')
}
)
});
}
Windows uses a different epoch and time units: see Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
One detail hasn't been noted yet: modern desktop browsers consider different button presses to be "clicks" for AddEventListener('click'
and onclick
by default.
onclick
and AddEventListener
click fire on left and middle click.onclick
fires only on left click, but AddEventListener
click fires on left, middle and right clicks.Also, middle-click behavior is very inconsistent across browsers when scroll cursors are involved:
It is also worth noting that "click" events for any keyboard-selectable HTML element such as input
also fire on space or enter when the element is selected.
postgres
UPDATE table1
SET COLUMN = value
FROM table2,
table3
WHERE table1.column_id = table2.id
AND table1.column_id = table3.id
AND table1.COLUMN = value
AND table2.COLUMN = value
AND table3.COLUMN = value
Follow the below steps in Eclipse.
Check here for more information : How to use web camera in android emulator to capture a live image?
The Bundle
is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle
.
putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)
In your onCreate
function, this Bundle
is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:
if (savedInstanceState != null) {
// Then the application is being reloaded
}
To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Your saved message will be toasted to the screen. Hope this helps.
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
Not sure if your question was answered.
This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.
Does not seem to create multiple instances, so that's a good thing.
@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls
This is a lot simpler with .slideToggle():
jQuery('.class1 a').click( function() {
$(this).next('.class2').slideToggle();
});
EDIT: made it .next instead of .siblings
http://www.mredesign.com/demos/jquery-effects-1/
You can also add cookie's to remember where you're at...
http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/
Because you need parentheses around the value your looking for.
So here : document.querySelector('a[data-a="1"]')
If you don't know in advance the value but is looking for it via variable you can use template literals :
Say we have divs with data-price
<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>
We want to find an element but with the number that someone chose (so we don't know it):
// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]
Escape the hyphen.
[a-zA-Z0-9!$* \t\r\n\-]
UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:
select
(select count(*) c from v$session where program = 'w3wp.exe') w3wp,
(select count(*) c from v$session) total,
sysdate
from dual;
which gives the following one-row output:
W3WP TOTAL SYSDATE
----- ----- -------------------
14 290 2020/02/18 10:45:07
(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)
In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.
An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.
select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo)
limit 1
My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...
SQLer
Running Xcode 4.6.3 on OSX 10.7.5 was able to fix this error by changing Architectures to Native Architecture of Build Machine from $(NATIVE_ARCH_ACTUAL).
I just had this problem and it seems to be related to permissions somehow. I initially unzipped it to my Program Files folder, in Windows 8. After unzipping it directly to C: the program started normally.
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
Use background-size
for that purpose:
background-size: 100% 100%;
More on:
This will give you some control over the clicking, and looks tidy
<script>
var timeOut = 0;
function onClick(but)
{
//code
clearTimeout(timeOut);
timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.
Here is information about all of the isolation levels at your disposal, as well as table hints.
Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...
CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;
CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid),
INDEX(tmpid))
SELECT * FROM tmpLivecheck;
... solved my problem.
Greetings...
Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip
Having fun with filter:
import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)
Easiest way is use read only attribute to prevent direct user input:
<input class="datepicker" type="text" name="date" value="" readonly />
Or you could use HTML5 validation based on pattern attribute. Date input pattern (dd/mm/yyyy or mm/dd/yyyy):
<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" class="datepicker" name="date" value="" />
I think it is because %
has often be associated with the modulus operator in many programming languages.
It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).