You can simply use:
ps -o args= -f -p ProcessPid
I have also met this issue and wasted a lot of time debugging it.
First, make sure that the path you provide is valid, i.e., there is an image in that path.
Next, you should be aware that Opencv doesn't support image paths which contain unicode characters (see ref). If your image path contains Unicode characters, you can use the following code to read the image:
import numpy as np
import cv2
# img is in BGR format if the underlying image is a color image
img = cv2.imdecode(np.fromfile(im_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
As others have mentioned, myCoolDiv
is a child of markerDiv
not playerContainer
. If you want to remove myCoolDiv
but keep markerDiv
for some reason you can do the following
myCoolDiv.parentNode.removeChild(myCoolDiv);
You may need free up some space from root (/) partition. Stop mysql process by:
/etc/init.d/mysql stop
Delete an unused database from mySql by command:
rm -rf [Database-Directory]
Execute it in /var/lib/mysql
. Now if you run df -h
, you may confused by still full space. For removing the unused database 's directory to be affected, you need to kill processes are using current directory/partition.
Stopping mysql_safe
or mysqld_safe
and then mysqld
:
ps -A
Then find mysql's process number (e.g. 2234). Then execute:
kill 2234
Now start again mysql:
/etc/init.d/mysql start
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.
On SPARC at least, you have psrinfo
to show you processor information, which run on its own will show you the number of CPU
s the machine sees. psrinfo -p
shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.
prtdiag
will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag
, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.
I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:
UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)
It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know)
Yes it is. Here are the implementations and instructions for the various JPA 2.0 implementations:
org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
org.apache.openjpa.persistence.meta.AnnotationProcessor6
org.datanucleus.jpa.JPACriteriaProcessor
The latest Hibernate implementation is available at:
An older Hibernate implementation is at:
This will work
select * from table
where (id,point) IN (select id,min(point) from table group by id);
Another simple directive could be like:
var appModule = angular.module("appModule", []);
appModule.directive("checkList", [function () {
return {
restrict: "A",
scope: {
selectedItemsArray: "=",
value: "@"
},
link: function (scope, elem) {
scope.$watchCollection("selectedItemsArray", function (newValue) {
if (_.contains(newValue, scope.value)) {
elem.prop("checked", true);
} else {
elem.prop("checked", false);
}
});
if (_.contains(scope.selectedItemsArray, scope.value)) {
elem.prop("checked", true);
}
elem.on("change", function () {
if (elem.prop("checked")) {
if (!_.contains(scope.selectedItemsArray, scope.value)) {
scope.$apply(
function () {
scope.selectedItemsArray.push(scope.value);
}
);
}
} else {
if (_.contains(scope.selectedItemsArray, scope.value)) {
var index = scope.selectedItemsArray.indexOf(scope.value);
scope.$apply(
function () {
scope.selectedItemsArray.splice(index, 1);
});
}
}
console.log(scope.selectedItemsArray);
});
}
};
}]);
The controller:
appModule.controller("sampleController", ["$scope",
function ($scope) {
//#region "Scope Members"
$scope.sourceArray = [{ id: 1, text: "val1" }, { id: 2, text: "val2" }];
$scope.selectedItems = ["1"];
//#endregion
$scope.selectAll = function () {
$scope.selectedItems = ["1", "2"];
};
$scope.unCheckAll = function () {
$scope.selectedItems = [];
};
}]);
And the HTML:
<ul class="list-unstyled filter-list">
<li data-ng-repeat="item in sourceArray">
<div class="checkbox">
<label>
<input type="checkbox" check-list selected-items-array="selectedItems" value="{{item.id}}">
{{item.text}}
</label>
</div>
</li>
I'm also including a Plunker: http://plnkr.co/edit/XnFtyij4ed6RyFwnFN6V?p=preview
on Mac edit .bash_profile use code or vim
code ~/.bash_profile
export ANDROID_SDK_ROOT=~/Library/Android/sdk
export ANDROID_HOME=~/Library/Android/sdk
It could be a security access on your machine, are you running Pageant (which is a putty agent)?
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
for decreasing order for integer array of 2 dimension you can use
Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order
Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]);//decreasing order
I think most people want their placeholder text to be in grey and appear only once, so this is what I did:
Set your color in viewDidLoad()
(not in IB)
commentsTextView.textColor = UIColor.darkGray
Implement UITextViewDelegate
to your controller
add function to your controller
func textViewDidBeginEditing(_ textView: UITextView) {
if (commentsTextView.textColor == UIColor.darkGray) {
commentsTextView.text = ""
commentsTextView.textColor = UIColor.black
}
}
This solution is simple.
It is certain that you can not do it through Ajax call.
However, there is a workaround.
Steps :
If you are using form.submit() for downloading the file, what you can do is :
This is helpful in case when you want to decide whether or not file needs to be downloaded after making form.submit(), eg: there can be a case where on form.submit(), an exception occurs on the server side and instead of crashing, you might need to show a custom message on the client side, in such case this implementation might help.
OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp
tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the ftp
program, containing instructions for it. Name it as you want, and put into it:
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
The first line opens a connection to the ftp server at ftp.myftpsite.com
. The two following lines specify the login, and the password which ftp will ask for (replace login
and pass
with just the login and password, without any keywords). Then, you use mget *
to get all files. Instead of the *
, you can use any wildcard. Finally, you use quit
to close the ftp
program without interactive prompt.
If you needed to enter some directory first, add a cd
command before mget
. It should be pretty straightforward.
Finally, write that file and run ftp
like this:
ftp -i -s:yourscript
where -i
disables interactivity (asking before downloading files), and -s
specifies path to the script you created.
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp
which is practically the PuTTy counter-part of the openssh scp
command.
The syntax is similar to copy
command, and it supports wildcards:
pscp -batch [email protected]:iiumlabs* .
If you authenticate using a key file, you should pass it using -i path-to-key-file
. If you use password, -pw pass
. It can also reuse sessions saved using PuTTy, using the load -load your-session-name
argument.
q = request.GET.get("q", None)
if q:
message = 'q= %s' % q
else:
message = 'Empty'
If you're using SQLite version 3.3+ you can easily create a table with:
create table if not exists TableName (col1 typ1, ..., colN typN)
In the same way, you can remove a table only if it exists by using:
drop table if exists TableName
To even do better boolean mapping to Y/N, add to your hibernate configuration:
<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>
Now you can use booleans in HQL, for example:
"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"
A similar option in Sublime Text is the built in Edit->Line->Reindent
. You can put this code in Preferences -> Key Bindings User
:
{ "keys": ["alt+shift+f"], "command": "reindent"}
I use alt+shift+f because I'm a Netbeans user.
To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.
Or if you don't want to select all before formatting, add an argument to the command instead:
{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }
(as per comment by @Supr below)
O(1): finding the best next move in Chess (or Go for that matter). As the number of game states is finite it's only O(1) :-)
I have had this EXACT problem with VS2010 Professional Trial / Evaluation download. I can provide clear and concise steps to reproduce:
In my case, the resolution was quite simple - set the clock back ahead to the wrong date. The next day, I was able to set the clock back to the correct date and continue using the product.
Based on other answers to this question, it would appear there are numerous reasons that you could receive this message. This specific issue is most likely to be encountered by someone with a "virgin" install of Windows since it is not so difficult to set the clock incorrectly when setting up a new computer and then fix it later (and if you fix the clock hours after installing the product, it might be hard to put it all together and realize what happened).
Hope this helps someone else.
You can use like
:
"12-18" -like "*-*"
Or split
for contains
:
"12-18" -split "" -contains "-"
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
I had the same problem, I then realized that I was still running Network Conditioner on "Very Bad Network". Turning that off solved the issue.
Hope that helps someone.
Demo:
In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))
In [256]: df
Out[256]:
a b c d e f
0 0.823638 0.767999 0.460358 0.034578 0.592420 0.776803
1 0.344320 0.754412 0.274944 0.545039 0.031752 0.784564
2 0.238826 0.610893 0.861127 0.189441 0.294646 0.557034
3 0.478562 0.571750 0.116209 0.534039 0.869545 0.855520
4 0.130601 0.678583 0.157052 0.899672 0.093976 0.268974
In [257]: dfs = np.split(df, [4], axis=1)
In [258]: dfs[0]
Out[258]:
a b c d
0 0.823638 0.767999 0.460358 0.034578
1 0.344320 0.754412 0.274944 0.545039
2 0.238826 0.610893 0.861127 0.189441
3 0.478562 0.571750 0.116209 0.534039
4 0.130601 0.678583 0.157052 0.899672
In [259]: dfs[1]
Out[259]:
e f
0 0.592420 0.776803
1 0.031752 0.784564
2 0.294646 0.557034
3 0.869545 0.855520
4 0.093976 0.268974
np.split()
is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]
:
In [260]: dfs = np.split(df, [2,3], axis=1)
In [261]: dfs[0]
Out[261]:
a b
0 0.823638 0.767999
1 0.344320 0.754412
2 0.238826 0.610893
3 0.478562 0.571750
4 0.130601 0.678583
In [262]: dfs[1]
Out[262]:
c
0 0.460358
1 0.274944
2 0.861127
3 0.116209
4 0.157052
In [263]: dfs[2]
Out[263]:
d e f
0 0.034578 0.592420 0.776803
1 0.545039 0.031752 0.784564
2 0.189441 0.294646 0.557034
3 0.534039 0.869545 0.855520
4 0.899672 0.093976 0.268974
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
$(document).ready(function() {
$("#gate option[value='Gateway 2']").prop('selected', true);
// you need to specify id of combo to set right combo, if more than one combo
});
I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.
just create additional User_Seq
table:
with two fields: id Uniq index
and SeqVal nvarchar(1)
and create next SP, and generated ID value from this SP and put to new User row!
CREATE procedure [dbo].[User_NextValue]
as
begin
set NOCOUNT ON
declare @existingId int = (select isnull(max(UserId)+1, 0) from dbo.User)
insert into User_Seq (SeqVal) values ('a')
declare @NewSeqValue int = scope_identity()
if @existingId > @NewSeqValue
begin
set identity_insert User_Seq on
insert into User_Seq (SeqID) values (@existingId)
set @NewSeqValue = scope_identity()
end
delete from User_Seq WITH (READPAST)
return @NewSeqValue
end
JSONObject showing error please use
JsonObject paramObject = new JsonObject(); paramObject.addProperty("loginId", vMobile_Email);
@Günter's answer is correct. I just wanted to propose yet another method.
You could also add the host-binding inside the @Component()
-decorator. You can put the event and desired function call in the host-metadata-property like so:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
host: {
'(window:resize)': 'onResize($event)'
}
})
export class AppComponent{
onResize(event){
event.target.innerWidth; // window width
}
}
If you are using a mac you can use the following terminal command:
open -a Google\ Chrome --args --allow-file-access-from-files
Just add:
namespace System.IO
{
public static class FileInfoExtensions
{
public static void Rename(this FileInfo fileInfo, string newName)
{
fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
}
}
}
And then...
FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
System.Int32.MaxValue
Assuming you mean System.Array
, ie. any normally defined array (int[]
, etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.
This limit is enforced because System.Array
uses an Int32
as it's indexer, hence only valid values for an Int32
can be used. On top of this, only positive values (ie, >= 0
) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32
, which is available in Int32.MaxValue
and is equivalent to 2^31, or roughly 2 billion.
On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T>
instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T>
or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.
The other collection of note is Dictionary<int, T>
which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:
Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);
Using Dictionary
also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>
, which will provide more potential elements than you could possible think about.
The problem is the TypeError
gets raised 'before' assertRaises
gets called since the arguments to assertRaises
need to be evaluated before the method can be called. You need to pass a lambda
expression like:
self.assertRaises(TypeError, lambda: self.testListNone[:1])
I wrote a pure java mp3 player: mp3transform.
I'm late to the party, here is an Excel VBA script I wrote years ago for Australia. It can be easily modified to support other Countries. I've made a GitHub repository of the C# code here. I've hosted it on my site and you can download it here: http://jeremythompson.net/rocks/ParseAddress.xlsm
For any country with a PostCode that's numeric or can be matched with a RegEx my strategy works very well:
First we detect the First and Surname which are assumed to be the top line. Its easy to skip the name and start with the address by unticking the checkbox (called 'Name is top row' as shown below).
Next its safe to expect the Address consisting of the Street and Number come before the Suburb and the St, Pde, Ave, Av, Rd, Cres, loop, etc is a separator.
Detecting the Suburb vs the State and even Country can trick the most sophisticated parsers as there can be conflicts. To overcome this I use a PostCode look up based on the fact that after stripping Street and Apartment/Unit numbers as well as the PoBox,Ph,Fax,Mobile etc, only the PostCode number will remain. This is easy to match with a regEx to then look up the suburb(s) and country.
Your National Post Office Service will provide a list of post codes with Suburbs and States free of charge that you can store in an excel sheet, db table, text/json/xml file, etc.
DISCLAIMER, I know this code is not perfect, or even written well however its very easy to convert to any programming language and run in any type of application.The strategy is the answer depending on your country and rules, take this code as an example:
Option Explicit
Private Const TopRow As Integer = 0
Public Sub ParseAddress()
Dim strArr() As String
Dim sigRow() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Stat As String
Dim SpaceInName As Integer
Dim Temp As String
Dim PhExt As String
On Error Resume Next
Temp = ActiveSheet.Range("Address")
'Split info into array
strArr = Split(Temp, vbLf)
'Trim the array
For i = 0 To UBound(strArr)
strArr(i) = VBA.Trim(strArr(i))
Next i
'Remove empty items/rows
ReDim sigRow(LBound(strArr) To UBound(strArr))
For i = LBound(strArr) To UBound(strArr)
If Trim(strArr(i)) <> "" Then
sigRow(j) = strArr(i)
j = j + 1
End If
Next i
ReDim Preserve sigRow(LBound(strArr) To j)
'Find the name (MUST BE ON THE FIRST ROW UNLESS CHECKBOX UNTICKED)
i = TopRow
If ActiveSheet.Shapes("chkFirst").ControlFormat.Value = 1 Then
SpaceInName = InStr(1, sigRow(i), " ", vbTextCompare) - 1
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
Else
If MsgBox("First Name: " & VBA.Mid$(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
End If
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
Else
If MsgBox("Surame: " & VBA.Mid(sigRow(i), SpaceInName + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
End If
sigRow(i) = ""
End If
'Find the Street by looking for a "St, Pde, Ave, Av, Rd, Cres, loop, etc"
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 8
If InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) > 0 Then
'Find the position of the street in order to get the suburb
SpaceInName = InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) + Len(Street(j)) - 1
'If its a po box then add 5 chars
If VBA.Right(Street(j), 3) = "BOX" Then SpaceInName = SpaceInName + 5
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
Else
If MsgBox("Street Address: " & VBA.Mid(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
End If
'Trim the Street, Number leaving the Suburb if its exists on the same line
sigRow(i) = VBA.Mid(sigRow(i), SpaceInName) + 2
sigRow(i) = Replace(sigRow(i), VBA.Mid(sigRow(i), 1, SpaceInName), "")
GoTo PastAddress:
End If
Next j
End If
Next i
PastAddress:
'Mobile
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 3
Temp = Mb(j)
If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
Else
If MsgBox("Mobile: " & VBA.Mid(sigRow(i), Len(Temp) + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
End If
sigRow(i) = ""
GoTo PastMobile:
End If
Next j
End If
Next i
PastMobile:
'Phone
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 1
Temp = Ph(j)
If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
'TODO: Detect the intl or national extension here.. or if we can from the postcode.
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
Else
If MsgBox("Phone: " & VBA.Mid(sigRow(i), Len(Temp) + 3), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
End If
sigRow(i) = ""
GoTo PastPhone:
End If
Next j
End If
Next i
PastPhone:
'Email
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
'replace with regEx search
If InStr(1, sigRow(i), "@", vbTextCompare) And InStr(1, VBA.UCase(sigRow(i)), ".CO", vbTextCompare) Then
Dim email As String
email = sigRow(i)
email = Replace(VBA.UCase(email), "EMAIL:", "")
email = Replace(VBA.UCase(email), "E-MAIL:", "")
email = Replace(VBA.UCase(email), "E:", "")
email = Replace(VBA.UCase(Trim(email)), "E ", "")
email = VBA.LCase(email)
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Email") = email
Else
If MsgBox("Email: " & email, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Email") = email
End If
sigRow(i) = ""
Exit For
End If
End If
Next i
'Now the only remaining items will be the postcode, suburb, country
'there shouldn't be any numbers (eg. from PoBox,Ph,Fax,Mobile) except for the Post Code
'Join the string and filter out the Post Code
Temp = Join(sigRow, vbCrLf)
Temp = Trim(Temp)
For i = 1 To Len(Temp)
Dim postCode As String
postCode = VBA.Mid(Temp, i, 4)
'In Australia PostCodes are 4 digits
If VBA.Mid(Temp, i, 1) <> " " And IsNumeric(postCode) Then
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("PostCode") = postCode
Else
If MsgBox("Post Code: " & postCode, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("PostCode") = postCode
End If
'Lookup the Suburb and State based on the PostCode, the PostCode sheet has the lookup
Dim mySuburbArray As Range
Set mySuburbArray = Sheets("PostCodes").Range("A2:B16670")
Dim suburbs As String
For j = 1 To mySuburbArray.Columns(1).Cells.Count
If mySuburbArray.Cells(j, 1) = postCode Then
'Check if the suburb is listed in the address
If InStr(1, UCase(Temp), mySuburbArray.Cells(j, 2), vbTextCompare) > 0 Then
'Set the Suburb and State
ActiveSheet.Range("Suburb") = mySuburbArray.Cells(j, 2)
Stat = mySuburbArray.Cells(j, 3)
ActiveSheet.Range("State") = Stat
'Knowing the State - for Australia we can get the telephone Ext
PhExt = PhExtension(VBA.UCase(Stat))
ActiveSheet.Range("PhExt") = PhExt
'remove the phone extension from the number
Dim prePhone As String
prePhone = ActiveSheet.Range("Phone")
prePhone = Replace(prePhone, PhExt & " ", "")
prePhone = Replace(prePhone, "(" & PhExt & ") ", "")
prePhone = Replace(prePhone, "(" & PhExt & ")", "")
ActiveSheet.Range("Phone") = prePhone
Exit For
End If
End If
Next j
Exit For
End If
Next i
End Sub
Private Function PhExtension(ByVal State As String) As String
Select Case State
Case Is = "NSW"
PhExtension = "02"
Case Is = "QLD"
PhExtension = "07"
Case Is = "VIC"
PhExtension = "03"
Case Is = "NT"
PhExtension = "04"
Case Is = "WA"
PhExtension = "05"
Case Is = "SA"
PhExtension = "07"
Case Is = "TAS"
PhExtension = "06"
End Select
End Function
Private Function Ph(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Ph = "PH"
Case Is = 1
Ph = "PHONE"
'Case Is = 2
'Ph = "P"
End Select
End Function
Private Function Mb(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Mb = "MB"
Case Is = 1
Mb = "MOB"
Case Is = 2
Mb = "CELL"
Case Is = 3
Mb = "MOBILE"
'Case Is = 4
'Mb = "M"
End Select
End Function
Private Function Fax(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Fax = "FAX"
Case Is = 1
Fax = "FACSIMILE"
'Case Is = 2
'Fax = "F"
End Select
End Function
Private Function State(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
State = "NSW"
Case Is = 1
State = "QLD"
Case Is = 2
State = "VIC"
Case Is = 3
State = "NT"
Case Is = 4
State = "WA"
Case Is = 5
State = "SA"
Case Is = 6
State = "TAS"
End Select
End Function
Private Function Street(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Street = " ST"
Case Is = 1
Street = " RD"
Case Is = 2
Street = " AVE"
Case Is = 3
Street = " AV"
Case Is = 4
Street = " CRES"
Case Is = 5
Street = " LOOP"
Case Is = 6
Street = "PO BOX"
Case Is = 7
Street = " STREET"
Case Is = 8
Street = " ROAD"
Case Is = 9
Street = " AVENUE"
Case Is = 10
Street = " CRESENT"
Case Is = 11
Street = " PARADE"
Case Is = 12
Street = " PDE"
Case Is = 13
Street = " LANE"
Case Is = 14
Street = " COURT"
Case Is = 15
Street = " BLVD"
Case Is = 16
Street = "P.O. BOX"
Case Is = 17
Street = "P.O BOX"
Case Is = 18
Street = "PO BOX"
Case Is = 19
Street = "POBOX"
End Select
End Function
You could try this:
#include <stdio.h>
int main()
{
int i,j;
int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d ", my_array[i][j]);
}
printf("\n");
}
return 0;
}
Assuming that your implementation meaningfully supports SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file
You can use stat
(if you know the filename), or fstat
(if you have the file descriptor).
Here is an example for stat:
#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;
You can use GetFileSize or GetFileSizeEx.
SELECT ... INTO ...
only works if the table specified in the INTO clause does not exist - otherwise, you have to use:
INSERT INTO dbo.TABLETWO
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO
(col1, col2)
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
You can use itertools.repeat
with operator.methodcaller
to call the __call__
method of the function N times. Here is an example of a generator function doing it:
from itertools import repeat
from operator import methodcaller
def call_n_times(function, n):
yield from map(methodcaller('__call__'), repeat(function, n))
Example of usage:
import random
from functools import partial
throw_dice = partial(random.randint, 1, 6)
result = call_n_times(throw_dice, 10)
print(list(result))
# [6, 3, 1, 2, 4, 6, 4, 1, 4, 6]
The standard way to do this is as follows:
Provide:
and get in return a Integer between min and max, inclusive.
Random rand = new Random();
// nextInt as provided by Random is exclusive of the top value so you need to add 1
int randomNum = rand.nextInt((max - min) + 1) + min;
See the relevant JavaDoc.
As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.
I was fetching a windows-1252 encoded file via cURL and the mb_detect_encoding(curl_exec($ch));
returned UTF-8. Tried utf8_encode(curl_exec($ch));
and the characters were correct.
stdbool.h
defines macros true
and false
, but remember they are defined to be 1 and 0.
That is why sizeof(true)
is 4.
An example of direct String
usage since 1.7 may be shown as well:
public static void main(String[] args) {
switch (args[0]) {
case "Monday":
case "Tuesday":
case "Wednesday":
System.out.println("boring");
break;
case "Thursday":
System.out.println("getting better");
case "Friday":
case "Saturday":
case "Sunday":
System.out.println("much better");
break;
}
}
Simpliest way for my opinion
var web = new WebClient();
var url = $"{hostname}/LoadDataSync?systemID={systemId}";
var responseString = web.DownloadString(url);
OR
var bytes = web.DownloadData(url);
You can have a unique file name automatically generated for you without any custom methods. Just use the following with the StorageFolder Class or the StorageFile Class. The key here is: CreationCollisionOption.GenerateUniqueName
and NameCollisionOption.GenerateUniqueName
To create a new file with a unique filename:
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myfile.txt", NameCollisionOption.GenerateUniqueName);
To copy a file to a location with a unique filename:
var myFile2 = await myFile1.CopyAsync(ApplicationData.Current.LocalFolder, myFile1.Name, NameCollisionOption.GenerateUniqueName);
To move a file with a unique filename in the destination location:
await myFile.MoveAsync(ApplicationData.Current.LocalFolder, myFile.Name, NameCollisionOption.GenerateUniqueName);
To rename a file with a unique filename in the destination location:
await myFile.RenameAsync(myFile.Name, NameCollisionOption.GenerateUniqueName);
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
I've managed to launch and debug an Android testing application on the Android emulator through Delphi.
I have Windows 7 64 bit, 4GB RAM, a dual core processor at 3GHz and Delphi XE 5.
Below is a link that I've prepared in a hurry for my colleagues at work but I will make it better by the first chance:
Debug Android Apps with Delphi
Forgive my English language but I am not a native English speaker. I hope you will find this small tutorial
For those who use Tomcat with Bitronix, this will fix the problem:
The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.
In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:
(if you already used them, make sure your references are correct):
e.g.
-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59"
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties"
Now, restart your server and check the log.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.
But consider such code (it is for a REST controller):
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
return $this->doGet($request, $object);
case 'POST':
return $this->doPost($request, $object);
case 'PUT':
return $this->doPut($request, $object);
case 'DELETE':
return $this->doDelete($request, $object);
default:
return $this->onBadRequest();
}
It would not be very useful to apply sanitizing here (although it would not break anything, either).
So, follow recommendations, but not blindly - rather understand why they are for :)
Regex can also be good and be used effectively (Replaces all UTF-8 characters not covered in ISO-8859-1
with space):
String input = "€Tes¶ti©ng [§] al€l o€f i¶t _ - À ÆÑ with some 9umbers as"
+ " w2921**#$%!@# well Ü, or ü, is a chaŒracte?";
String output = input.replaceAll("[^\\u0020-\\u007e\\u00a0-\\u00ff]", " ");
System.out.println("Input = " + input);
System.out.println("Output = " + output);
String s=null;
String is not initialized for null. if any string operation tried it can throw null pointer exception
String t="null";
It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.
String u="";
It is as empty string , It will not throw null pointer.
In my case, it wasn't until I PAUSEd the batch file and scrolled up a bit, that wasn't the only error I had gotten. My DROP
command had become DROP
and so the table wasn't dropping in the first place (thus the relation did indeed still exist). The 
I've learned is called a Byte Order Mark (BOM). Opening this in Notepad++, re-save the SQL file with Encoding set to UTM-8 without BOM and it runs fine.
Use collections.Counter
:
>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
Counters are basically a subclass of dict
, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.
char c = '5'
A char
(1 byte) is allocated on stack at address 0x12345678
.
char *d = &c;
You obtain the address of c
and store it in d
, so d = 0x12345678
.
int *e = (int*)d;
You force the compiler to assume that 0x12345678
points to an int
, but an int is not just one byte (sizeof(char) != sizeof(int)
). It may be 4 or 8 bytes according to the architecture or even other values.
So when you print the value of the pointer, the integer is considered by taking the first byte (that was c
) and other consecutive bytes which are on stack and that are just garbage for your intent.
In my case, issue was occured even after all these configurations have done (@Pekka has mentioned changes in httpd.conf & .htaccess files). It was resolved only after I add
<Directory "project/path">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
to virtual host configuration in vhost file
Edit on 29/09/2017 (For Apache 2.4 <) Refer this answer
<VirtualHost dropbox.local:80>
DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
ServerName dropbox.local
ErrorLog "logs/dropbox.local-error.log"
CustomLog "logs/dropbox.local-access.log" combined
<Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
# AllowOverride All # Deprecated
# Order Allow,Deny # Deprecated
# Allow from all # Deprecated
# --New way of doing it
Require all granted
</Directory>
Another thing you could do is to create a session variable that gets set in the code behind and then check the state of that variable and then run your javascript. The good thing is this will allow you to run your script right where you want to instead of having to figure out if you want it to run in the DOM or globally.
Something like this: Code behind:
Session["newuser"] = "false"
In javascript
var newuser = '<%=Session["newuser"]%>';
if (newuser == "yes")
startTutorial();
DataFrame.to_dict()
converts DataFrame to dictionary.
Example
>>> df = pd.DataFrame(
{'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
col1 col2
a 1 0.1
b 2 0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
See this Documentation for details
Windows 64 bit, JDK 64 bit (Solution that worked for me) Tried all the above solutions, None of them worked, I have been trying to solve it from past few days and now i done it successfully.For me the problem was, when i first installed Android Studio my JDK version was 1.7, then after installing i updated the JDK to 1.8,then i removed old JDK folder and everything was messed up, even uninstalling and reinstalling android studio randomly didn't solved the issue.
Below is the solution that worked for me
1) Uninstall Android Studio.
2) clean temp files and android studio C:\Users\Username.AndroidStudio1.5
3) Uninstall JDK.
4) Now without JDK try to install Android Studio and now it will show message that it cant find any JDK. Stop installation
5) Install JDK 1.7 or 1.8 (Set JAVA_HOME,JDK_HOME,path Environment variables as explained by everybody above)
6) Install Android Studio.
7) Done. Enjoy and happy coding.
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
Have got the same error as in header because of failed attempt to compile my project with java 8 and then reattempting to compile with java 6. Some classes where compiled at the first attempt with 8 and did not recompile with 6. Mixed classes did not compile then. Cleaning project solved the problem. This answer is not strictly relevant to the question, but could be useful for someone.
http://wiki.answers.com/Q/Does_Google_Chrome_support_ActiveX
Google Chrome comes with an ActiveX shim, as part of its default plugin array. So Google Chrome features at least partial support for ActiveX controls (as do many non-Internet Explorer browsers). I can't find information as to whether or not this includes support for ActiveX security certificates or the like, nor if/where such plugins can be controlled, within the browser.
..... Note that to enable the plug-in you must run Chrome with the following switch " --allow-all-activex" So in shortcut that is used to start up Chrome, add this after "Chrome.exe"
Technically, there's no built-in command to edit an existing symbolic link. It can be easily achieved with a few short commands.
Here's a little bash/zsh function I wrote to update an existing symbolic link:
# -----------------------------------------
# Edit an existing symbolic link
#
# @1 = Name of symbolic link to edit
# @2 = Full destination path to update existing symlink with
# -----------------------------------------
function edit-symlink () {
if [ -z "$1" ]; then
echo "Name of symbolic link you would like to edit:"
read LINK
else
LINK="$1"
fi
LINKTMP="$LINK-tmp"
if [ -z "$2" ]; then
echo "Full destination path to update existing symlink with:"
read DEST
else
DEST="$2"
fi
ln -s $DEST $LINKTMP
rm $LINK
mv $LINKTMP $LINK
printf "Updated $LINK to point to new destination -> $DEST"
}
You can also do like this:
- command: "{{ item }}"
args:
chdir: "/src/package/"
with_items:
- "./configure"
- "/usr/bin/make"
- "/usr/bin/make install"
Hope that might help other
>>> l = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in l if l.count(x) > 1])
set([1, 4, 5])
By changing runProguard to minifyEnabled, part of the issue gets fixed.
But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").
By removing application Id in the build.gradle file, you should be good to go.
You just need to provide object reference . Please provide your class name in the position.
private static void data2()
{
<classname> c1 = new <classname>();
c1. data1();
}
At my previous job we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.
After a lot of googling and reflector usage I came across the WM_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.
This is a very very simple class demonstrating how to use this message:
class DrawingControl
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
}
There are fuller discussions on this - google for C# and WM_SETREDRAW, e.g.
And to whom it may concern, this is similar example in VB:
Public Module Extensions
<DllImport("user32.dll")>
Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
End Function
Private Const WM_SETREDRAW As Integer = 11
' Extension methods for Control
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
SendMessage(Target.Handle, WM_SETREDRAW, True, 0)
If Redraw Then
Target.Refresh()
End If
End Sub
<Extension()>
Public Sub SuspendDrawing(ByVal Target As Control)
SendMessage(Target.Handle, WM_SETREDRAW, False, 0)
End Sub
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control)
ResumeDrawing(Target, True)
End Sub
End Module
Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)
Greetings mic enter image description here
What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &
) aren't called using actual addresses, i.e. &a
.
The simple answer is that declaring a function as pass-by-reference:
void foo(int& x);
is all we need. It's then passed by reference automatically.
You now call this function like so:
int y = 5;
foo(y);
and y
will be passed by reference.
You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy* param);
};
int CDummy::isitme (CDummy* param)
{
if (param == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a; // assigning address of a to b
if ( b->isitme(&a) ) // Called with &a (address of a) instead of a
cout << "yes, &a is b";
return 0;
}
Output:
yes, &a is b
Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.
You can do this with 1 line of code:
$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);
If you're using jQuery you don't need setTimeout, at least not to autohide an element.
I prefer case objects
(it's a matter of personal preference). To cope with the problems inherent to that approach (parse string and iterate over all elements), I've added a few lines that are not perfect, but are effective.
I'm pasting you the code here expecting it could be useful, and also that others could improve it.
/**
* Enum for Genre. It contains the type, objects, elements set and parse method.
*
* This approach supports:
*
* - Pattern matching
* - Parse from name
* - Get all elements
*/
object Genre {
sealed trait Genre
case object MALE extends Genre
case object FEMALE extends Genre
val elements = Set (MALE, FEMALE) // You have to take care this set matches all objects
def apply (code: String) =
if (MALE.toString == code) MALE
else if (FEMALE.toString == code) FEMALE
else throw new IllegalArgumentException
}
/**
* Enum usage (and tests).
*/
object GenreTest extends App {
import Genre._
val m1 = MALE
val m2 = Genre ("MALE")
assert (m1 == m2)
assert (m1.toString == "MALE")
val f1 = FEMALE
val f2 = Genre ("FEMALE")
assert (f1 == f2)
assert (f1.toString == "FEMALE")
try {
Genre (null)
assert (false)
}
catch {
case e: IllegalArgumentException => assert (true)
}
try {
Genre ("male")
assert (false)
}
catch {
case e: IllegalArgumentException => assert (true)
}
Genre.elements.foreach { println }
}
I'm doing the following:
getLocalStorageSizeLimit = function () {
var maxLength = Math.pow(2,24);
var preLength = 0;
var hugeString = "0";
var testString;
var keyName = "testingLengthKey";
//2^24 = 16777216 should be enough to all browsers
testString = (new Array(Math.pow(2, 24))).join("X");
while (maxLength !== preLength) {
try {
localStorage.setItem(keyName, testString);
preLength = testString.length;
maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));
testString = hugeString.substr(0, maxLength);
} catch (e) {
hugeString = testString;
maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
testString = hugeString.substr(0, maxLength);
}
}
localStorage.removeItem(keyName);
maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;
return maxLength;
};
From the Spring reference, 3.2.3.1 Naming Beans:
Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.
When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.
So basically the id
attribute conforms to the XML id attribute standards whereas name
is a little more flexible. Generally speaking, I use name
pretty much exclusively. It just seems more "Spring-y".
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
Directory can be created using file module only, as directory is nothing but a file.
# create a directory if it doesn't exist
- file:
path: /etc/some_directory
state: directory
mode: 0755
owner: foo
group: foo
The best way is to use q
parameter so that it displays the map with the point marked. eg.:
https://maps.google.com/?q=<lat>,<lng>
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.
You can use the file Object to get the length of the file to initialize your array:
int length = Long.valueOf(file.length()).intValue();
byte[] byteArray = new byte[length];
Most the time If Activity
name changed reflected all over the project except the AndroidManifest.xml
file.
You just need to Add the name in manifest
manually.
<activity
android:name="Activity_Class_Name"
android:label="@string/app_name">
</activity>
http://blogs.mysql.com/peterg/2009/04/
In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )
As in
SELECT format(1234567,2,’de_DE’);
For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.
You can use an extension.
import UIKit
extension UILabel {
func sizeFont(_ size: CGFloat) {
self.font = self.font.withSize(size)
}
}
To use it:
self.myLabel.fontSize(100)
You can get the user's WindowsIdentity object under Windows Authentication by:
WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;
and then you can get the information about the user like identity.Name.
Please note you need to have HttpContext for these code.
You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.
For example:
function stateChange(newState) {
setTimeout(function(){
if(newState == -1){alert('VIDEO HAS STOPPED');}
}, 5000);
}
But, if you have code like this:
stateChange(-1);
console.log("Hello");
The console.log()
statement will run immediately. It will not wait until after the timeout fires in the stateChange()
function. You cannot just pause javascript execution for a predetermined amount of time.
Instead, any code that you want to run delays must be inside the setTimeout()
callback function (or called from that function).
If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.
Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.
But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.
Normally HEAD
points to a branch. When it is not pointing to a branch instead when it points to a commit hash like 69e51
it means you have a detached HEAD. You need to point it two a branch to fix the issue. You can do two things to fix it.
hash
HEAD must point to a branch, not a commit hash is the golden rule.
As others have stated it's combination of your schema and the number of indexes.
A friend had about 100,000,000 historical stock prices, daily closing quotes, in an MDB which approached the 2 Gb limit.
He pulled them down using some code found in a Microsoft Knowledge base article. I was rather surprised that whatever server he was using didn't cut him off after the first 100K records.
He could view any record in under a second.
DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.
Get one of the Visual Studio packages; C++
Use { before $ sign. And also add addslashes function to escape special characters.
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";
For info, in your .bowerrc
file you can add a no-proxy attribute. I don't know since when it is supported but it works on bower 1.7.4
.bowerrc :
{
"directory": "bower_components",
"proxy": "http://yourProxy:yourPort",
"https-proxy":"http://yourProxy:yourPort",
"no-proxy":"myserver.mydomain.com"
}
.bowerrc
should be located in the root folder of your Javascript project, the folder in which you launch the bower command. You can also have it in your home folder (~/.bowerrc
).
I've been struggling with this issue and I've tried numerous "solutions".
However, in the end, the only one that worked and it actually took a few seconds to do it was to: delete and add back new server instance!
Basically, I right clicked on my Tomcat server in Eclipse under Servers and deleted it. Next, I've added a new Tomcat server. Cleaned and redeployed the application and I got rid of this error.
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
After verifying that the certificate is issued by a known Certificate Authority (CA), the Subject Alternative Names will be checked, or the Common Name will be checked, to verify that the hostname matches. This is in the checkServerIdentity function. If the certificate has Subject Alternative Names and the hostname is not listed, you'll see the error message described:
Hostname/IP doesn't match certificate's altnames
If you have the CA cert that is used to generate the certificate you're using (usually the case when using self-signed certificates), this can be provided with
var r = require('request');
var opts = {
method: "POST",
ca: fs.readFileSync("ca.cer")
};
r('https://api.dropbox.com', opts, function (error, response, body) {
// do something
});
This will verify that the certificate is issued by the CA provided, but hostname verification will still be performed. Just supplying the CA will be enough if the cert contains the hostname in the Subject Alternative Names. If it doesn't and you also want to skip hostname verification, you can pass a noop function for checkServerIdentity
var r = require('request');
var opts = {
method: "POST",
ca: fs.readFileSync("ca.cer"),
agentOptions: { checkServerIdentity: function() {} }
};
r('https://api.dropbox.com', opts, function (error, response, body) {
// do something
});
toFixed will behave like round.
For a floor like behavior use %:
var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3
I fix without .row
<div class="col col-33 left" ng-repeat="photo in photos">
Content here...
</div>
and css
.left {
float: left;
}
I just found out that if your element id is just a number
, then d3.select("1234"), will not work.
The unique id needs to be an alpha-numeric
character.
d3.select("1234")
d3.select("container1234")
Have you tried the aspnet_regiis tool to register .Net 4.0 for IIS? You can check more at msdn
I would iterate over the results array using an angularjs filter like this:
var foundResultObject = getObjectFromResultsList(results, 1);
function getObjectFromResultsList(results, resultIdToRetrieve) {
return $filter('filter')(results, { id: resultIdToRetrieve }, true)[0];
}
Another simple way using concat:
this.setState({
arr: this.state.arr.concat('new value')
})
is it possible to extend query results with literals like this?
Yes.
Select Name
From Customers
UNION ALL
Select 'Jason'
UNION
to add Jason if it isn't already in the result set.UNION ALL
to add Jason whether or not he's already in the result set.Replace '\n'
with "\n"
. The escape sequence is not recognized when you use '
.
See the manual.
For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen
should get "wb", not "w").
I discovered the following, which prints out which lines, if any, have null characters:
perl -ne '/\000/ and print;' file-with-nulls
Also, an octal dump can tell you if there are nulls:
od file-with-nulls | grep ' 000'
The newly popular tidyr
package does this with separate
. It uses regular expressions so you'll have to escape the |
df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
separate(data = df, col = FOO, into = c("left", "right"), sep = "\\|")
ID left right
1 11 a b
2 12 b c
3 13 x y
though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).
separate(data = df, col = FOO, into = c("left", "right"))
You can do this using simple custom method written below. You have give whole string in first parameter and text to be bold in the second parameter. Hope this will help.
func getAttributedBoldString(str : String, boldTxt : String) -> NSMutableAttributedString {
let attrStr = NSMutableAttributedString.init(string: str)
let boldedRange = NSRange(str.range(of: boldTxt)!, in: str)
attrStr.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17, weight: .bold)], range: boldedRange)
return attrStr
}
usage: initalString = I am a Boy
label.attributedText = getAttributedBoldString(str : initalString, boldTxt : "Boy")
resultant string = I am a Boy
You can use the command ncdu
. It will recursively count how many files a Linux directory contains. Here is an example of output:
It has a progress bar, which is convenient if you have many files:
To install it on Ubuntu:
sudo apt-get install -y ncdu
Benchmark: I used https://archive.org/details/cv_corpus_v1.tar (380390 files, 11 GB) as the folder where one has to count the number of files.
find . -type f | wc -l
: around 1m20s to completencdu
: around 1m20s to completeThe short answer: there is no difference.
The long answer: CHARACTER VARYING
is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR
is a shorter alias which all modern databases also support. I prefer VARCHAR
because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump
and \d
will output character varying
.
To replace with dashes, do the following:
text.replace(/[\W_-]/g,' ');
I usually work with expandtab
set, but that's bad for makefiles. I recently added:
:autocmd FileType make set noexpandtab
to the end of my .vimrc file and it recognizes Makefile, makefile, and *.mk as makefiles and does not expand tabs. Presumably, you can extend this.
Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?
It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/
I've created the boot entry that disables HyperV and it's working
Use inspect.getmembers
to get all the variables/classes/functions etc. in a module, and pass in inspect.isfunction
as the predicate to get just the functions:
from inspect import getmembers, isfunction
from my_project import my_module
functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]
getmembers
returns a list of (object_name, object)
tuples sorted alphabetically by name.
You can replace isfunction
with any of the other isXXX
functions in the inspect
module.
In C language, character literal is not a char
type. C considers character literal as integer. So, there is no difference between sizeof('a')
and sizeof(1)
.
So, the sizeof character literal is equal to sizeof integer in C.
In C++ language, character literal is type of char
. The cppreference say's:
1) narrow character literal or ordinary character literal, e.g.
'a'
or'\n'
or'\13'
. Such literal has typechar
and the value equal to the representation of c-char in the execution character set. If c-char is not representable as a single byte in the execution character set, the literal has type int and implementation-defined value.
So, in C++ character literal is a type of char
. so, size of character literal in C++ is one byte.
Alos, In your programs, you have used wrong format specifier for sizeof
operator.
C11 §7.21.6.1 (P9) :
If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, you should use %zu
format specifier instead of %d
, otherwise it is undefined behaviour in C.
# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password
encrypted and test with the current Password not encrypted to verify
if it's the same User.
For example :
public function updateUser(Request $req)
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(User::class);
$user = $repository->find($req->get(id)); /// get User from your DB
if($user == null){
throw $this->createNotFoundException('User don't exist!!', $user);
}
$password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
$passwordToUpdate = $req->get('password'); // not encrypted yet from request.
$passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);
////////////VERIFY IF IT'S THE SAME PASSWORD
$isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );
if($isPass === false){ // failure
throw $this->createNotFoundException('Your password it's not verify', null);
}
return $isPass; //// true!! it's the same password !!!
}
You could do it easily using
File.AppendAllText("date.txt", DateTime.Now.ToString());
If you need newline
File.AppendAllText("date.txt",
DateTime.Now.ToString() + Environment.NewLine);
Anyway if you need your code do this:
TextWriter tw = new StreamWriter("date.txt", true);
with second parameter telling to append to file.
Check here StreamWriter syntax.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
File.GetLastWriteTime
to Get last modified
File.CreationTime
to get Created time
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
The typical command is:
docker container ls -f 'status=exited'
However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:
You can filter on multiple statuses by passing multiple filters on the status:
docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'
If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q
, and you can also limit to just the containers that exited successfully with an exit code filter:
docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')
For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering
Call the pd.DataFrame
constructor directly:
df = pd.DataFrame(table, columns=headers)
df
Heading1 Heading2
0 1 2
1 3 4
This issue occurs when someone has commited the code to develop/master and latest code has not been rebased from develop/master and you're trying to overwrite new changes to develop/master branch
Solution:
Use:
Open Task Manager ? Processes ? adb.exe ? End Process ? restart Eclipse
This worked for me.
And:
Open Task Manager ? Processes ? eclipse.exe ? End Process ? restart Eclipse
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
Go to proxy settings in Firefox and choose "Use system proxy" but be sure to check if there is no exception for localhost in "no proxy for" field.
Just save the string to a temp variable and then use that in your expression:
var strItem = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
where p.Serial == strItem
select p;
The problem arises because ToString()
isn't really executed, it is turned into a MethodGroup and then parsed and translated to SQL. Since there is no ToString()
equivalent, the expression fails.
Make sure you also check out Alex's answer regarding the SqlFunctions
helper class that was added later. In many cases it can eliminate the need for the temporary variable.
Not sure if this is the most elegant solution (this is what I used), but you could scale your data to the range between 0 to 1 and then modify the colorbar:
import matplotlib as mpl
...
ax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.5)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cm,
norm=mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
cbar.set_clim(-2.0, 2.0)
With the two different limits you can control the range and legend of the colorbar. In this example only the range between -0.5 to 1.5 is show in the bar, while the colormap covers -2 to 2 (so this could be your data range, which you record before the scaling).
So instead of scaling the colormap you scale your data and fit the colorbar to that.
val jsonString =
"""
|{
| "languages": [{
| "name": "English",
| "is_active": true,
| "completeness": 2.5
| }, {
| "name": "Latin",
| "is_active": false,
| "completeness": 0.9
| }]
|}
""".stripMargin
val result = JSON.parseFull(jsonString).map {
case json: Map[String, List[Map[String, Any]]] =>
json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get
println(result)
assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )
static
means different things in different contexts.
You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo()
it will print an increasing number. The static variable is initialized only once.
void foo ()
{
static int i = 0;
printf("%d", i); i++
}
Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj
generated by the file. e.g.
static void foo() { ... }
Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.
This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.
From a user perspective the code works as follows:
To convert an api call to a background task, simply add the @async_api decorator.
Here is a fully contained example:
from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid
tasks = {}
app = Flask(__name__)
api = Api(app)
@app.before_first_request
def before_first_request():
"""Start a background thread that cleans up old tasks."""
def clean_old_tasks():
"""
This function cleans up old tasks from our in-memory data structure.
"""
global tasks
while True:
# Only keep tasks that are running or that finished less than 5
# minutes ago.
five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
tasks = {task_id: task for task_id, task in tasks.items()
if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
time.sleep(60)
if not current_app.config['TESTING']:
thread = threading.Thread(target=clean_old_tasks)
thread.start()
def async_api(wrapped_function):
@wraps(wrapped_function)
def new_function(*args, **kwargs):
def task_call(flask_app, environ):
# Create a request context similar to that of the original request
# so that the task can have access to flask.g, flask.request, etc.
with flask_app.request_context(environ):
try:
tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
except HTTPException as e:
tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
except Exception as e:
# The function raised an exception, so we set a 500 error
tasks[task_id]['return_value'] = InternalServerError()
if current_app.debug:
# We want to find out if something happened so reraise
raise
finally:
# We record the time of the response, to help in garbage
# collecting old tasks
tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())
# close the database session (if any)
# Assign an id to the asynchronous task
task_id = uuid.uuid4().hex
# Record the task, and then launch it
tasks[task_id] = {'task_thread': threading.Thread(
target=task_call, args=(current_app._get_current_object(),
request.environ))}
tasks[task_id]['task_thread'].start()
# Return a 202 response, with a link that the client can use to
# obtain task status
print(url_for('gettaskstatus', task_id=task_id))
return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
return new_function
class GetTaskStatus(Resource):
def get(self, task_id):
"""
Return status about an asynchronous task. If this request returns a 202
status code, it means that task hasn't finished yet. Else, the response
from the task is returned.
"""
task = tasks.get(task_id)
if task is None:
abort(404)
if 'return_value' not in task:
return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
return task['return_value']
class CatchAll(Resource):
@async_api
def get(self, path=''):
# perform some intensive processing
print("starting processing task, path: '%s'" % path)
time.sleep(10)
print("completed processing task, path: '%s'" % path)
return f'The answer is: {path}'
api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')
if __name__ == '__main__':
app.run(debug=True)
Even though I've grown to hate this pattern over time, it's in-grained into COM programming.
#define IfFailGo(x) {hr = (x); if (FAILED(hr)) goto Error}
...
HRESULT SomeMethod(IFoo* pFoo) {
HRESULT hr = S_OK;
IfFailGo( pFoo->PerformAction() );
IfFailGo( pFoo->SomeOtherAction() );
Error:
return hr;
}
First of all, @Fetch(FetchMode.JOIN)
and @ManyToOne(fetch = FetchType.LAZY)
are antagonistic because @Fetch(FetchMode.JOIN)
is equivalent to the JPA FetchType.EAGER
.
Eager fetching is rarely a good choice, and for predictable behavior, you are better off using the query-time JOIN FETCH
directive:
public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {
@Query(value = "SELECT p FROM Place p LEFT JOIN FETCH p.author LEFT JOIN FETCH p.city c LEFT JOIN FETCH c.state where p.id = :id")
Place findById(@Param("id") int id);
}
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom {
@Query(value = "SELECT c FROM City c LEFT JOIN FETCH c.state where c.id = :id")
City findById(@Param("id") int id);
}
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $
represents the jQuery Function, and is actually a shorthand alias for jQuery
. (Unlike in most languages, the $
symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
For example, you can invoke a private constructor inside a friend class or a friend function.
Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.
I have tried this and it is working fine for me:
sqlcmd -S servername -E -s~ -W -k1 -Q "sql query here" > "\\file_path\file_name.csv"
Visual Studio's UserVoice gives a link to generic OrderedDictionary implementation by dotmore.
But if you only need to get key/value pairs by index and don't need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:
class ListArray<T> : List<T[]> { }
You may also declare it with constructors:
class ListArray<T> : List<T[]>
{
public ListArray() : base() { }
public ListArray(int capacity) : base(capacity) { }
}
For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:
ListArray<string> settingsRead = new ListArray<string>();
using (var sr = new StreamReader(myFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] keyValueStrings = line.Split(separator);
for (int i = 0; i < keyValueStrings.Length; i++)
keyValueStrings[i] = keyValueStrings[i].Trim();
settingsRead.Add(keyValueStrings);
}
}
// Later you get your key/value strings simply by index
string[] myKeyValueStrings = settingsRead[index];
As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.
There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):
getApplicationInfo().dataDir
http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()
The following works:
@NonCPS
def printParams() {
env.getEnvironment().each { name, value -> println "Name: $name -> Value $value" }
}
printParams()
Note that it will most probably fail on first execution and require you approve various groovy methods to run in jenkins sandbox. This is done in "manage jenkins/in-process script approval"
The list I got included:
Try this:
- (void)tableView:(UITableView *)tableView1 willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell setBackgroundColor:[UIColor clearColor]];
tableView1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @"Cream.jpg"]];
}
Since c
is holding the address of an integer pointer, its type should be int**
:
int **c;
c = &a;
The entire program becomes:
#include <stdio.h>
int main(){
int b=10;
int *a;
a=&b;
int **c;
c=&a;
printf("%d",(**c)); //successfully prints 10
return 0;
}
function timeDifference(date1, date2) {_x000D_
var oneDay = 24 * 60 * 60; // hours*minutes*seconds_x000D_
var oneHour = 60 * 60; // minutes*seconds_x000D_
var oneMinute = 60; // 60 seconds_x000D_
var firstDate = date1.getTime(); // convert to milliseconds_x000D_
var secondDate = date2.getTime(); // convert to milliseconds_x000D_
var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds_x000D_
// the difference object_x000D_
var difference = {_x000D_
"days": 0,_x000D_
"hours": 0,_x000D_
"minutes": 0,_x000D_
"seconds": 0,_x000D_
}_x000D_
//calculate all the days and substract it from the total_x000D_
while (seconds >= oneDay) {_x000D_
difference.days++;_x000D_
seconds -= oneDay;_x000D_
}_x000D_
//calculate all the remaining hours then substract it from the total_x000D_
while (seconds >= oneHour) {_x000D_
difference.hours++;_x000D_
seconds -= oneHour;_x000D_
}_x000D_
//calculate all the remaining minutes then substract it from the total _x000D_
while (seconds >= oneMinute) {_x000D_
difference.minutes++;_x000D_
seconds -= oneMinute;_x000D_
}_x000D_
//the remaining seconds :_x000D_
difference.seconds = seconds;_x000D_
//return the difference object_x000D_
return difference;_x000D_
}_x000D_
console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));
_x000D_
look at the example
window.history.replaceState({
foo: 'bar'
}, 'Nice URL Title', '/nice_url');
window.onpopstate = function (e) {
if (typeof e.state == "object" && e.state.foo == "bar") {
alert("Blah blah blah");
}
};
window.history.go(-1);
and search location.hash
;
Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive
@if(@isset($names))
@unless($names)
Array has no value
@else
Array has value
@foreach($names as $name)
{{$name}}
@endforeach
@endunless
@else
Not defined
@endif
You need to compile with the link flag -lm
, like this:
gcc fib.c -lm -o fibo
This will tell gcc to link your code against the math lib. Just be sure to put the flag after the objects you want to link.
I had the same problem and this solution also did the trick for me: Provide the IP 127.0.0.1 in the Intellij Debug configuration instead of the host name "localhost", in case you're using this hostname.
I had to check the box for the debugger on the phone "always allow on this phone". I then did a adb devices and then entered the adb command to clear the adds. It worked fine. Before that, it did not recognize the pm and other commands
This page shows how to determine your scroll offset. jQuery may have similar functionality but I couldn't find it. Using the getScrollXY function shown on the page, you should be able to subtract the x and y coords from the .position() results.
There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to &&
or ||
.
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
You can use all functions from Long, if you put the number into "(" ")". That way you can cast the long to an int:
<c:out value="${map[(1).intValue()]}"/>
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
Another way is to mutate the undesired columns to NULL
, this avoids the embedded parentheses :
head(iris,2) %>% mutate_at(drop.cols, ~NULL)
# Petal.Length Petal.Width Species
# 1 1.4 0.2 setosa
# 2 1.4 0.2 setosa
try this....
public void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
Intent intent = new Intent(ctx, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);
Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(icon)
.setLargeIcon(bm)
.setContentTitle(content)
.setContentText(text)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(!silent)
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410, notificationBuilder.build());
}
and in onMessageReceived, call it
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");
buildPushNotification(/*your param*/);
}
or follow KongJing, Is also correct as he says, but you can use a Firebase Console.
Just derive a class from TextBox or MaskedTextBox:
public class SMaskedTextBox : MaskedTextBox
{
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
this.SelectAll();
}
}
And use it on your forms.
List<string> result = names.Split(new char[] { ',' }).ToList();
Or even cleaner by Dan's suggestion:
List<string> result = names.Split(',').ToList();
Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv
and paste the following content.
Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no
Here is the code the comments explains everything we are doing here! [python]
import pandas as pd
import pprint
class Classifier():
data = None
class_attr = None
priori = {}
cp = {}
hypothesis = None
def __init__(self,filename=None, class_attr=None ):
self.data = pd.read_csv(filename, sep=',', header =(0))
self.class_attr = class_attr
'''
probability(class) = How many times it appears in cloumn
__________________________________________
count of all class attribute
'''
def calculate_priori(self):
class_values = list(set(self.data[self.class_attr]))
class_data = list(self.data[self.class_attr])
for i in class_values:
self.priori[i] = class_data.count(i)/float(len(class_data))
print "Priori Values: ", self.priori
'''
Here we calculate the individual probabilites
P(outcome|evidence) = P(Likelihood of Evidence) x Prior prob of outcome
___________________________________________
P(Evidence)
'''
def get_cp(self, attr, attr_type, class_value):
data_attr = list(self.data[attr])
class_data = list(self.data[self.class_attr])
total =1
for i in range(0, len(data_attr)):
if class_data[i] == class_value and data_attr[i] == attr_type:
total+=1
return total/float(class_data.count(class_value))
'''
Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
(Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
scaled by P(Multiple Evidence)
'''
def calculate_conditional_probabilities(self, hypothesis):
for i in self.priori:
self.cp[i] = {}
for j in hypothesis:
self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
print "\nCalculated Conditional Probabilities: \n"
pprint.pprint(self.cp)
def classify(self):
print "Result: "
for i in self.cp:
print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]
if __name__ == "__main__":
c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
c.calculate_priori()
c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
c.calculate_conditional_probabilities(c.hypothesis)
c.classify()
output:
Priori Values: {'yes': 0.6428571428571429, 'no': 0.35714285714285715}
Calculated Conditional Probabilities:
{
'no': {
'<=30': 0.8,
'fair': 0.6,
'medium': 0.6,
'yes': 0.4
},
'yes': {
'<=30': 0.3333333333333333,
'fair': 0.7777777777777778,
'medium': 0.5555555555555556,
'yes': 0.7777777777777778
}
}
Result:
yes ==> 0.0720164609053
no ==> 0.0411428571429
Hope it helps in better understanding the problem
peace
If you are debugging T4 templates, then this happens all the time. My solution (before MS fixes this) would be just to kill this process:
Task Manager --> User --> T4VSHostProcess.exe
This process only comes up when you debug a T4 template, not when you run one.
A small change to Paul's code so that it doesn't return the error mentioned above.
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +
geom_point() + geom_line()
if you are using ps, you can check the manual
man ps
there is a list of keywords allowing you to build what you need. for example to show, userid / processid / percent cpu / percent memory / work queue / command :
ps -e -o "uid pid pcpu pmem wq comm"
-e is similar to -A (all inclusive; your processes and others), and -o is to force a format.
if you are looking for a specific uid, you can chain it using awk or grep such as :
ps -e -o "uid pid pcpu pmem wq comm" | grep 501
this should (almost) show only for userid 501. try it.
Team Foundation Sidekicks has a Status sidekick that allows you to query for checked out work items. Once a work item is selected, click the "Undo lock" buttons on the toolbar.
Rights
Keep in mind that you will need the appropriate rights. The permissions are called "Undo other users' changes" and "Unlock other users' changes". These permissions can be viewed by:
Disclaimer: this answer is an edited repost of Brett Roger's answer to a similar question.
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)
) before sending to report services and handle it as described above.
One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.
If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
I had the same problem but when I removed
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
it started working again.
for
is for loop that can iterate each element or every third etc. for_each
is for iterating only each element. It is clear from its name. So it is more clear what you are intending to do in your code.
import URL from 'url';
const pathname = URL.parse(url).path;
console.log(url.replace(pathname, ''));
this takes care of both the protocol.
Let's see the code of how we can use this
import react from 'react'
function Header()
{
return <p><b><h1>This is the Heading section</h1></b></p>;
}
**export default Header;**
If you want to install a bunch of dependencies from, say a requirements.txt, you would do:
mkdir dependencies
pip download -r requirements.txt -d "./dependencies"
tar cvfz dependencies.tar.gz dependencies
And, once you transfer the dependencies.tar.gz to the machine which does not have internet you would do:
tar zxvf dependencies.tar.gz
cd dependencies
pip install * -f ./ --no-index
I regularly work on the same file in 2 different positions. I solved this in Sublime Text 3 using origami and chain with some additional config.
My workflow is Ctrl + k + 2 splits the view of the file in two (horizontal) panes with the lower one active. Use Ctrl + k + o to toggle between the panes. When done ensure the lower pane is the active and press Ctrl + F4 to close the duplicated view and the pane.
In sublime global settings (not origami settings!) add
"origami_auto_close_empty_panes": true,
Add the following shortcuts
{ "keys": ["ctrl+k", "2"],
"command": "chain",
"args": {
"commands": [
["create_pane", {"direction": "down"}],
["clone_file_to_pane", {"direction": "down"}],
],
}
},
{ "keys": ["ctrl+k", "o"], "command": "focus_neighboring_group" },
I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.
So here are steps.
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Use string interpolation decimalVar:0.00
The above answers are bit outdated. Although those method work, but by using below method, you can share any text to a predefined number. The below method works for android, WhatsApp web, IOS etc.
You just need to use this format:
<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>
UPDATE-- Use this from now(Nov-2018)
<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.
Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing
After clicking on the link, you will be shown a list of contacts you can send your message to.
For more information, see https://www.whatsapp.com/faq/en/general/26000030
I guess I came a little late for this but I think the main problem here is that you're patching datetime.date.today directly and, according to the documentation, this is wrong.
You should patch the reference imported in the file where the tested function is, for example.
Let's say you have a functions.py file where you have the following:
import datetime
def get_today():
return datetime.date.today()
then, in your test, you should have something like this
import datetime
import unittest
from functions import get_today
from mock import patch, Mock
class GetTodayTest(unittest.TestCase):
@patch('functions.datetime')
def test_get_today(self, datetime_mock):
datetime_mock.date.today = Mock(return_value=datetime.strptime('Jun 1 2005', '%b %d %Y'))
value = get_today()
# then assert your thing...
Hope this helps a little bit.
I got this error on Ubuntu, and the following worked for me:
Removed the dropbox binaries and download them again, by running:
sudo rm -rf /var/lib/dropbox/.dropbox-dist
dropbox start -i
Try below code if you want to use php loop to display
<span>
<select name="birth_month">
<?php for( $m=1; $m<=12; ++$m ) {
$month_label = date('F', mktime(0, 0, 0, $m, 1));
?>
<option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
<?php } ?>
</select>
</span>
<span>
<select name="birth_day">
<?php
$start_date = 1;
$end_date = 31;
for( $j=$start_date; $j<=$end_date; $j++ ) {
echo '<option value='.$j.'>'.$j.'</option>';
}
?>
</select>
</span>
<span>
<select name="birth_year">
<?php
$year = date('Y');
$min = $year - 60;
$max = $year;
for( $i=$max; $i>=$min; $i-- ) {
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</span>
What does it mean?
It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.
What happens if I try to iterate the map with two threads at the same time?
It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.
But if the two threads used different iterators, you should be fine.
What happens if I put or remove a value from the map while iterating it?
That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.
you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.
It is a common problem when you have added two version of the same library..either in the dependency or in the library....It my case and almost every time this fixes the issue..
Update (thanks to dawmail333):
heroku logs -n 1500
or, to tail the logs live
heroku logs -t
If you need more than a few thousand lines you can Use heroku's Syslog Drains
Alternatively (old method):
$ heroku run rails c
File.open('log/production.log', 'r').each_line { |line| puts line }
Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.
If you are not using IPython then just install it: "pip install ipython"
For lists
a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)
The output is [('a', 'p'), ('b', 'q'), ('c', 'r')
For dictionary:
c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)
The output is:
[('gaurav', 'amit'),
('nilesh', 'swapnil'),
('ramesh', 'anish'),
('anu', 'raghu')]
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
for WORDPRESS:
global $wpdb;
$your_table = $wpdb->prefix. 'My_Table_Name';
$your_column = 'My_Column_Name';
if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){ $result= $wpdb->query(
"ALTER TABLE $your_table ADD $your_column VARCHAR(100) CHARACTER SET utf8 NOT NULL " //you can add positioning phraze: "AFTER My_another_column"
);}
If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.
this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
In my case, one of the exported child module was not returning a proper react component.
const Component = <div> Content </div>;
instead of
const Component = () => <div>Content</div>;
The error shown was for the parent, hence couldn't figure out.
I had a similar problem for xml. Just passing the error and solution (edited Jonathon version).
Code:
HttpGet xmlGet = new HttpGet( xmlContent );
Xml format:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<code>CA</code>
<name>Cath</name>
<salary>300</salary>
</employee>
Error:
java.lang.IllegalArgumentException: Illegal character in path at index 0: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<contents>
<portalarea>CA</portalarea>
<portalsubarea>Cath</portalsubarea>
<direction>Navigator</direction>
</contents>
at java.net.URI.create(URI.java:859)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
at de.vogella.jersey.first.Hello.validate(Hello.java:56)
Not Exactly perfect Solution: ( error vanished for that instance )
String theXml = URLEncoder.encode( xmlContent, "UTF-8" );
HttpGet xmlGet = new HttpGet( theXml );
Any idea What i should be doing ? It just cleared passed but had problem while doing this
HttpResponse response = httpclient.execute( xmlGet );
The cheapest and dirtiest way to do it is simply make microtime()
calls at places in your code you want to benchmark. Do it right before and right after database queries and it's simple to remove those durations from the rest of your script execution time.
A hint: your PHP execution time is rarely going to be the thing that makes your script timeout. If a script times out it's almost always going to be a call to an external resource.
PHP microtime documentation: http://us.php.net/microtime
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
Try
\d \w |\d
or add a positive lookahead if you don't want to include the trailing space in the match
\d \w(?= )|\d
When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
Each controller has it's own scope(s) so that's causing your issue.
Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".
Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video
One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).
You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)
I would suggest it might be better to use ajax and load the svg element from another page.
$('.container').load(href + ' .svg_element');
Where href is the location of the page with the svg. This way you can avoid any jittery effects that might occur from replacing the html content. Also, don't forget to unwrap the svg after it's loaded:
$('.svg_element').unwrap();