I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.
First use z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.
The design guidelines defines two sizes and unless there is a strong reason to deviate from using either, the size can be controlled with the fabSize
XML attribute of the FloatingActionButton
component.
Consider specifying using either app:fabSize="normal"
or app:fabSize="mini"
, e.g.:
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_done_white_24px"
app:fabSize="mini" />
Try something like:-
ALTER TABLE table_name ADD CONSTRAINT [DF_table_name_Created]
DEFAULT (getdate()) FOR [created_at];
replacing table_name
with the name of your table.
mysql.exe->Run as administrator or go to following path C:\wamp\bin\mysql\mysql5.5.24\bin and than right click on mysql.exe go to properties and than select tab as Compatibility and see the bottom of dialog box in privilege level and just check the Run this program as an administrator and then click apply ok.finished now you open success phpMyadmin. bye
Another version of the function without error handling. This time it is not case sensitive and a little bit more efficient.
Function WorksheetExists(wsName As String) As Boolean
Dim ws As Worksheet
Dim ret As Boolean
wsName = UCase(wsName)
For Each ws In ThisWorkbook.Sheets
If UCase(ws.Name) = wsName Then
ret = True
Exit For
End If
Next
WorksheetExists = ret
End Function
If your class inherits from Thread, you can use methods getName
and setName
to name each thread. Otherwise you could just add a name
field to MyTask
, and initialize it in your constructor.
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
To automatically convert spaces to tabs on save, add the following Python script to a newly created subfolder called "UnexpandTabsOnSave" within "$SUBLIME_HOME$\Packages\":
import sublime, sublime_plugin, os
class ConvertSpacesToTabsOnSave( sublime_plugin.EventListener ):
# Run Sublime's 'unexpand_tabs' command when saving any file
def on_pre_save( self, view ):
view.window().run_command( 'unexpand_tabs' )
Thank you for the initial resource.
have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme
for unix-like systems it will be as @Alex said file:///your/file/here
whereas for Windows systems would be file:///c|/path/to/file
Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount()
in a React class.
For you edit, you may want to try something like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
Here is my solution:
DataTable datatable = (DataTable)dataset.datatablename;
Packaged artifacts contain a META-INF/maven/${groupId}/${artifactId}/pom.properties
file which content looks like:
#Generated by Maven
#Sun Feb 21 23:38:24 GMT 2010
version=2.5
groupId=commons-lang
artifactId=commons-lang
Many applications use this file to read the application/jar version at runtime, there is zero setup required.
The only problem with the above approach is that this file is (currently) generated during the package
phase and will thus not be present during tests, etc (there is a Jira issue to change this, see MJAR-76). If this is an issue for you, then the approach described by Alex is the way to go.
We now finally have IDENTITY
columns like many other databases, in case of which a sequence is auto-generated behind the scenes. This solution is much faster than a trigger-based one as can be seen in this blog post.
So, your table creation would look like this:
CREATE TABLE qname
(
qname_id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL PRIMARY KEY,
qname VARCHAR2(4000) NOT NULL -- CONSTRAINT qname_uk UNIQUE
);
According to the documentation, you cannot do that:
Restriction on Default Column Values A DEFAULT expression cannot contain references to PL/SQL functions or to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, PRIOR, and ROWNUM, or date constants that are not fully specified.
The standard way to have "auto increment" columns in Oracle is to use triggers, e.g.
CREATE OR REPLACE TRIGGER my_trigger
BEFORE INSERT
ON qname
FOR EACH ROW
-- Optionally restrict this trigger to fire only when really needed
WHEN (new.qname_id is null)
DECLARE
v_id qname.qname_id%TYPE;
BEGIN
-- Select a new value from the sequence into a local variable. As David
-- commented, this step is optional. You can directly select into :new.qname_id
SELECT qname_id_seq.nextval INTO v_id FROM DUAL;
-- :new references the record that you are about to insert into qname. Hence,
-- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
-- obtained from your sequence, before inserting
:new.qname_id := v_id;
END my_trigger;
Read more about Oracle TRIGGERs in the documentation
No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug
and app\release
folders.
Try what @iFreilicht suggested above. If that didn't work after you've installed webpack and all, you may have just copied a webpack configuration from somewhere online and configured there that you want the output to support CommonJS by mistake. Make sure this isn't the case in webpack.config.js
:
module.exports = {
mode: process.env.NODE_ENV || "development",
entry: {
index: "./src/js/index.ts"
},
...
...
output: {
libraryTarget: 'commonjs', <==== DELETE THIS LINE
path: path.join(__dirname, 'build'),
filename: "[name].bundle.js"
}
};
I am using ng-class for adding style :-
ng-class="column.label=='Description' ? 'tableStyle':
column.label == 'Markdown Type' ? 'Mtype' :
column.label == 'Coupon Number' ? 'couponNur' : ''
"
Using ternary operator along with ng-class directives in angular.js for giving style. Then define the style for class in .css or .scss file. Eg :-
.Mtype{
width: 90px !important;
min-width: 90px !important;
max-width: 90px !important;
}
.tableStyle{
width: 129px !important;
min-width: 129px !important;
max-width: 129px !important;
}
.couponNur{
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
}
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
yields the attributes of obj
with their respective values:
name: Krishna
gender: male
I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.
What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:
LogicalORExpression ? AssignmentExpression : AssignmentExpression
The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.
The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.
Add the following in the textview in XML.
android:scrollbars="vertical"
And finally, add
textView.setMovementMethod(new ScrollingMovementMethod());
in the Java file.
I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:
Now your column headers should repeat on each page.
Two other simple possibilities:
There is an old (unfashionable) solution to the "a daemon that binds on a low port and hands control to your daemon". It's called inetd (or xinetd). The cons are:
Pros:
Another alternative: a hacked-up proxy (netcat or even something more robust) from the privileged port to some arbitrary high-numbered port where you can run your target daemon. (Netcat is obviously not a production solution, but "just my dev box", right?). This way you could continue to use a network-capable version of your server, would only need root/sudo to start proxy (at boot), wouldn't be relying on complex/potentially fragile capabilities.
For TypeScript users:
toggle(event: Event): void {
let elementId: string = (event.target as Element).id;
// do something with the id...
}
I used GENEGC's script, but I found it quite slow.
It is slow because it scans whole sheet on every edit.
So I wrote way faster and cleaner method for myself and I wanted to share it.
function onEdit(e) {
if (e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
// If you want to be specific
// do not work in first row
// do not work in other sheets except "MySheet"
if (r.getRow() != 1 && ss.getName() == "MySheet") {
// E.g. status column is 2nd (B)
status = ss.getRange(r.getRow(), 2).getValue();
// Specify the range with which You want to highlight
// with some reading of API you can easily modify the range selection properties
// (e.g. to automatically select all columns)
rowRange = ss.getRange(r.getRow(),1,1,19);
// This changes font color
if (status == 'YES') {
rowRange.setFontColor("#999999");
} else if (status == 'N/A') {
rowRange.setFontColor("#999999");
// DEFAULT
} else if (status == '') {
rowRange.setFontColor("#000000");
}
}
}
}
Taking @CaffGeek and simplifying it:
public static string Truncate(this string value, int maxLength)
{
return string.IsNullOrEmpty(value) ? value : value.Substring(0, Math.Min(value.Length, maxLength));
}
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Can you try changing "Allow from 127.0.0 192.168.1 ::1 localhost" to "Allow from all". If that fixes your problem, you need to be less restrict about where content can be requested from
You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf
:
Just add the JVM Option:
AddVMOption -Duser.language=en
The file will be like this:
Using a regex approach:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $text);
It searches for UTF-8 sequences, and captures those into group 1. It also matches single bytes that could not be identified as part of a UTF-8 sequence, but does not capture those. Replacement is whatever was captured into group 1. This effectively removes all invalid bytes.
It is possible to repair the string, by encoding the invalid bytes as UTF-8 characters. But if the errors are random, this could leave some strange symbols.
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| ( [\x80-\xBF] ) # invalid byte in range 10000000 - 10111111
| ( [\xC0-\xFF] ) # invalid byte in range 11000000 - 11111111
/x
END;
function utf8replacer($captures) {
if ($captures[1] != "") {
// Valid byte sequence. Return unmodified.
return $captures[1];
}
elseif ($captures[2] != "") {
// Invalid byte of the form 10xxxxxx.
// Encode as 11000010 10xxxxxx.
return "\xC2".$captures[2];
}
else {
// Invalid byte of the form 11xxxxxx.
// Encode as 11000011 10xxxxxx.
return "\xC3".chr(ord($captures[3])-64);
}
}
preg_replace_callback($regex, "utf8replacer", $text);
EDIT:
!empty(x)
will match non-empty values ("0"
is considered empty).x != ""
will match non-empty values, including "0"
.x !== ""
will match anything except ""
.x != ""
seem the best one to use in this case.
I have also sped up the match a little. Instead of matching each character separately, it matches sequences of valid UTF-8 characters.
You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.
$('#myForm').submit(function() {
$('select').removeAttr('disabled');
});
Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.
$(document).ready(function() {
$('select').attr('disabled', 'disabled');
});
When you set a percentage height on an element who's parent elements don't have heights set, the parent elements have a default
height: auto;
You are asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing with the height of child elements.
Besides using a JavaScript solution you could use this deadly easy table method:
#parent3 {
display: table;
width: 100%;
}
#parent3 .between {
display: table-row;
}
#parent3 .child {
display: table-cell;
}
Preview on http://jsbin.com/IkEqAfi/1
But: Bare in mind, that the table method only works properly in all modern Browsers and the Internet Explorer 8 and higher. As Fallback you could use JavaScript.
Finally it works for me.
private VideoView videoView;
videoView = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse("http://www.servername.com/projects/projectname/videos/1361439400.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoView.start();
}
});
Hope this would help others.
The main difference is that ChildA.__init__
will unconditionally call Base.__init__
whereas ChildB.__init__
will call __init__
in whatever class happens to be ChildB
ancestor in self
's line of ancestors
(which may differ from what you expect).
If you add a ClassC
that uses multiple inheritance:
class Mixin(Base):
def __init__(self):
print "Mixin stuff"
super(Mixin, self).__init__()
class ChildC(ChildB, Mixin): # Mixin is now between ChildB and Base
pass
ChildC()
help(ChildC) # shows that the Method Resolution Order is ChildC->ChildB->Mixin->Base
then Base
is no longer the parent of ChildB
for ChildC
instances. Now super(ChildB, self)
will point to Mixin
if self
is a ChildC
instance.
You have inserted Mixin
in between ChildB
and Base
. And you can take advantage of it with super()
So if you are designed your classes so that they can be used in a Cooperative Multiple Inheritance scenario, you use super
because you don't really know who is going to be the ancestor at runtime.
The super considered super post and pycon 2015 accompanying video explain this pretty well.
The only way to override inline style is by using !important
keyword beside the CSS rule. The following is an example of it.
div {
color: blue !important;
/* Adding !important will give this rule more precedence over inline style */
}
_x000D_
<div style="font-size: 18px; color: red;">
Hello, World. How can I change this to blue?
</div>
_x000D_
Important Notes:
Using
!important
is not considered as a good practice. Hence, you should avoid both!important
and inline style.Adding the
!important
keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.It even overrides the inline styles from the markup.
The only way to override is by using another
!important
rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.Must Read - CSS Specificity by MDN
jQuery
$('input[type=checkbox]').removeAttr('checked');
Or
<!-- checked -->
<input type='checkbox' name='foo' value='bar' checked=''/>
<!-- unchecked -->
<input type='checkbox' class='inputUncheck' name='foo' value='bar' checked=''/>
<input type='checkbox' class='inputUncheck' name='foo' value='bar'/>
+
$('input.inputUncheck').removeAttr('checked');
\d
means a digit in most languages. You can also use [0-9]
in all languages. For the "period or comma" use [\.,]
. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.
*
means "zero-or-more", so \d*
and [0-9]*
mean "zero or more numbers". ?
means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n}
to mean "between m and n" (ie: {1,2} means "between 1 and 2")
Since the dot or comma and additional numbers are optional, you can put them in a group and use the ?
quantifier to mean "zero-or-one" of that group.
Putting that all together you can use:
\d{1,2}([\.,][\d{1,2}])?
Meaning, one or two digits \d{1,2}
, followed by zero-or-one of a group (...)?
consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
I was needing to find out just which version of .NET framework I had on my computer, and all I did was go to the control panel and select the "Uninstall a Program" option. After that, I sorted the programs by name, and found Microsoft .NET Framework 4 Client Profile.
If it has a UI, it has an "API". Let's use the following example: I want to publish the pic I use in any new blog post I create. Let's assume is Wordpress.
No need to specify or even check if the file is/has compressed, you can send it to every file, On every request.
It tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.
<ifModule mod_headers.c>
Header unset Vary
Header set Vary "Accept-Encoding, X-HTTP-Method-Override, X-Forwarded-For, Remote-Address, X-Real-IP, X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port, X-Forwarded-Server"
</ifModule>
unset
is to fix some bugs in older GoDaddy hosting, optionally.Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.
The .add() method adds the selected elements to the result set:
// classA OR classB
jQuery('.classA').add('.classB');
It's more verbose than '.classA, .classB'
, but lets you build more complex selectors like the following:
// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));
It is worth noting that if you are returning server side data - you must supply the Data attribute even if there isn't any. It doesn't read the recordsTotal
or recordsFiltered
but relies on the count of the data object
I'm surprised nobody pointed out JSON's []
method, which makes it very easy and transparent to decode and encode from/to JSON.
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.
Consider this:
require 'json'
hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"
str
now contains the JSON encoded hash
.
It's easy to reverse it using:
JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}
Custom objects need to_s
defined for the class, and inside it convert the object to a Hash then use to_json
on it.
Refresh/Cleanup did not work for me. What worked:
1) File -> Switch workspace - choose a different workspace
2) afterwards switch back to the original workspace
As in any unix-based environment, you can use the sudo
command:
$ sudo script-name
It will ask for your password (your own, not a separate root
password).
You can assign an alternate ghost image if you really need to use drag events and can't set draggable=false. So just assign a blank png like so:
$('#img').bind({
dragstart: function(e) {
var dragIcon = document.createElement('img');
dragIcon.src = 'blank.png';
dragIcon.width = 100;
e.dataTransfer.setDragImage(dragIcon, -10, -10);
}
});
Although all the answers are already satisfactory, I'll try to cover the two extra cases along with the all the previous case.
if the spaces are not uniform and you want to maintain the same
string = hello world i am here.
if all the string are not starting from alphabets
string = 1 w 2 r 3g
Here you can use this:
def solve(s):
a = s.split(' ')
for i in range(len(a)):
a[i]= a[i].capitalize()
return ' '.join(a)
This will give you:
output = Hello World I Am Here
output = 1 W 2 R 3g
Postgres has a very rich system catalog exposed via SQL tables. PG's statistics collector is a subsystem that supports collection and reporting of information about server activity.
Now to figure out the blocking PIDs you can simply query pg_stat_activity
.
select pg_blocking_pids(pid) as blocked_by
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;
To, get the query corresponding to the blocking PID, you can self-join or use it as a where clause in a subquery.
SELECT query
FROM pg_stat_activity
WHERE pid IN (select unnest(pg_blocking_pids(pid)) as blocked_by from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0);
Note: Since pg_blocking_pids(pid)
returns an Integer[], so you need to unnest
it before you use it in a WHERE pid IN
clause.
Hunting for slow queries can be tedious sometimes, so have patience. Happy hunting.
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Use $evalAsync if you want your callback (i.e., test()) to be executed after the DOM is constructed, but before the browser renders. This will prevent flicker -- ref.
if (scope.$last) {
scope.$evalAsync(attr.onFinishRender);
}
If you really want to call your callback after rendering, use $timeout:
if (scope.$last) {
$timeout(function() {
scope.$eval(attr.onFinishRender);
});
}
I prefer $eval instead of an event. With an event, we need to know the name of the event and add code to our controller for that event. With $eval, there is less coupling between the controller and the directive.
Here's how you can put both batch code and the python one in single file:
0<0# : ^
'''
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''
print("python code")
the '''
respectively starts and ends python multi line comments.
0<0# : ^
is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^
by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0
statement and a start of inline comment.
The credit goes to siberia-man
Correct Xpath
syntax is like:
//tagname[@value='name']
So you should write something like this:
findElement(By.xpath("//input[@test-id='test-username']"));
I struggled with many of the suggestions here before I simple created an instance of a new 'Fake' class that implements whatever interface you are trying to Mock out. Then you can simply set the value of the out parameter with the method itself.
I was also facing the same issue for 2 days but now finally it is working.
Step 1 : create a php script file with this content.
<?php
echo 'username : ' . `whoami`;
phpinfo();
?>
note down the username. note down open_basedir under core section of phpinfo. also note down upload_tmp_dir under core section of phpinfo.
Here two things are important , see if upload_tmp_dir value is inside one of open_basedir directory. ( php can not upload files outside open_basedir directory ).
Step 2 : Open terminal with root access and go to upload_tmp_dir location. ( In my case "/home/admin/tmp". )
=> cd /home/admin/tmp
But it was not found in my case so I created it and added chown for php user which I get in step 1 ( In my case "admin" ).
=> mkdir /home/admin/tmp
=> chown admin /home/admin/tmp
That is all you have to do to fix the file upload problem.
You must do the following command:
sort -n -k1 filename
That should do it :)
Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.
Option Explicit
Private Const SEE_MASK_DEFAULT = &H0
Public Enum EShellShowConstants
essSW_HIDE = 0
essSW_SHOWNORMAL = 1
essSW_SHOWMINIMIZED = 2
essSW_MAXIMIZE = 3
essSW_SHOWMAXIMIZED = 3
essSW_SHOWNOACTIVATE = 4
essSW_SHOW = 5
essSW_MINIMIZE = 6
essSW_SHOWMINNOACTIVE = 7
essSW_SHOWNA = 8
essSW_RESTORE = 9
essSW_SHOWDEFAULT = 10
End Enum
Private Type SHELLEXECUTEINFO
cbSize As Long
fMask As Long
hwnd As Long
lpVerb As String
lpFile As String
lpParameters As String
lpDirectory As String
nShow As Long
hInstApp As Long
lpIDList As Long 'Optional
lpClass As String 'Optional
hkeyClass As Long 'Optional
dwHotKey As Long 'Optional
hIcon As Long 'Optional
hProcess As Long 'Optional
End Type
Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long
Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
Dim SEI As SHELLEXECUTEINFO
On Error GoTo Err
'Fill the SEI structure
With SEI
.cbSize = Len(SEI) ' Bytes of the structure
.fMask = SEE_MASK_DEFAULT ' Check MSDN for more info on Mask
.lpFile = FilePath ' Program Path
.nShow = ShellShowType ' How the program will be displayed
.lpDirectory = PathGetFolder(FilePath)
.lpParameters = EXEParameters ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
.hwnd = hWndOwner ' Owner window handle
' Determine launch type (would recommend checking for Vista or greater here also)
If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
.lpVerb = "runas"
Else
.lpVerb = "Open"
End If
End With
ExecuteProcess = ShellExecuteEx(SEI) ' Execute the program, return success or failure
Exit Function
Err:
' TODO: Log Error
ExecuteProcess = False
End Function
Private Function PathGetFolder(psPath As String) As String
On Error Resume Next
Dim lPos As Long
lPos = InStrRev(psPath, "\")
PathGetFolder = Left$(psPath, lPos - 1)
End Function
Try this:
npm install -g tsd
npm i
and npm start
I came up with another solution based on @emenegro's solution
NSInteger maxY = 0;
for (UIView* subview in scrollView.subviews)
{
if (CGRectGetMaxY(subview.frame) > maxY)
{
maxY = CGRectGetMaxY(subview.frame);
}
}
maxY += 10;
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, maxY)];
Basically, we figure out which element is furthest down in the view and adds a 10px padding to the bottom
Check for NUnit versions mismatch. The currently available NUnit Test Adapter only works for NUnit version 2.6.4 and below. To downgrade NUnit from version 3.x go to Package Manager Console > update-package NUnit -version 2.6.4
http://jeremybytes.blogspot.co.ke/2015/11/review-of-unit-testing-makes-me-faster.html
Although it is easy to construct a GET query using window.open()
, it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:
<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>
<input type="button" onclick="loadNnextPage()" value="Click me!">
<script>
function loadNnextPage() {
document.getElementById("helper").headerData.value = "New";
document.getElementById("helper").submit();
}
</script>
Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.
Problems with GET
Ah yes. Welcome to Asynchronous execution.
Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.
Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.
A simple way to see remote branches is:
git branch -r
To see local branches:
git branch -l
I would recommend state.cs. I personally used state.js (the JavaScript version) and am very happy with it. That C# version works in a similar way.
You instantiate states:
// create the state machine
var player = new StateMachine<State>( "player" );
// create some states
var initial = player.CreatePseudoState( "initial", PseudoStateKind.Initial );
var operational = player.CreateCompositeState( "operational" );
...
You instantiate some transitions:
var t0 = player.CreateTransition( initial, operational );
player.CreateTransition( history, stopped );
player.CreateTransition<String>( stopped, running, ( state, command ) => command.Equals( "play" ) );
player.CreateTransition<String>( active, stopped, ( state, command ) => command.Equals( "stop" ) );
You define actions on states and transitions:
t0.Effect += DisengageHead;
t0.Effect += StopMotor;
And that's (pretty much) it. Look at the website for more information.
I usually do
SELECT *
FROM MyTable
WHERE CONVERT(VARCHAR, MyTable.dateField, 101) = CONVERT(VARCHAR, GETDATE(), 101)
if you are using SQL SERVER 2008, you can do
SELECT *
FROM MyTable
WHERE CAST(MyTable.dateField AS DATE) = CAST(GETDATE() AS DATE)
Hope this helps
Another way:
var := coalesce (var, 5);
COALESCE is the ANSI equivalent (more or less) of Oracle's NVL function.
For my situation, I had
RewriteEngine On
in my .htaccess
, along with the module being loaded, and it was not working.
The solution to my problem was to edit my vhost entry to inlcude
AllowOverride all
in the <Directory>
section for the site in question.
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
It's better to use SUSER_SNAME() since when there is no corresponding login on the server the join to syslogins will not match
SELECT s.name ,
SUSER_SNAME(s.owner_sid) AS owner
FROM msdb..sysjobs s
ORDER BY name
I suspect wpis.entry.lastChangeDate
has been somehow transformed into a string in the view, before arriving to the template.
In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper
, and then see if the template crashes.
You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.
On an unrelated notice, why don't you use models.DateTimeField(
auto_now_add
=True)
to set the datetime on creation?
I've had success with this solution. It's almost like Patrick's, with a little twist. You can use these expressions separately or in sequence. If the parameter is blank, it will be ignored and all values for the column that your searching will be displayed, including NULLS.
SELECT * FROM MyTable
WHERE
--check to see if @param1 exists, if @param1 is blank, return all
--records excluding filters below
(Col1 LIKE '%' + @param1 + '%' OR @param1 = '')
AND
--where you want to search multiple columns using the same parameter
--enclose the first 'OR' expression in braces and enclose the entire
--expression
((Col2 LIKE '%' + @searchString + '%' OR Col3 LIKE '%' + @searchString + '%') OR @searchString = '')
AND
--if your search requires a date you could do the following
(Cast(DateCol AS DATE) BETWEEN CAST(@dateParam AS Date) AND CAST(GETDATE() AS DATE) OR @dateParam = '')
I was looking for a solution to enumerate an array of an unknown at compile time rank with an access to every element indices set. I saw solutions with yield but here is another implementation with no yield. It is in old school minimalistic way. In this example AppendArrayDebug() just prints all the elements into StringBuilder buffer.
public static void AppendArrayDebug ( StringBuilder sb, Array array )
{
if( array == null || array.Length == 0 )
{
sb.Append( "<nothing>" );
return;
}
int i;
var rank = array.Rank;
var lastIndex = rank - 1;
// Initialize indices and their boundaries
var indices = new int[rank];
var lower = new int[rank];
var upper = new int[rank];
for( i = 0; i < rank; ++i )
{
indices[i] = lower[i] = array.GetLowerBound( i );
upper[i] = array.GetUpperBound( i );
}
while( true )
{
BeginMainLoop:
// Begin work with an element
var element = array.GetValue( indices );
sb.AppendLine();
sb.Append( '[' );
for( i = 0; i < rank; ++i )
{
sb.Append( indices[i] );
sb.Append( ' ' );
}
sb.Length -= 1;
sb.Append( "] = " );
sb.Append( element );
// End work with the element
// Increment index set
// All indices except the first one are enumerated several times
for( i = lastIndex; i > 0; )
{
if( ++indices[i] <= upper[i] )
goto BeginMainLoop;
indices[i] = lower[i];
--i;
}
// Special case for the first index, it must be enumerated only once
if( ++indices[0] > upper[0] )
break;
}
}
For example the following array will produce the following output:
var array = new [,,]
{
{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } },
{ { 13, 14, 15 }, { 16, 17, 18 }, { 19, 20, 21 }, { 22, 23, 24 } }
};
/*
Output:
[0 0 0] = 1
[0 0 1] = 2
[0 0 2] = 3
[0 1 0] = 4
[0 1 1] = 5
[0 1 2] = 6
[0 2 0] = 7
[0 2 1] = 8
[0 2 2] = 9
[0 3 0] = 10
[0 3 1] = 11
[0 3 2] = 12
[1 0 0] = 13
[1 0 1] = 14
[1 0 2] = 15
[1 1 0] = 16
[1 1 1] = 17
[1 1 2] = 18
[1 2 0] = 19
[1 2 1] = 20
[1 2 2] = 21
[1 3 0] = 22
[1 3 1] = 23
[1 3 2] = 24
*/
My response is very late but for others users In your case you have to configure failsafe pluging to use the command line agent configuration saved in itCoverageAgent variable. For exemple
<configuration>
<argLine>${itCoverageAgent}</argLine>
</configuration>
In your maven configuration, jacoco prepare the command line arguments in prepare-agent phase, but failsafe plugin doesn't use it so there is no execution data file.
This has only been tested on Windows:
You can do the following:
import os
os.startfile("C:/Users/TestFile.txt", "print")
This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os
module which comes with the standard library
If you are using a self-hosted version of GitLab then you may consider running this command.
grep gitlab /opt/gitlab/version-manifest.txt
Edit: both answers have been updated and are now correct. I'll leave the answer since the function timings are still useful.
The answers by 'zombat' and 'too much php' are unfortunately not correct. This is a revision to the answer zombat posted (as I don't have enough reputation to post a comment):
$pos = strpos($haystack,$needle);
if ($pos !== false) {
$newstring = substr_replace($haystack,$replace,$pos,strlen($needle));
}
Note the strlen($needle), instead of strlen($replace). Zombat's example will only work correctly if needle and replace are the same length.
Here's the same functionality in a function with the same signature as PHP's own str_replace:
function str_replace_first($search, $replace, $subject) {
$pos = strpos($subject, $search);
if ($pos !== false) {
return substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
This is the revised answer of 'too much php':
implode($replace, explode($search, $subject, 2));
Note the 2 at the end instead of 1. Or in function format:
function str_replace_first($search, $replace, $subject) {
return implode($replace, explode($search, $subject, 2));
}
I timed the two functions and the first one is twice as fast when no match is found. They are the same speed when a match is found.
add below code in your < a > TAG
data-toggle="collapse" data-target=".navbar-collapse.show"
as shows below in every TAG
<li class="nav-item">
<a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>
Okay this is an example for the new embed code for youtube videos.
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM" frameborder="0" allowFullScreen></iframe>
if you want to autoplay it, at the src="http://www.youtube.com/embed/8v_4O44sfjM"
add the ?autoplay=1
parameter
So the code will look like this:
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM?autoplay=1" frameborder="0" allowFullScreen></iframe>
i tried this on my blog and it works ! Hope this help (:
For 2 and more left joins (left joining creatorUser and initiatorUser )
IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
join candidateUser in authContext.AuthUsers
on r.CandidateId equals candidateUser.Id
join creatorUser in authContext.AuthUsers
on r.CreatorId equals creatorUser.Id into gj
from x in gj.DefaultIfEmpty()
join initiatorUser in authContext.AuthUsers
on r.InitiatorId equals initiatorUser.Id into init
from x1 in init.DefaultIfEmpty()
where candidateUser.UserName.Equals(candidateUsername)
select new CreateRequestModel
{
UserName = candidateUser.UserName,
CreatorId = (x == null ? String.Empty : x.UserName),
InitiatorId = (x1 == null ? String.Empty : x1.UserName),
CandidateId = candidateUser.UserName
};
foo.h
#ifndef FOO_H_ /* Include guard */
#define FOO_H_
int foo(int x); /* An example function declaration */
#endif // FOO_H_
foo.c
#include "foo.h" /* Include the header (not strictly necessary here) */
int foo(int x) /* Function definition */
{
return x + 5;
}
main.c
#include <stdio.h>
#include "foo.h" /* Include the header here, to obtain the function declaration */
int main(void)
{
int y = foo(3); /* Use the function here */
printf("%d\n", y);
return 0;
}
To compile using GCC
gcc -o my_app main.c foo.c
On input type=file add an event onchange="preview()"
For the function preview()
type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
_x000D_
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
Mongoose (Formerly Simple HTTP Daemon) is pretty good. In particular, it's embeddable and compiles under Windows, Windows CE, and UNIX.
It is a horrible mistake but:
Be sure you have Web.config files in your View at Remote. Maybe you skipped to upload it by your Ftp programme's filters.
waiting for some(like 10) seconds your compiler to use this static class method
TimeUnit.SECONDS.sleep(10);
it's including in
java.util.concurrent.TimeUnit libery
the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.
Setting the timeout in componentDidMount works but in my application I received a memory leak warning. Try something like this.
constructor(props) {
super(props)
this.state = {
loading: true,
}
}
componentDidMount() {
this.timerHandle = setTimeout(() => this.setState({ loading: false }), 3500);
}
componentWillUnmount(){
if (this.timerHandle) {
clearTimeout(this.timerHandle);
this.timerHandle = 0;
}
}
From Python's sources object.c:
/* Test whether an object can be called */
int
PyCallable_Check(PyObject *x)
{
if (x == NULL)
return 0;
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "__call__");
if (call == NULL) {
PyErr_Clear();
return 0;
}
/* Could test recursively but don't, for fear of endless
recursion if some joker sets self.__call__ = self */
Py_DECREF(call);
return 1;
}
else {
return x->ob_type->tp_call != NULL;
}
}
It says:
__call__
attribute.x
is callable iff x->ob_type->tp_call != NULL
Desciption of tp_call
field:
ternaryfunc tp_call
An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call(). This field is inherited by subtypes.
You can always use built-in callable
function to determine whether given object is callable or not; or better yet just call it and catch TypeError
later. callable
is removed in Python 3.0 and 3.1, use callable = lambda o: hasattr(o, '__call__')
or isinstance(o, collections.Callable)
.
Example, a simplistic cache implementation:
class Cached:
def __init__(self, function):
self.function = function
self.cache = {}
def __call__(self, *args):
try: return self.cache[args]
except KeyError:
ret = self.cache[args] = self.function(*args)
return ret
Usage:
@Cached
def ack(x, y):
return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1)
Example from standard library, file site.py
, definition of built-in exit()
and quit()
functions:
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
I have had the same problem as noted above. I could not get Eclipse to install because of Java incompatibilities. The sequence I followed goes like this:
This took hours of my time. I hope this proves useful.
system
The system
method calls a system program. You have to provide the command as a string argument to this method. For example:
>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true
The invoked program will use the current STDIN
, STDOUT
and STDERR
objects of your Ruby program. In fact, the actual return value is either true
, false
or nil
. In the example the date was printed through the IO object of STDIN
. The method will return true
if the process exited with a zero status, false
if the process exited with a non-zero status and nil
if the execution failed.
As of Ruby 2.6, passing exception: true
will raise an exception instead of returning false
or nil
:
>> system('invalid')
=> nil
>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)
Another side effect is that the global variable $?
is set to a Process::Status
object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.
>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>
Backticks
Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.
>> `date`
=> Wed Sep 4 22:22:51 CEST 2013
The global variable $?
is set through the backticks, too. With backticks you can also make use string interpolation.
%x()
Using %x
is an alternative to the backticks style. It will return the output, too. Like its relatives %w
and %q
(among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date)
, %x{date}
and %x-date-
are all synonyms. Like backticks %x
can make use of string interpolation.
exec
By using Kernel#exec
the current process (your Ruby script) is replaced with the process invoked through exec
. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.
Open3.popen3
Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3
comes in handy:
require 'open3'
Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
pid = thread.pid
puts stdout.read.chomp
end
Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.
Although solution to this problem is hardly coded in regeneration of your .htaccess file; indeed it din't worked for most of you specially when the site is migrated to some new server.
Let's dive into some basics.
Let's assume that for most of us, WordPress environment is running on a PHP server APACHE where this server is controlling most of our environment's initial dependencies. Meanwhile .htaccess generation is also mainly dependent on Apache configurations.
So if that been said, the contribution of .htaccess creation conflict mainly occurs when a WordPress website is migrated from a server running the WordPress environment on old version of Apache and PHP to a newer version of PHP and Apache.
Because dependencies of nrwer and older versions are different that's why the newer version of Apache2 won't allow the .htaccess directives to create a .htaccess file by default; because of which we have to manually set the WordPress website's root directory permissions from "AllowOverride None" to "AllowOverride All".
Comparatively, AllowOverride directive is used to allow the use of .htaccess within the web server to allow overriding of the Apache config on a per directory basis.
Use the following fix to change the apache2.conf directory permission settings:
Swift 3.0 with failsafe option (returns the original image in case of error):
func resize(image: UIImage, toSize size: CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(size,false,1.0)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
if let resizedImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return resizedImage
}
UIGraphicsEndImageContext()
return image
}
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.
However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.
This code will test if your String matches:
if (str.matches("\".*\"")) {
// this string starts and end with a double quote
}
Note that you don't need to add start and end of input markers (^
and $
) in the regex, because matches()
requires that the whole input be matched to return true - ^
and $
are implied.
My first question is which version of SQL Server are you using (i.e 2005, 2008, 2008 R2, 2012)?
Assuming you are using 2008 or later SQL uses scope for variable determination. I believe 2005 still had global variables that would use @@variablename instead of @variable name which would define the difference between global and local variables. Starting in 2008 I believe this was changed to a scope defined variable designation structure. For example to create a global variable the @variable has to be defined at the start of a procedure, function, view, etc. In 2008 and later @@defined system variables for system functions I do believe. I could explain further if you explained the version and also where the variable is being defined, and the error that you are getting.
Solution included in the EditText action listenner:
public void onCreate(Bundle savedInstanceState) {
...
...
edittext = (EditText) findViewById(R.id.EditText01);
edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(edittext.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
...
...
}
Downgrading to node stable fixed this issue for me, as it occurred after I upgraded to node 12
sudo n 10.16.0
button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well
button:active{_x000D_
color: red;_x000D_
}
_x000D_
The default shortcut key is Ctrl-Alt-C.
As zmorris points driver.getPageSource().contains("input");
is not the proper solution because it searches in all the html, not only the texts on it.
I suggest to check this question: how can I check if some text exist or not in the page?
and the recomended way explained by Slanec:
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));
Basically it's like a DataReader, once read, data will be lost.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
String str = TempData["T"]; //Output - T
return View();
}
}
If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.
Check the output in Action Method Test 1 and Test 2
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
string Str = Convert.ToString(TempData["T"]);
TempData.Keep(); // Keep TempData
return RedirectToAction("Test2");
}
public ActionResult Test2()
{
string Str = Convert.ToString(TempData["T"]); //OutPut - T
return View();
}
}
If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep()
. is that
The Data will persist to the corresponding View
Fix any XML formatting errors in the XML Files in your /res/menu folder.
Might be a compile time error from the XML file being improperly formatted.
I'd like to suggest a related solution, which is to pass the @Value
-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils
class.
Instead of this:
public class Foo {
@Value("${foo}")
private String foo;
}
and
public class FooTest {
@InjectMocks
private Foo foo;
@Before
public void setUp() {
ReflectionTestUtils.setField(Foo.class, "foo", "foo");
}
@Test
public void testFoo() {
// stuff
}
}
Do this:
public class Foo {
private String foo;
public Foo(@Value("${foo}") String foo) {
this.foo = foo;
}
}
and
public class FooTest {
private Foo foo;
@Before
public void setUp() {
foo = new Foo("foo");
}
@Test
public void testFoo() {
// stuff
}
}
Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).
Remove the old event handler
$('#id').unbind('click');
And attach the new one
$('#id').click(function(){
// your code here
});
it is pretty easy to calculate the MD5 hash using the MD5 function of CryptoJS and the HTML5 FileReader API. The following code snippet shows how you can read the binary data and calculate the MD5 hash from an image that has been dragged into your Browser:
var holder = document.getElementById('holder');
holder.ondragover = function() {
return false;
};
holder.ondragend = function() {
return false;
};
holder.ondrop = function(event) {
event.preventDefault();
var file = event.dataTransfer.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binary = event.target.result;
var md5 = CryptoJS.MD5(binary).toString();
console.log(md5);
};
reader.readAsBinaryString(file);
};
I recommend to add some CSS to see the Drag & Drop area:
#holder {
border: 10px dashed #ccc;
width: 300px;
height: 300px;
}
#holder.hover {
border: 10px dashed #333;
}
More about the Drag & Drop functionality can be found here: File API & FileReader
I tested the sample in Google Chrome Version 32.
In the first class, sayHi()
is actually an instance method which you are calling as a static method and you get away with it because sayHi()
never refers to $this
.
Static functions are associated with the class, not an instance of the class. As such, $this
is not available from a static context ($this
isn't pointing to any object).
The FLAG_ACTIVITY_NO_ANIMATION
flag works fine for disabling the animation when starting activities.
To disable the similar animation that is triggered when calling finish()
on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0)
after calling finish()
and the next animation will be excluded.
This also works on the in-animation if you call overridePendingTransition(0, 0)
after calling startActivity(...)
.
Look in the Cmakelists.txt if you find ARM you need to install C++ for ARM and as well vcvarsall.bat use for ARM bin folder.
It's these packages:
C++ Universal Windows Platform for ARM64 "Not Required"
Visual C++ Compilers and libraries for ARM "Not Required"
Visual C++ Compilers and libraries for ARM64 "Very Likely Required"
Required for finding Threads on ARM
enable_language(C)
enable_language(CXX)
Then the problems might disappear:
No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.
If above does not resolve your problem?
Optionally you can remove the options C and CXX in cmakelists.txt by setting # infront of where the enable_language(C) is. And avoid Android ARM processor compilation.
You could use the following code where indentation doesn't matter:
>>> def fun():
return ('{0} Here is a really long'
' sentence with {1}').format(3, 5)
You just need to enclose string in the parentheses.
In case you were looking to transform your column number into a letter:
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
This way you could do something like this:
Function selectColumnRange(colNum As Integer, targetWorksheet As Worksheet)
Dim colLetter As String
Dim testRange As Range
colLetter = ConvertToLetter(colNum)
testRange = targetWorksheet.Range(colLetter & ":" & colLetter).Select
End Function
That example function would select the entire column ( i.e. Range("A:A").Select)
It's pretty straightforward with some simple rules:
then
, return it - any promise you don't return will not be waited for outside..all
them - that way it waits for all the promises and no error from any of them are silenced.then
s, you can typically return in the middle - then
chains are usually at most 1 level deep.And some tips:
.map
than with for/push
- if you're mapping values with a function, map
lets you concisely express the notion of applying actions one by one and aggregating the results.Promise.all
than to execute things one after the other - each waiting before the next.Ok, so let's get started:
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I said, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the previous
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
It has uses in both C and C++.
As you guessed, the static
part limits its scope to that compilation unit. It also provides for static initialization. const
just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.
All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static
is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const
on there will warn you if any code would try to modify that.
If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).
1) As mentioned by Greg, wstring is helpful for internationalization, that's when you will be releasing your product in languages other than english
4) Check this out for wide character http://en.wikipedia.org/wiki/Wide_character
You have missed matInput
directive in your input tag.
I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.
http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/ The blog post is a 2 parter, and the project is here: https://github.com/dkarzon/DropNet
It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.
Working with VS 2013. Try the following
Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off
It will disable the display of modules loaded.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
This is how to pass the struct
by reference. This means that your function can access the struct
outside of the function and modify its values. You do this by passing a pointer to the structure to the function.
#include <stdio.h>
/* card structure definition */
struct card
{
int face; // define pointer face
}; // end structure card
typedef struct card Card ;
/* prototype */
void passByReference(Card *c) ;
int main(void)
{
Card c ;
c.face = 1 ;
Card *cptr = &c ; // pointer to Card c
printf("The value of c before function passing = %d\n", c.face);
printf("The value of cptr before function = %d\n",cptr->face);
passByReference(cptr);
printf("The value of c after function passing = %d\n", c.face);
return 0 ; // successfully ran program
}
void passByReference(Card *c)
{
c->face = 4;
}
This is how you pass the struct
by value so that your function receives a copy of the struct
and cannot access the exterior structure to modify it. By exterior I mean outside the function.
#include <stdio.h>
/* global card structure definition */
struct card
{
int face ; // define pointer face
};// end structure card
typedef struct card Card ;
/* function prototypes */
void passByValue(Card c);
int main(void)
{
Card c ;
c.face = 1;
printf("c.face before passByValue() = %d\n", c.face);
passByValue(c);
printf("c.face after passByValue() = %d\n",c.face);
printf("As you can see the value of c did not change\n");
printf("\nand the Card c inside the function has been destroyed"
"\n(no longer in memory)");
}
void passByValue(Card c)
{
c.face = 5;
}
use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();
I faced the issue when i was using ZBar for scanning in tabs. Camera orientation issue. Using below code i was able to resolve issue. This is not the whole code snippet, Please take only help from this.
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (isPreviewRunning) {
mCamera.stopPreview();
}
setCameraDisplayOrientation(mCamera);
previewCamera();
}
public void previewCamera() {
try {
// Hard code camera surface rotation 90 degs to match Activity view
// in portrait
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(previewCallback);
mCamera.startPreview();
mCamera.autoFocus(autoFocusCallback);
isPreviewRunning = true;
} catch (Exception e) {
Log.d("DBG", "Error starting camera preview: " + e.getMessage());
}
}
public void setCameraDisplayOrientation(android.hardware.Camera camera) {
Camera.Parameters parameters = camera.getParameters();
android.hardware.Camera.CameraInfo camInfo =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(getBackFacingCameraId(), camInfo);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (camInfo.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (camInfo.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
private int getBackFacingCameraId() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload() {
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
A method based on np.split
:
df = pd.DataFrame({ 'A':[2,4,6,8,10,2,4,6,8,10],
'B':[10,-10,0,20,-10,10,-10,0,20,-10],
'C':[4,12,8,0,0,4,12,8,0,0],
'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})
listOfDfs = [df.loc[idx] for idx in np.split(df.index,5)]
A small function that uses a modulo could take care of cases where the split is not even (e.g. np.split(df.index,4)
will throw an error).
(Yes, I am aware that the original question was somewhat more specific than this. However, this is supposed to answer the question in the title.)
Another option, using the command module:
- name: Create file
command: touch /path/to/file
args:
creates: /path/to/file
The 'creates' argument ensures that this action is not performed if the file exists.
here's non-paste methods
awk
awk 'BEGIN {OFS=" "}{
getline line < "file2"
print $0,line
} ' file1
Bash
exec 6<"file2"
while read -r line
do
read -r f2line <&6
echo "${line}${f2line}"
done <"file1"
exec 6<&-
Since the release of iOS 8, UIAlertView
is now deprecated; UIAlertController is the replacement.
Here is a sample of how it looks in Swift:
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!
Updated for Swift 4.2
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
Forget about your custom sorter. Start over using the code at the following page. It will show you how to define a class that inherits from the IComparer interface. Each line is commented out, so you can actually see what is happening. The only potential complication is how you are retrieving your Listview Items from your Listview control. Get those squared away and all you need to do is copy and paste the IComparer interface class and the columnClick method.
Data Flow and Flow Chart differ in processes, flow, and timing.
Processes
a.) On DFDs, processes can operate in parallel (at-the-same-time).
b.) On flowcharts, processes execute one at a time.
Flow
a.) DFDs show the flow of data through a system
b.) Flowcharts show the flow of control (sequence and transfer of control)
Timing
a.) Processes on a DFD can have dramatically different timing (daily, weekly, on demand)
b.) Processes on flowcharts are part of a single program with consistent timing
I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.
If you'd like to use it as well, then:
Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.
Unzip TortoiseIDiff.exe
and TortoiseMerge.exe
to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\
in my case).
In SourceTree open Tools > Options > Diff > External Diff / Merge
. Select TortoiseMerge
in both dropdown lists.
Hit OK
and point SourceTree to your location of TortoiseIDiff.exe
and TortoiseMerge.exe
.
After that, you can select Resolve Conflicts > Launch External Merge Tool
from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.
The only problem is, that it automatically creates backup copy, even though proper option is unchecked.
The & and | are usually bitwise operations.
Where as && and || are usually logical operations.
For comparison purposes, it's perfectly fine provided that everything returns either a 1 or a 0. Otherwise, it can return false positives. You should avoid this though to prevent hard to read bugs.
You have ArrayList
all wrong,
add()
method in an arrayRather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0
to N-1
where N
is size()
of list.
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page
If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.
Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.
The button is a web control Button Add a Click event to the button call it Button1Click:
void Button1Click(Object sender,EventArgs e) { }
Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.
So if for example you want to access the text in TextBox1
you just need to call that object in the C# code:
String firstBox = TextBox1.Text;
In the same way you can populate the objects when event occur.
Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.
I had a similar issue. In my case, I had to uninstall and then reinstall pip3:
sudo apt-get remove python3-pip
sudo apt-get install python3-pip
I tried the procedures of your posts but with no success.
This is what I get from debugger:
Original string that I save into sqlite database was b\r\na
.. when I read them, I get b\\r\\na
(length in debugger is 6: "b" "\" "\r" "\" "\n" "a"
) then I try replace this string and I get string with length 6 again (you can see in picture above).
I run this short script in my test form with only one text box:
private void Form_Load(object sender, EventArgs e)
{
string x = "b\\r\\na";
string y = x.Replace(@"\\", @"\");
this.textBox.Text = y + "\r\n\r\nLength: " + y.Length.ToString();
}
and I get this in text box (so, no new line characters between "b" and "a":
b\r\na
Length: 6
What can I do with this string to unescape backslash? (I expect new line between "b" and "a".)
Solution:
OK, this is not possible to do with standard replace, because of \r
and \n
is one character. Is possible to replace part of string character by character but not possible to replace "half part" of one character. So, I must replace any special character separatelly, like this:
private void Form_Load(object sender, EventArgs e) {
...
string z = x.Replace(@"\r\n", Environment.NewLine);
...
This produce correct result for me:
b
a
There are multiple ways to add the basic HTTP authentication to the RestTemplate
.
try {
// request url
String url = "https://jsonplaceholder.typicode.com/posts";
// create auth credentials
String authStr = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
// create headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
// create request
HttpEntity request = new HttpEntity(headers);
// make a request
ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);
// get JSON response
String json = response.getBody();
} catch (Exception ex) {
ex.printStackTrace();
}
If you are using Spring 5.1
or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth()
method instead:
// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthentication("username", "password")
.build();
}
// use `restTemplate` instance here
}
@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthentication("username", "password").build();
}
I hope it helps!
A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.
XmlDocument doc = new XmlDocument();_x000D_
doc.Load(@"F:\dji\A18rad\A18rad\XMLFile1.xml");_x000D_
List<vreme> vreme = new List<vreme>();_x000D_
string grad = Request.Form["grad"];_x000D_
_x000D_
foreach (XmlNode cvor in doc.SelectNodes("/vreme/Prognoza"))_x000D_
{_x000D_
if (grad == cvor["NazivMesta"].InnerText)_x000D_
vreme.Add(new vreme_x000D_
{_x000D_
mesto = cvor["NazivMesta"].InnerText,_x000D_
maxtemp = cvor["MaxTemperatura"].InnerText,_x000D_
mintemp = cvor["MinTemperatura"].InnerText,_x000D_
vremee = cvor["Vreme"].InnerText_x000D_
});_x000D_
}_x000D_
return View(vreme);_x000D_
}_x000D_
public ActionResult maxtemperature()_x000D_
{_x000D_
XmlDocument doc = new XmlDocument();_x000D_
doc.Load(@"F:\dji\A18rad\A18rad\XMLFile1.xml");_x000D_
List<vreme> vreme = new List<vreme>();_x000D_
_x000D_
foreach (XmlNode cvor in doc.SelectNodes("/vreme/Prognoza"))_x000D_
{_x000D_
vreme.Add(new vreme_x000D_
{_x000D_
mesto = cvor["NazivMesta"].InnerText,_x000D_
maxtemp = cvor["MaxTemperatura"].InnerText_x000D_
});_x000D_
}_x000D_
return View(vreme);_x000D_
}_x000D_
}_x000D_
}_x000D_
@*@{_x000D_
ViewBag.Title = "maxtemperature";_x000D_
}_x000D_
@Html.ActionLink("Vreme Po izboru","index","home")_x000D_
<h2>maxtemperature</h2>_x000D_
<table border="10">_x000D_
<tr><th>Mesto</th>_x000D_
<th>MaxTemp</th>_x000D_
</tr>_x000D_
@foreach (A18rad.Models.vreme vr in Model)_x000D_
{_x000D_
<tr>_x000D_
<td>@vr.mesto</td>_x000D_
<td>@vr.maxtemp</td>_x000D_
</tr>_x000D_
}_x000D_
</table>*@_x000D_
@*@{_x000D_
ViewBag.Title = "Index";_x000D_
}_x000D_
@Html.ActionLink("MaxTemperature","maxtemperature","home")_x000D_
@using(Html.BeginForm("Index","Home")){_x000D_
<h2>Index</h2>_x000D_
_x000D_
_x000D_
<span>Grad:</span><select name="grad">_x000D_
<option value="Nis">Nis</option>_x000D_
<option value="Beograd">Beograd</option>_x000D_
<option value="Kopaonik">Kopaonik</option>_x000D_
</select>_x000D_
<input type="submit" value="Moze" /><br />_x000D_
foreach (A18rad.Models.vreme vr in Model)_x000D_
{_x000D_
<span>Min temperatura:</span> @vr.mintemp<br />_x000D_
<span>Max temperatura:</span> @vr.maxtemp<br />_x000D_
if(vr.vremee =="Kisa"){_x000D_
<span>Vreme:</span> <img src ="kisa.jpg" />_x000D_
}_x000D_
else if(vr.vremee =="Sneg"){_x000D_
<img src="sneg.jpg" />_x000D_
} else if (vr.vremee == "Vedro") { _x000D_
_x000D_
<img src ="vedro.png" /><br />_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
}*@
_x000D_
I haven't tried it, but this pysftp module might help, which in turn uses paramiko. I believe everything is client-side.
The interesting command is probably .execute()
which executes an arbitrary command on the remote machine. (The module also features .get()
and .put
methods which allude more to its FTP character).
UPDATE:
I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
Create a Virtual Machine with Windows running on it and download the file to a shared folder. :-D
After trial and error I discovered that you need to stage the file that had the merge conflict, then you can commit the merge.
litt late, but I had the same concern...
Rephrasing your code from the original post, you want the max of the set S defined by
(From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter)
Taking in account your last comment
Suffice to say that I know I want 0 when there are no records to select from, which definitely has an impact on the eventual solution
I can rephrase your problem as: You want the max of {0 + S}. And it looks like the proposed solution with concat is semantically the right one :-)
var max = new[]{0}
.Concat((From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.Max();
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
Using the logging module you can automatically add the current thread identifier in each log entry. Just use one of these LogRecord mapping keys in your logger format string:
%(thread)d : Thread ID (if available).
%(threadName)s : Thread name (if available).
and set up your default handler with it:
logging.basicConfig(format="%(threadName)s:%(message)s")
You can use the new URL for Google Maps: https://www.google.com/maps/@39.774769,-74.86084,18z equivalent to http://maps.google.com/?ll=39.774769,-74.86084.
39.774769 is the latitude and -74.86084 is longitude and 18z is 18 zoom level.
To prevent a long line of commands in a text file, I keep my copy-pase snippets like this:
echo a;\
echo b;\
echo c
You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm.
The idea is to have two references to the list and move them at different speeds. Move one forward by 1
node and the other by 2
nodes.
next
)
will become null
.Java function implementing the algorithm:
boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop either
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list
while(true) {
slow = slow.next; // 1 hop
if(fast.next != null)
fast = fast.next.next; // 2 hops
else
return false; // next node null => no loop
if(slow == null || fast == null) // if either hits null..no loop
return false;
if(slow == fast) // if the two ever meet...we must have a loop
return true;
}
}
Just in case someone from Blogger arrives, I had this problem when using Beautify
extension in VSCode. Don´t use it, don´t beautify
it.
Without an index, maintaining an autoincrement column becomes too expensive, that's why MySQL
requires an autoincrement column to be a leftmost part of an index.
You should remove the autoincrement property before dropping the key:
ALTER TABLE user_customer_permission MODIFY id INT NOT NULL;
ALTER TABLE user_customer_permission DROP PRIMARY KEY;
Note that you have a composite PRIMARY KEY
which covers all three columns and id
is not guaranteed to be unique.
If it happens to be unique, you can make it to be a PRIMARY KEY
and AUTO_INCREMENT
again:
ALTER TABLE user_customer_permission MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
You can use Ruby's Net::HTTP
class:
require 'net/http'
url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
I actually had the same problem.
when I run
mvn clean package
on my maven project, I get this certificate error by the maven tool.
I followed @Andy 's Answer till the point where I downloaded the .cer file
after that the rest of the answer didn't work for me but I did the following(I am running on Linux Debian machine)
first of all, run:
keytool -list -keystore "Java path+"/jre/lib/security/cacerts""
for example in my case it is:
keytool -list -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/security/cacerts
if it asks about the password, just hit enter.
this command is supposed to list all the ssl certificates accepted by the java. when I ran this command, in my case I got 93 certificates for example.
Now add the downloaded file .cer to the cacerts file by running the following command:
sudo keytool -importcert -file /home/hal/Public/certificate_file_downloaded.cer -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/security/cacerts
write your sudo password then it will ask you about the keystore password
the default one is changeit
then say y that you trust this certificate.
if you run the command
keytool -list -keystore /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/security/cacerts
once again, in my case, I got 94 contents of the cacerts file
it means, it was added successfully.
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):
import inspect
import functools
def memoize(fn):
cache = fn.cache = {}
@functools.wraps(fn)
def memoizer(*args, **kwargs):
kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
if key not in cache:
cache[key] = fn(**kwargs)
return cache[key]
return memoizer
Similar question: Identifying equivalent varargs function calls for memoization in Python
I know this topic is old but I think my answer can be useful for a lot of people.
Here is jQuery plugin made from Pointy's answer using ES6:
/**
* Sort values alphabetically in select
* source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
*/
$.fn.extend({
sortSelect() {
let options = this.find("option"),
arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => { // sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
});
Use is very easy
$("select").sortSelect();
Another graphical alternative - plot_missing
function from excellent DataExplorer
package:
Docs also points out to the fact that you can save this results for additional analysis with missing_data <- plot_missing(data)
.
What you can do is:
Update your local git repo:
git fetch
Build a local branch and checkout on it:
git branch pouet && git checkout pouet
Apply the commit you want on this branch:
git cherry-pick abcdefabcdef
(abcdefabcdef is the sha1 of the commit you want to apply)
msgbox ("Message goes here",0+16,"Title goes here")
if the user is supposed to make a decision the variable can be added like this.
variable=msgbox ("Message goes here",0+16,"Title goes here")
The numbers in the middle vary what the message box looks like. Here is the list
0 - ok button only
1 - ok and cancel
2 - abort, retry and ignore
3 - yes no and cancel
4 - yes and no
5 - retry and cancel
TO CHANGE THE SYMBOL (RIGHT NUMBER)
16 - critical message icon
32 - warning icon
48 - warning message
64 - info message
DEFAULT BUTTON
0 = vbDefaultButton1 - First button is default
256 = vbDefaultButton2 - Second button is default
512 = vbDefaultButton3 - Third button is default
768 = vbDefaultButton4 - Fourth button is default
SYSTEM MODAL
4096 = System modal, alert will be on top of all applications
Note: There are some extra numbers. You just have to add them to the numbers already there like
msgbox("Hello World", 0+16+0+4096)
from https://www.instructables.com/id/The-Ultimate-VBS-Tutorial/
You can use EventEmitter or observables to create an eventbus service that you register with DI. Every component that wants to participate just requests the service as constructor parameter and emits and/or subscribes to events.
See also
Simply use if statement
if(!isset($_SESSION))
{
session_start();
}
or
check the session status with session_status that Returns the current session status and if current session is already working then return with nothing else if session not working start the session
session_status() === PHP_SESSION_ACTIVE ?: session_start();
You can use:
\\
That's ok, for example:
if (invName.substring(j,k).equals("\\")) {
copyf=invName.substring(0,j);
}
open: function () {
var win = $(window);
$(this).parent().css({
position: 'absolute',
left: (win.width() - $(this).parent().outerWidth()) / 2,
top: (win.height() - $(this).parent().outerHeight()) / 2
});
}
You can use the -p
parameter, which is documented as:
-p, --parents
no error if existing, make parent directories as needed
So:
mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
You can use tool I've created specifically for this task:
https://github.com/sheerun/git-squash
Basically you need to call git squash master
and you're done
I run into this, it's an old question, but I want that file to be tracked but to not track it on certain working copies, to do that you can run
git update-index --assume-unchanged sites/default/settings.php
Another option is regex:
>>> import re
>>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
'Foobarbaz'
All,
Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.
step1. 1st stop your databases
service mysqld stop
step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"
vi /etc/my.cnf
[mysqld] skip-grant-tables
step3. 3rd start mysql
service mysqld start
step4. select mysql default database
mysql -u root
mysql>use mysql;
step4. set a new password
mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root'
;
step5 restart mysql database
service mysqld restart
mysql -u root -p
enjoy :)
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
Yes. It is possible for overridden methods to have different return type .
But the limitations are that the overridden method must have a return type that is more specific type of the return type of the actual method.
All the answers have given examples of the overridden method to have a return type which is a subclass of the return type of the actual method.
For example :
public class Foo{
//method which returns Foo
Foo getFoo(){
//your code
}
}
public class subFoo extends Foo{
//Overridden method which returns subclass of Foo
@Override
subFoo getFoo(){
//your code
}
}
But this is not only limited to subclass.Even classes that implement an interface are a specific type of the interface and thus can be a return type where the interface is expected.
For example :
public interface Foo{
//method which returns Foo
Foo getFoo();
}
public class Fizz implements Foo{
//Overridden method which returns Fizz(as it implements Foo)
@Override
Fizz getFoo(){
//your code
}
}
Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.
As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide
The collection comments
in your model class Topic
is lazily loaded, which is the default behaviour if you don't annotate it with fetch = FetchType.EAGER
specifically.
It is mostly likely that your findTopicByID
service is using a stateless Hibernate session. A stateless session does not have the first level cache, i.e., no persistence context. Later on when you try to iterate comments
, Hibernate will throw an exception.
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mvc3.model.Topic.comments, no session or session was closed
The solution can be:
Annotate comments
with fetch = FetchType.EAGER
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
If you still would like comments to be lazily loaded, use Hibernate's stateful sessions, so that you'll be able to fetch comments later on demand.
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
I had similar issue in Eclipse 3.6 with m2eclipse.
Could not calculate build plan: Failure to transfer org.apache.maven.plugins:maven-resources-plugin:jar:2.4.3 from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:jar:2.4.3 from central (http://repo1.maven.org/maven2): ConnectException project1 Unknown Maven Problem
Deleting all maven*.lastUpdated files from my local reository (as Deepak Joy suggested) solved that problem.
In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.
I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.
In Chart.js version 2.0 this is possible:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See axes labelling documentation for more details.
Here is an optimized version of npinti's answer:
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;
public class TextComponentLimit extends PlainDocument
{
private int charactersLimit;
private TextComponentLimit(int charactersLimit)
{
this.charactersLimit = charactersLimit;
}
@Override
public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
{
if (isAllowed(input))
{
super.insertString(offset, input, attributeSet);
} else
{
Toolkit.getDefaultToolkit().beep();
}
}
private boolean isAllowed(String string)
{
return (getLength() + string.length()) <= charactersLimit;
}
public static void addTo(JTextComponent textComponent, int charactersLimit)
{
TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
textComponent.setDocument(textFieldLimit);
}
}
To add a limit to your JTextComponent
, simply write the following line of code:
JTextFieldLimit.addTo(myTextField, myMaximumLength);
(This info is from The Git User's Manual)
I'm also learning, so this might not be exactly an answer to the question but it might help somebody:
git branch -r
)git fetch
. This will not effect any of you existing, custom created branches.git add origin /path/to/repository
) use git checkout origin/branch_name
, this will override your locals changes on branch branch_name
Make sure to create a static DataTable object and then use the following code:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
While @yydl gives a compelling reason on why the newInstance
method is better:
If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.
it's still quite possible to use a constructor. To see why this is, first we need to see why the above workaround is used by Android.
Before a fragment can be used, an instance is needed. Android calls YourFragment()
(the no arguments constructor) to construct an instance of the fragment. Here any overloaded constructor that you write will be ignored, as Android can't know which one to use.
In the lifetime of an Activity the fragment gets created as above and destroyed multiple times by Android. This means that if you put data in the fragment object itself, it will be lost once the fragment is destroyed.
To workaround, android asks that you store data using a Bundle
(calling setArguments()
), which can then be accessed from YourFragment
. Argument bundle
s are protected by Android, and hence are guaranteed to be persistent.
One way to set this bundle is by using a static newInstance
method:
public static YourFragment newInstance (int data) {
YourFragment yf = new YourFragment()
/* See this code gets executed immediately on your object construction */
Bundle args = new Bundle();
args.putInt("data", data);
yf.setArguments(args);
return yf;
}
However, a constructor:
public YourFragment(int data) {
Bundle args = new Bundle();
args.putInt("data", data);
setArguments(args);
}
can do exactly the same thing as the newInstance
method.
Naturally, this would fail, and is one of the reasons Android wants you to use the newInstance
method:
public YourFragment(int data) {
this.data = data; // Don't do this
}
As further explaination, here's Android's Fragment Class:
/**
* Supply the construction arguments for this fragment. This can only
* be called before the fragment has been attached to its activity; that
* is, you should call it immediately after constructing the fragment. The
* arguments supplied here will be retained across fragment destroy and
* creation.
*/
public void setArguments(Bundle args) {
if (mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
mArguments = args;
}
Note that Android asks that the arguments be set only at construction, and guarantees that these will be retained.
EDIT: As pointed out in the comments by @JHH, if you are providing a custom constructor that requires some arguments, then Java won't provide your fragment with a no arg default constructor. So this would require you to define a no arg constructor, which is code that you could avoid with the newInstance
factory method.
EDIT: Android doesn't allow using an overloaded constructor for fragments anymore. You must use the newInstance
method.
From what I can gather, the model doesn't want to guess whether checked = true or false, I got around this by setting a value attribute on the checkbox element with jQuery before submitting the form like this:
$('input[type="checkbox"]').each(function () {
$(this).attr('value', $(this).is(':checked'));
});
This way, you don't need a hidden element just to store the value of the checkbox.
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); return des.data.Count.ToString();
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
nothing
. This can be used to provide optional arguments.string s = &str1 + &str2;
using pointers. void f(const T& t); ... f(T(a, b, c));
, pointers cannot be used like that since you cannot take the address of a temporary.There Are few steps to set the path
1:goto this "https://github.com/UB-Mannheim/tesseract/wiki"
2:download the latest installers
3:install it
4: set the path in system variables such as "C:\Program Files\Tesseract-OCR" or "C:\ProgramFiles (x86)\Tesseract-OCR"
5 : open CMD type "tesseract" and some output except "not regonized type errors"
multiprocessing is not like threading. Each child process will get a copy of the main process's memory. Generally state is shared via communication (pipes/sockets), signals, or shared memory.
Multiprocessing makes some abstractions available for your use case - shared state that's treated as local by use of proxies or shared memory: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes
Relevant sections:
Here is my solution: a combination of the working ones below.
var checkInput = function(e) {
if (!e) {
e = window.event;
}
var code = e.keyCode || e.which;
if (!e.ctrlKey) {
//46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
return true;
//35..39 - home, end, left, right
if (code >= 35 && code <= 39)
return true;
//numpad numbers
if (code >= 96 && code <= 105)
return true;
//keyboard numbers
if (isNaN(parseInt(String.fromCharCode(code), 10))) {
e.preventDefault();
return false;
}
}
return true;
};
The usual way to do this in PHP is to put id[]
in your URL instead of just id
:
http://link/foo.php?id[]=1&id[]=2&id[]=3
Then $_GET['id']
will be an array of those values. It's not especially pretty, but it works out of the box.
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
This one I found simple solutions:
row = myArray.map((cell, i) => {
if (i == myArray.length - 1) {
return <div> Test Data 1</div>;
}
return <div> Test Data 2</div>;
});
Internet Explorer 9 support MPEG4 using H.264 codec. But it also required that the file can start to play as soon as it starts downloading.
Here are the very basic steps on how to make a MPEG file that works in IE9 (using avconv on Ubuntu). I spent many hours to figure that out, so I hope that it can help someone else.
Convert the video to MPEG4 using H.264 codec. You don't need anything fancy, just let avconv do the job for you:
avconv -i video.mp4 -vcodec libx264 pre_out.mp4
This video will works on all browsers that support MPEG4, except IE9. To add support for IE9, you have to move the file info to the file header, so the browser can start playing it as soon as it starts to download it. THIS IS THE KEY FOR IE9!!!
qt-faststart pre_out.mp4 out.mp4
qt-faststart
is a Quicktime utilities that also support H.264/ACC file format. It is part of libav-tools
package.
You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).
For instance :
System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK // API Level
android.os.Build.DEVICE // Device
android.os.Build.MODEL // Model
android.os.Build.PRODUCT // Product
Etc...
how did you install easy_install/pip? make sure that you installed it for the upgraded version of python. what could have happened here is that the old (default) python install might be linked to your pip install. you might wanna try running the default version and importing the newly installed modules.
try this one ,
n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
a=raw_input()
if(a.isdigit()):
l1.insert(i,float(a)) #statement1
else:
l1.insert(i,a) #statement2
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
If you apply static keyword with any method, it is known as static method.
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111 Indian BBDIT 222 American BBDIT 333 China BBDIT
Unfortunately in Windows, It is not possible. The only way out is to exit and type cls and then again open mySQL
In my case i restart php for and it become ok.
The easiest way to do this now is with a flexbox:
http://css-tricks.com/snippets/css/a-guide-to-flexbox/
The CSS is then simply:
#container {
display: flex;
justify-content: space-between;
}
demo: http://jsfiddle.net/QPrk3/
However, this is currently only supported by relatively recent browsers (http://caniuse.com/flexbox). Also, the spec for flexbox layout has changed a few times, so it's possible to cover more browsers by additionally including an older syntax:
Try accessing a static file. If this is not working either then go to all directories from the root "/" or "c:\" to the directory of your file and check if they contain ".htaccess" files.
I once left a file in "c:\" and it had the most strange results.
Maybe this example listed here can help you out. Statement from the author
about 24 lines of code to encrypt, 23 to decrypt
Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Utilities.Encryption
{
/// <summary>
/// Utility class that handles encryption
/// </summary>
public static class AESEncryption
{
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="PlainText">Text to be encrypted</param>
/// <param name="Password">Password to encrypt with</param>
/// <param name="Salt">Salt to encrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public static string Encrypt(string PlainText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="CipherText">Text to be decrypted</param>
/// <param name="Password">Password to decrypt with</param>
/// <param name="Salt">Salt to decrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public static string Decrypt(string CipherText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(CipherText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
#endregion
}
}
There is also another convention, used by many open source projects including Spring.
interface User {
}
class DefaultUser implements User {
}
class AnotherClassOfUser implements User {
}
I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.