You need the admin privilege to run the service
I had the similar issue. The problem goes away when I run command prompt ( run as an administrator" , and type " docker version".
C:\WINDOWS\system32>docker version
Client: Docker Engine - Community Version: 19.03.8 API version: 1.40 Go version: go1.12.17 Git commit: afacb8b Built: Wed Mar 11 01:23:10 2020 OS/Arch: windows/amd64 Experimental: false
Server: Docker Engine - Community Engine: Version: 19.03.8 API version: 1.40 (minimum version 1.12) Go version: go1.12.17 Git commit: afacb8b Built: Wed Mar 11 01:29:16 2020 OS/Arch: linux/amd64 Experimental: false containerd: Version: v1.2.13 GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429 runc: Version: 1.0.0-rc10 GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd docker-init: Version: 0.18.0 GitCommit: fec3683
You can use it this way:
$root = 'C:'
$folder1 = 'Program Files (x86)'
$folder2 = 'Microsoft.NET'
if (-Not(Test-Path $(Join-Path $root -ChildPath $folder1 | Join-Path -ChildPath $folder2)))
{
"Folder does not exist"
}
else
{
"Folder exist"
}
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:
public IHttpActionResult Post(Task task)
What worked for me was to create my own entity "DTOTask" like:
public IHttpActionResult Post(DTOTask task)
Everything in one line:
get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof -join ";" } } | export-csv membership.csv
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
For Swift version 5.3 its easy as:
let string = "Hello world"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
I came into problem of sorting array of objects, with changing priority of values, basically I want to sort array of peoples by their Age, and then by surname - or just by surname, name. I think that this is most simple solution compared to another answers.
it' is used by calling sortPeoples(['array', 'of', 'properties'], reverse=false)
///////////////////////example array of peoples ///////////////////////_x000D_
_x000D_
var peoples = [_x000D_
{name: "Zach", surname: "Emergency", age: 1},_x000D_
{name: "Nancy", surname: "Nurse", age: 1},_x000D_
{name: "Ethel", surname: "Emergency", age: 1},_x000D_
{name: "Nina", surname: "Nurse", age: 42},_x000D_
{name: "Anthony", surname: "Emergency", age: 42},_x000D_
{name: "Nina", surname: "Nurse", age: 32},_x000D_
{name: "Ed", surname: "Emergency", age: 28},_x000D_
{name: "Peter", surname: "Physician", age: 58},_x000D_
{name: "Al", surname: "Emergency", age: 58},_x000D_
{name: "Ruth", surname: "Registration", age: 62},_x000D_
{name: "Ed", surname: "Emergency", age: 38},_x000D_
{name: "Tammy", surname: "Triage", age: 29},_x000D_
{name: "Alan", surname: "Emergency", age: 60},_x000D_
{name: "Nina", surname: "Nurse", age: 58}_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
//////////////////////// Sorting function /////////////////////_x000D_
function sortPeoples(propertyArr, reverse) {_x000D_
function compare(a,b) {_x000D_
var i=0;_x000D_
while (propertyArr[i]) {_x000D_
if (a[propertyArr[i]] < b[propertyArr[i]]) return -1;_x000D_
if (a[propertyArr[i]] > b[propertyArr[i]]) return 1;_x000D_
i++;_x000D_
}_x000D_
return 0;_x000D_
}_x000D_
peoples.sort(compare);_x000D_
if (reverse){_x000D_
peoples.reverse();_x000D_
}_x000D_
};_x000D_
_x000D_
////////////////end of sorting method///////////////_x000D_
function printPeoples(){_x000D_
$('#output').html('');_x000D_
peoples.forEach( function(person){_x000D_
$('#output').append(person.surname+" "+person.name+" "+person.age+"<br>");_x000D_
} )_x000D_
}
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<html>_x000D_
<body>_x000D_
<button onclick="sortPeoples(['surname']); printPeoples()">sort by ONLY by surname ASC results in mess with same name cases</button><br>_x000D_
<button onclick="sortPeoples(['surname', 'name'], true); printPeoples()">sort by surname then name DESC</button><br>_x000D_
<button onclick="sortPeoples(['age']); printPeoples()">sort by AGE ASC. Same issue as in first case</button><br>_x000D_
<button onclick="sortPeoples(['age', 'surname']); printPeoples()">sort by AGE and Surname ASC. Adding second field fixed it.</button><br>_x000D_
_x000D_
<div id="output"></div>_x000D_
</body>_x000D_
</html>
_x000D_
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
I found the easiest solution on Windows is to build from source.
You can pretty much follow this guide: http://spark.apache.org/docs/latest/building-spark.html
Download and install Maven, and set MAVEN_OPTS
to the value specified in the guide.
But if you're just playing around with Spark, and don't actually need it to run on Windows for any other reason that your own machine is running Windows, I'd strongly suggest you install Spark on a linux virtual machine. The simplest way to get started probably is to download the ready-made images made by Cloudera or Hortonworks, and either use the bundled version of Spark, or install your own from source or the compiled binaries you can get from the spark website.
For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.
Here's another answer, similar to Justin's, but doesn't need an identity or aggregate, just a primary (unique) key.
declare @table1 table(dataKey int, dataCol1 varchar(20), dataCol2 datetime)
declare @dataKey int
while exists select 'x' from @table1
begin
select top 1 @dataKey = dataKey
from @table1
order by /*whatever you want:*/ dataCol2 desc
-- do processing
delete from @table1 where dataKey = @dataKey
end
And in Kotlin:
tailrec fun Context.activity(): Activity? = when {
this is Activity -> this
else -> (this as? ContextWrapper)?.baseContext?.activity()
}
ex mode is easiest:
:%s/$/,
: - enter command mode
% - for every line
s/ - substitute
$ - the end of the line
/ - and change it to
, - a comma
If there may be empty trailing spaces, probably there isn't better solution. COALESCE
is just for problems like yours.
I have on several projects.
The biggest difference in my opinion
jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old
Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding
jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)
So what to choose?
That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?
I always end up using both, so I can use the best of both worlds.
Here are the links to both frameworks, if you decide to use them.
give the read / write permission to the IIS user or group users
Start -> run -> inetmgr
enable the ASP.NET authentication for your default website
3. For 64-bit (x64), create this folder: C:\Windows\SysWOW64\config\systemprofile\Desktop
For 32-bit (x86), create this folder: C:\Windows\System32\config\systemprofile\Desktop
The windows service, if running under the systemprofile, needs the Desktop folder. This folder was automatically created on XP and older Windows Server versions, but not for Vista and Windows 2008 Server.
If the iframe was not on a different domain, you could do something like this:
document.getElementById(FrameID).contentDocument.location.reload(true);
But since the iframe is on a different domain, you will be denied access to the iframe's contentDocument
property by the same-origin policy.
But you can hackishly force the cross-domain iframe to reload if your code is running on the iframe's parent page, by setting it's src attribute to itself. Like this:
// hackishly force iframe to reload
var iframe = document.getElementById(FrameId);
iframe.src = iframe.src;
If you are trying to reload the iframe from another iframe, you are out of luck, that is not possible.
Here is how I know if one list is a subset of another one, the sequence matters to me in my case.
def is_subset(list_long,list_short):
short_length = len(list_short)
subset_list = []
for i in range(len(list_long)-short_length+1):
subset_list.append(list_long[i:i+short_length])
if list_short in subset_list:
return True
else: return False
use this full code
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+Uri.encode(PhoneNum.trim())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
In Linux, it was solved by opening PyCharm from the terminal and leaving it open. After that, I was able to choose the correct interpreter in preferences. In my case, linked to a virtual environment (venv).
if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.
package com.java.demo;
/**
* @author Ankit Sood Apr 20, 2017
*/
public class Demo {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
/* Initialize while loop */
while (true) {
/*
* You have to declare some condition to stop while loop
* In which situation or condition you want to terminate while loop.
* conditions like: if(condition){break}, if(var==10){break} etc...
*/
/* break keyword is for stop while loop */
break;
}
}
}
DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db=CurrentDB
strSQL = "select * from table where some condition"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
rs.Edit
rs!SomeField = "Abc"
rs!OtherField = 2
rs!ADate = Date()
rs.Update
rs.MoveNext
Loop
Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code
Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from
(
select new.* from
(
select distinct cName, cCity, cState
from [Competitors] s, [City] c, [State] s
) new
left join
(
select distinct cName, cCity, cState
from [Competitors] s
) existing
on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
where existing.Name is null or existing.City is null or existing.State is null
)
The profile choices need to be setup as a ManyToManyField for this to work correctly.
So... your model should be like this:
class Choices(models.Model):
description = models.CharField(max_length=300)
class Profile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
choices = models.ManyToManyField(Choices)
Then, sync the database and load up Choices with the various options you want available.
Now, the ModelForm will build itself...
class ProfileForm(forms.ModelForm):
Meta:
model = Profile
exclude = ['user']
And finally, the view:
if request.method=='POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
else:
form = ProfileForm()
return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.
Good luck.
This gives you the total amount from another WMI class:
$cs = get-wmiobject -class "Win32_ComputerSystem"
$Mem = [math]::Ceiling($cs.TotalPhysicalMemory / 1024 / 1024 / 1024)
Hope this helps.
<style>
background: url(images/Untitled-2.fw.png);
background-repeat:no-repeat;
background-position:center;
background-size: cover;
</style>
You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...
int i = 5; char a = ((char*)&i)[0]; char b = ((char*)&i)[1];
Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!
But you probably meant "i want to stringify a number", so ignore this response :-)
Try like below... it will help you...
Some time in Window Form Focus()
doesn't work correctly. So better you can use Select()
to focus the textbox.
txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox
This example is fast and will delete all instances of a value from the list:
a = [1,2,3,1,2,3,4]
while True:
try:
a.remove(3)
except:
break
print a
>>> [1, 2, 1, 2, 4]
You can't instantiate interfaces or abstract classes.
That's because it wouldn't have any logic to it.
Interfaces provide a contract of the methods that should be in a class, without implementation. (So there's no actual logic in the interface).
Abstract classes provide basic logic of a class, but are not fully functional (not everything is implemented). So again, you won't be able to do anything with it.
You should just use Spread operator:
var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);_x000D_
_x000D_
var newArr = [...myMap].map(value => value[1] + 1);_x000D_
console.log(newArr); //[2, 3, 4]_x000D_
_x000D_
var newArr2 = [for(value of myMap) value = value[1] + 1];_x000D_
console.log(newArr2); //[2, 3, 4]
_x000D_
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
I used this approach to perform the same operation in my app.
var varDate = $("#dateStart").val();
var DateinISO = $.datepicker.parseDate('mm/dd/yy', varDate);
var DateNewFormat = $.datepicker.formatDate( "yy-mm-dd", new Date( DateinISO ) );
$("#dateStartNewFormat").val(DateNewFormat);
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, &&
and ||
only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{}
construction and to direct program control rather than construct new vectors.. The &
and the |
operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to &&
or ||
are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
Two separate checks. Also, use ==
rather than is
to check for equality rather than identity.
if var=='stringone' or var=='stringtwo':
dosomething()
Works fine, except if you have spaces or escaped characters. I don't find the way to capture arguments in this case and send to a ssh inside of script.
This could be useful but is so ugly
_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )
btnTest.Click +=new EventHandler(btnTest_Click)
Give radio buttons, same name but different IDs.
var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
//condition
final_answer = verified1;
}
else
{
if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
//condition
final_answer = verified2;
}
else
{
return false;
}
}
Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
I'm not sure this has been mentioned yet. But there is a lodash function for that. Snippet below where value is your attribute to sum is 'value'.
_.sumBy(objects, 'value');
_.sumBy(objects, function(o) { return o.value; });
Both will work.
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
Let's say you have two numbers, 40 and 30.
30/40*100 = 75.
So 30 is 75% of 40.
40/30*100 = 133.
So 40 is 133% of 30.
The percentage increase from 30 to 40 is:
(40-30)/30 * 100 = 33%
The percentage decrease from 40 to 30 is:
(40-30)/40 * 100 = 25%.
These calculations hold true whatever your two numbers.
This should do it:
//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
char *e = strchr(string, c);
if (e == NULL) {
return -1;
}
return (int)(e - string);
}
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
When animating height (from 0 to auto), using transform: scaleY(0);
is another useful approach to hide the element, instead of display: none;
:
.section {
overflow: hidden;
transition: transform 0.3s ease-out;
height: auto;
transform: scaleY(1);
transform-origin: top;
&.hidden {
transform: scaleY(0);
}
}
This technique is working for me:
$('#myInputFieldId').bind('input',function(){
alert("Hello");
});
Note that according to this JQuery doc, "on" is recommended rather than bind in newer versions.
use this one in your pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
or this one :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
This worked for me:
git clone https://username:[email protected]/username/repo_name.git
The color plugin is only 4kb so much cheaper than the UI library. Of course you'll want to use a decent version of the plugin and not some buggy old thing which doesn't handle Safari and crashes when the transitions are too fast. Since a minified version isn't supplied you might like test various compressors and make your own min version. YUI gets the best compression in this case needing only 2317 bytes and since it is so small - here it is:
(function (d) {
d.each(["backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "color", "outlineColor"], function (f, e) {
d.fx.step[e] = function (g) {
if (!g.colorInit) {
g.start = c(g.elem, e);
g.end = b(g.end);
g.colorInit = true
}
g.elem.style[e] = "rgb(" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(",") + ")"
}
});
function b(f) {
var e;
if (f && f.constructor == Array && f.length == 3) {
return f
}
if (e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)) {
return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]
}
if (e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)) {
return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]
}
if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {
return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]
}
if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {
return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]
}
if (e = /rgba\(0, 0, 0, 0\)/.exec(f)) {
return a.transparent
}
return a[d.trim(f).toLowerCase()]
}
function c(g, e) {
var f;
do {
f = d.css(g, e);
if (f != "" && f != "transparent" || d.nodeName(g, "body")) {
break
}
e = "backgroundColor"
} while (g = g.parentNode);
return b(f)
}
var a = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0],
transparent: [255, 255, 255]
}
})(jQuery);
You can also use a small function that will loop through and remove any spaces.
This is very clean and simple.
Public Shared Function RemoveXtraSpaces(strVal As String) As String
Dim iCount As Integer = 1
Dim sTempstrVal As String
sTempstrVal = ""
For iCount = 1 To Len(strVal)
sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
Next
RemoveXtraSpaces = sTempstrVal
Return RemoveXtraSpaces
End Function
Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv
commands will tire quickly. To make things a bit easier this is what I do:
git add . -A
to remove all files.git add .
. Git should see that the files are renamed.Now you can make a commit saying you have changed the file name capitalization.
Yep you should start anaconda's python in order to use python libs which come with anaconda. Or otherwise you have to manually add anaconda\lib
to pythonpath
which is less trivial. You can start anaconda's python by a full path:
path\to\anaconda\python.exe
or you can run the following two commands as an admin in cmd to make windows pipe every .py
file to anaconda's python:
assoc .py=Python.File
ftype Python.File=C:\path\to\Anaconda\python.exe "%1" %*
after this you'll be able just to call python scripts without specifying the python executable at all.
While astype
is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr
in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
int*
functions from NumPy>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
*array
functions themselves:>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
astype
method (that was already mentioned but for completeness sake):>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int
as dtype to astype
or array
will default to a default integer type that depends on your platform. For example on Windows it will be int32
, on 64bit Linux with 64bit Python it's int64
. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32
or np.int64
.
place something like this in your script file json-content.js
var mainjson = { your json data}
then call it from script tag
<script src="json-content.js"></script>
then you can use it in next script
<script>
console.log(mainjson)
</script>
as noted here, this is what worked best for me:
sudo apt-get install python3 python3-pip python3-setuptools
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.
<input type="text" name="fname" autofocus>
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
this works:
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
else
{
TopMost = true;
Focus();
BringToFront();
TopMost = false;
}
SQL Server stored procedure:
CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
@na varchar(50),
@occ varchar(50),
@New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Mem_Basic
VALUES (@na, @occ)
SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END
C# code:
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
// values 0 --> -99 are SQL reserved.
int new_MEM_BASIC_ID = -1971;
SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);
outPutVal.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutVal);
cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;
SQLconn.Open();
cmd.ExecuteNonQuery();
SQLconn.Close();
if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
return new_MEM_BASIC_ID;
}
I hope these will help to you ....
You can also use this if you want ...
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
int newID;
var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";
using(SqlCommand cmd=new SqlCommand(cmd, con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
newID = (int)insertCommand.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return newID;
}
}
}
If you want to use some variable, you may use this way:
String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
I know it's an old question, but it's a good one, so how about this?
unsigned short int x = 65529U;
short int y = *(short int*)&x;
printf("%d\n", y);
This should work:
$(this).find('option:selected').text();
My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:
This is what worked for me:
1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine.
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines.
5.) `git clone my_project`
6.) `vagrant up`
I had a few problems with VB Guest additions.
I fixed them with this solution.
Regex.Matches(input, "true").Count
I got similar error while using in-app-purchase in android. My mistake is I used wrong purchase id while instantiating the purchases.
public static final String PRODUCT_ID_ASTRO_Match = "android.test.product";//wrong id not in play store dev console
Replaced it with:
public static final String PRODUCT_ID_ASTRO_Match = "android.test.purchased";
and it worked.
I've seen similar problems happen if anti-virus was installed on the SQL server. The AV's auto-update features were clocking the server and not allowing enough CPU for SQL Server.
Also, have you put a small application on the SQL server itself that verifies that connections can be made or runs very basic SQL like "SELECT GETDATE();"? This would eliminate network possibilities.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
This is a great plugin for use with update panels:
You can use hasattr()
or catch AttributeError
, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr()
:
getattr(a, 'property', 'default value')
I wrote a few methods for this a while ago, so I figured why not throw my two cents at this.
/** @param stackTraceElements The elements to convert
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements) {
return stackTraceElementsToStr(stackTraceElements, "\n");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements, String lineSeparator) {
return stackTraceElementsToStr(stackTraceElements, lineSeparator, "");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting string */
public static final String stackTraceElementsToStr(StackTraceElement[] stackTraceElements, String lineSeparator, String padding) {
String str = "";
if(stackTraceElements != null) {
for(StackTraceElement stackTrace : stackTraceElements) {
str += padding + (!stackTrace.toString().startsWith("Caused By") ? "\tat " : "") + stackTrace.toString() + lineSeparator;
}
}
return str;
}
/** @param stackTraceElements The elements to convert
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements) {
return stackTraceCausedByElementsOnlyToStr(stackTraceElements, "\n");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements, String lineSeparator) {
return stackTraceCausedByElementsOnlyToStr(stackTraceElements, lineSeparator, "");
}
/** @param stackTraceElements The elements to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting string */
public static final String stackTraceCausedByElementsOnlyToStr(StackTraceElement[] stackTraceElements, String lineSeparator, String padding) {
String str = "";
if(stackTraceElements != null) {
for(StackTraceElement stackTrace : stackTraceElements) {
str += (!stackTrace.toString().startsWith("Caused By") ? "" : padding + stackTrace.toString() + lineSeparator);
}
}
return str;
}
/** @param e The {@link Throwable} to convert
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e) {
return throwableToStrNoStackTraces(e, "\n");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e, String lineSeparator) {
return throwableToStrNoStackTraces(e, lineSeparator, "");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting String */
public static final String throwableToStrNoStackTraces(Throwable e, String lineSeparator, String padding) {
if(e == null) {
return "null";
}
String str = e.getClass().getName() + ": ";
if((e.getMessage() != null) && !e.getMessage().isEmpty()) {
str += e.getMessage() + lineSeparator;
} else {
str += lineSeparator;
}
str += padding + stackTraceCausedByElementsOnlyToStr(e.getStackTrace(), lineSeparator, padding);
for(Throwable suppressed : e.getSuppressed()) {
str += padding + throwableToStrNoStackTraces(suppressed, lineSeparator, padding + "\t");
}
Throwable cause = e.getCause();
while(cause != null) {
str += padding + "Caused by:" + lineSeparator + throwableToStrNoStackTraces(e.getCause(), lineSeparator, padding);
cause = cause.getCause();
}
return str;
}
/** @param e The {@link Throwable} to convert
* @return The resulting String */
public static final String throwableToStr(Throwable e) {
return throwableToStr(e, "\n");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @return The resulting String */
public static final String throwableToStr(Throwable e, String lineSeparator) {
return throwableToStr(e, lineSeparator, "");
}
/** @param e The {@link Throwable} to convert
* @param lineSeparator The line separator to use
* @param padding The string to be used at the start of each line
* @return The resulting String */
public static final String throwableToStr(Throwable e, String lineSeparator, String padding) {
if(e == null) {
return "null";
}
String str = padding + e.getClass().getName() + ": ";
if((e.getMessage() != null) && !e.getMessage().isEmpty()) {
str += e.getMessage() + lineSeparator;
} else {
str += lineSeparator;
}
str += padding + stackTraceElementsToStr(e.getStackTrace(), lineSeparator, padding);
for(Throwable suppressed : e.getSuppressed()) {
str += padding + "Suppressed: " + throwableToStr(suppressed, lineSeparator, padding + "\t");
}
Throwable cause = e.getCause();
while(cause != null) {
str += padding + "Caused by:" + lineSeparator + throwableToStr(e.getCause(), lineSeparator, padding);
cause = cause.getCause();
}
return str;
}
Example:
try(InputStream in = new FileInputStream(file)) {
...
} catch(IOException e) {
String exceptionToString = throwableToStr(e);
someLoggingUtility.println(exceptionToString);
...
}
Prints:
java.io.FileNotFoundException: C:\test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.gmail.br45entei.Example.main(Example.java:32)
For ubuntu 16.10 are sessions save in /var/lib/php/session/...
Typecasting in Objective-C is easy as:
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
However, what happens if first object is not UIView
and you try to use it:
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
Those assertions doesn't look very nice, so we could improve them with this handy category:
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
This is much better:
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
P.S. For collections type safety Xcode 7 have a much better than typecasting - generics
You could simply have: var result = (str == "true")
.
Resource is a RESTful subset of Endpoint.
An endpoint by itself is the location where a service can be accessed:
https://www.google.com # Serves HTML
8.8.8.8 # Serves DNS
/services/service.asmx # Serves an ASP.NET Web Service
A resource refers to one or more nouns being served, represented in namespaced fashion, because it is easy for humans to comprehend:
/api/users/johnny # Look up johnny from a users collection.
/v2/books/1234 # Get book with ID 1234 in API v2 schema.
All of the above could be considered service endpoints, but only the bottom group would be considered resources, RESTfully speaking. The top group is not expressive regarding the content it provides.
A REST request is like a sentence composed of nouns (resources) and verbs (HTTP methods):
GET
(method) the user named johnny
(resource).DELETE
(method) the book with id 1234
(resource).Endpoint typically refers to a service, but resource could mean a lot of things. Here are some examples of resource that are dependent on the context they're used in.
Something that can be used to help you:
The library was a valuable resource, and he frequently made use of it.
Resources are natural substances such as water and wood which are valuable in supporting life:
[ pl ] The earth has limited resources, and if we don’t recycle them we use them up.
Resources are also things of value such as money or possessions that you can use when you need them:
[ pl ] The government doesn’t have the resources to hire the number of teachers needed.
The term resource by definition has a lot of nuance. It all depends on the context its used in.
join is not a jQuery function .Its a javascript function.
The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
I'd think this should suffice:
#!python
import re
pattern = re.compile(r'<title>([^<]*)</title>', re.MULTILINE|re.IGNORECASE)
pattern.search(text)
... assuming that your text (HTML) is in a variable named "text."
This also assumes that there are not other HTML tags which can be legally embedded inside of an HTML TITLE tag and no way to legally embed any other < character within such a container/block.
However ...
Don't use regular expressions for HTML parsing in Python. Use an HTML parser! (Unless you're going to write a full parser, which would be a of extra work when various HTML, SGML and XML parsers are already in the standard libraries.
If your handling "real world" tag soup HTML (which is frequently non-conforming to any SGML/XML validator) then use the BeautifulSoup package. It isn't in the standard libraries (yet) but is wide recommended for this purpose.
Another option is: lxml ... which is written for properly structured (standards conformant) HTML. But it has an option to fallback to using BeautifulSoup as a parser: ElementSoup.
Best programmatically Understanding.
when syntax is
{}
then this isJsonObject
when syntax is
[]
then this isJsonArray
A JSONObject
is a JSON-like object that can be represented as an element in the JSONArray
. JSONArray
can contain a (or many) JSONObject
Hope this will helpful to you !
Someone over at Ozgrid answered a similar question. Basically, you just copy each sheet one at a time from Workbook1 to Workbook2.
Sub CopyWorkbook()
Dim currentSheet as Worksheet
Dim sheetIndex as Integer
sheetIndex = 1
For Each currentSheet in Worksheets
Windows("SOURCE WORKBOOK").Activate
currentSheet.Select
currentSheet.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(sheetIndex)
sheetIndex = sheetIndex + 1
Next currentSheet
End Sub
Disclaimer: I haven't tried this code out and instead just adopted the linked example to your problem. If nothing else, it should lead you towards your intended solution.
Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.
The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.
Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.
Use FractionallySizedBox
widget.
FractionallySizedBox(
widthFactor: 1.0, // width w.r.t to parent
heightFactor: 1.0, // height w.r.t to parent
child: *Your Child Here*
}
This widget is also very useful when you want to size your child at a fractional of its parent's size.
Example:
If you want the child to occupy 50% width of its parent, provide
widthFactor
as0.5
I know this is an old question but if you want a parseable PHP representation you could use:
$parseablePhpCode = var_export($yourVariable,true);
If you echo the exported code to a file.php (with a return statement) you may require it as
$yourVariable = require('file.php');
You might consider using Font Awesome instead of using the unicode or other icons
The code can be as simple as (a) including font-awesome e.g. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
(b) making a button such as <button><i class="fa fa-arrow-down"></i></button>
You are getting this error because you are calling $apply
inside an existing digestion cycle.
The big question is: why are you calling $apply
? You shouldn't ever need to call $apply
unless you are interfacing from a non-Angular event. The existence of $apply
usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).
If $apply
really is appropriate here, consider using a "safe apply" approach:
1.Define Function to get Token from server
@function
{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
2.Get token and set header before send to server
var token = '@TokenHeaderValue()';
$http({
method: "POST",
url: './MainBackend/MessageDelete',
data: dataSend,
headers: {
'RequestVerificationToken': token
}
}).success(function (data) {
alert(data)
});
3. Onserver Validation on HttpRequestBase on method you handle Post/get
string cookieToken = "";
string formToken = "";
string[] tokens = Request.Headers["RequestVerificationToken"].Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
AntiForgery.Validate(cookieToken, formToken);
I found the possible way to write.
Server Side -
app.get('/main', function(req, res) {
var name = 'hello';
res.render(__dirname + "/views/layouts/main.html", {name:name});
});
Client side (main.html) -
<h1><%= name %></h1>
This function returns the actual used range to the lower right limit. It returns "Nothing" if the sheet is empty.
'2020-01-26
Function fUsedRange() As Range
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim rngLastCell As Range
On Error Resume Next
Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious)
If rngLastCell Is Nothing Then 'look for data backwards in rows
Set fUsedRange = Nothing
Exit Function
Else
lngLastRow = rngLastCell.Row
End If
Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious)
If rngLastCell Is Nothing Then 'look for data backwards in columns
Set fUsedRange = Nothing
Exit Function
Else
lngLastCol = rngLastCell.Column
End If
Set fUsedRange = ActiveSheet.Range(Cells(1, 1), Cells(lngLastRow, lngLastCol)) 'set up range
End Function
I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-
def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
if string[y]==" ":
list_.append(string[x:y])
x = y+1
elif y==len(string)-1:
list_.append(string[x:y+1])
return list_
def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
reversed_list.append(element)
return reversed_list
def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with
space as a separator'''
final_string = str()
for element in list_:
final_string += str(element) + " "
return final_string
#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I
Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!
The installer from the git homepage installs into /usr/local/git by default. See also this answer. However, if you install XCode4, it will install a git version in /usr/bin. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place /usr/local/git/bin before /usr/bin in the $PATH or edit /etc/paths and insert /usr/local/git/bin as the first entry (see this answer).
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
I've had this problem many times before with my Galaxy Nexus. Despite having the Android SDK's USB drivers installed, it did not seem to suffice.
I've always solved this by installing a program called PdaNet. While I don't know exactly what it is used for and where it gets its drivers - it comes with the drivers that has always fixed the problem for me. You can uninstall the program itself once it has finished.
You have in your module
import {Routes, RouterModule} from '@angular/router';
you have to export the module RouteModule
example:
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
to be able to access the functionalities for all who import this module.
To add all untracked files git command is
git add -A
Also if you want to get more details about various available options , you can type command
git add -i
instead of first command , with this you will get more options including option to add all untracked files as shown below :
$ git add -i warning: LF will be replaced by CRLF in README.txt. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in package.json.
* Commands * 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help What now> a
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
The selector would be label[for=email]
, so in CSS:
label[for=email]
{
/* ...definitions here... */
}
...or in JavaScript using the DOM:
var element = document.querySelector("label[for=email]");
...or in JavaScript using jQuery:
var element = $("label[for=email]");
It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.
(I'm assuming that the template {t _your_email}
will fill in a field with id="email"
. If not, use a class instead.)
Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:
label[for="field[]"]
{
/* ...definitions here... */
}
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.
<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->
Otherwise, you can put !important
at the end of your CSS like this: color:#ffffff!important;
but I would advise against using !important
at all costs.
As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
if __name__ == "__main__":
for word in read_words('./very_large_file.txt'):
process(word)
If you are running python version 3.9 pandas wont work as of now. So install python version 3.7 or below to mitigate this issue. Or else if you want to stick with python 3.9 try install pandas by compiling the library
Set the parent div as position:relative
and the inner element to position:absolute; bottom:0
The comment by MK pointed me in the right direction.
In the case of Apache 2.4 and up, there are different defaults and a new directive.
I am running Apache 2.4.6, and I had to add the following directives to get it working:
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
'Fraid so. I'd make an HTML page with a stylesheet, then use jQuery to apply the stylesheet to the style attr of each element. Something like this:
var styleAttributes = ['color','font-size']; // all the attributes you've applied in your stylesheet
for (i in styleAttributes) {
$('body *').css(styleAttributes[i],function () {
$(this).css(styleAttributes[i]);
});
}
Then copy the DOM and use that in the email.
You may try the following:
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
A string literal is delimited by quotation marks and is of type char* not char.
Example: "hello"
So when you compare a char to a char* you will get that same compiling error.
char c = 'c';
char *p = "hello";
if(c==p)//compiling error
{
}
To fix use a char literal which is delimited by single quotes.
Example: 'c'
Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.
Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Just do:
document.body.innerHTML = document.body.innerHTML + '<img src="../images/loaded.gif" alt="" onload="alert(\'test\');this.parentNode.removeChild(this);" />';
I was actually searching for a similar error and Google sent me here to this question. The error was:
The type arguments for method 'IModelExpressionProvider.CreateModelExpression(ViewDataDictionary, Expression>)' cannot be inferred from the usage
I spent maybe 15 minutes trying to figure it out. It was happening inside a Razor .cshtml view file. I had to comment portions of the view code to get to where it was barking since the compiler didn't help much.
<div class="form-group col-2">
<label asp-for="Organization.Zip"></label>
<input asp-for="Organization.Zip" class="form-control">
<span asp-validation-for="Zip" class="color-type-alert"></span>
</div>
Can you spot it? Yeah... I re-checked it maybe twice and didn't get it at first!
See that the ViewModel's property is just Zip
when it should be Organization.Zip
. That was it.
So re-check your view source code... :-)
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();
It is the directory from where you run the command to execute your batch file.
As mentioned in the above answers you can add the below command to your script to verify:
> set current_dir=%cd%
> echo %current_dir%
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
One other thing. You may need to specify the -L option as well - eg
-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz
or you may end up with an error like
ld: cannot find -lbaz
I also experienced this problem and found the easy solution to be
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
This also works with other return types and gives the least amount of problems
The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.
I was having the same problem, but using Long type. I changed for INT and it worked for me.
CREATE TABLE lists (
id INT NOT NULL AUTO_INCREMENT,
desc varchar(30),
owner varchar(20),
visibility boolean,
PRIMARY KEY (id)
);
This can happen if disableContentCompression()
is set on a pooling manager assigned to your HttpClient, and the target server is trying to use gzip compression.
you can try this
class select_choice():
return x, y
a, b = test()
i believe the following code will only run after form1
is closed
while (true)
{
if (form1.Visible == false)
form2.Show();
}
Why not start your form2
from form1
instead?
Form2 form2 = new Form2();
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
form1.Visible=false;
form2.Show();
}
else MessageBox.Show("Insert Attributes First !");
}
First, I add the references to my Model, then I use them in my code. There are two references you should add:
using System.ServiceModel;
using System.Runtime.Serialization;
then, this problem was solved in my program. I hope this answer can help you. Thanks.
As of Pandas version 0.22, there exists also an alternative to apply
: pipe
, which can be considerably faster than using apply
(you can also check this question for more differences between the two functionalities).
For your example:
df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})
my_label
0 A
1 B
2 A
3 C
4 D
5 D
6 E
The apply
version
df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
gives
my_label
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
and the pipe
version
df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
yields
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):
%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop
and
%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop
Wrapping it into a function is then also straightforward:
def get_perc(grp_obj):
gr_size = grp_obj.size()
return gr_size / gr_size.sum()
Now you can call
df.groupby('my_label').pipe(get_perc)
yielding
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
However, for this particular case, you do not even need a groupby
, but you can just use value_counts
like this:
df['my_label'].value_counts(sort=False) / df.shape[0]
yielding
A 0.285714
C 0.142857
B 0.142857
E 0.142857
D 0.285714
Name: my_label, dtype: float64
For this small dataframe it is quite fast
%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop
As pointed out by @anmol, the last statement can also be simplified to
df['my_label'].value_counts(sort=False, normalize=True)
I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)
I got this error many times before, and I am certain all PHP programmer got this error at least once before.
Possible Solution 1
This error may have been caused by the blank spaces before the start of the file or after the end of the file.These blank spaces should not be here.
ex) THERE SHOULD BE NO BLANK SPACES HERE
echo "your code here";
?>
THERE SHOULD BE NO BLANK SPACES HERE
Check all files associated with file that causes this error.
Note: Sometimes EDITOR(IDE) like gedit (a default linux editor) add one blank line on save file. This should not happen. If you are using Linux. you can use VI editor to remove space/lines after ?> at the end of the page.
Possible Solution 2: If this is not your case, then use ob_start to output buffering:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.
Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
Hence -
this.setState({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update. To achieve the above process -
this.setState({data:value},function () {
console.log(this.state.data);
});
You can have a look at dozer which is a
Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
From Version 4.0.0 on RegionUtil
-methods have a new signature. For example:
RegionUtil.setBorderBottom(BorderStyle.DOUBLE,
CellRangeAddress.valueOf("A1:B7"), sheet);
Inject a script into the page you want to get the source from and message it back to the popup....
manifest.json
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
Apply the following CSS:
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
background-repeat: no-repeat;
background-attachment: fixed;
}
Edit: Added margin: 0;
to body declaration per comments (Martin).
Edit: Added background-attachment: fixed;
to body declaration per comments (Johe Green).
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)
public class NonNullThing {
Vector vectorField = new Vector();
int[] arrayField = new int[0];
public NonNullThing() {
// etc
}
}
Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:
#!/bin/bash 2> nul
:; set -o errexit
:; function goto() { return $?; }
command 1 || goto :error
command 2 || goto :error
command 3 || goto :error
:; exit 0
exit /b 0
:error
exit /b %errorlevel%
I have used this type of thing in the past for a multiple platform continuous integration script.
The difference between npm install and npm update handling of package versions specified in package.json:
{
"name": "my-project",
"version": "1.0", // install update
"dependencies": { // ------------------
"already-installed-versionless-module": "*", // ignores "1.0" -> "1.1"
"already-installed-semver-module": "^1.4.3" // ignores "1.4.3" -> "1.5.2"
"already-installed-versioned-module": "3.4.1" // ignores ignores
"not-yet-installed-versionless-module": "*", // installs installs
"not-yet-installed-semver-module": "^4.2.1" // installs installs
"not-yet-installed-versioned-module": "2.7.8" // installs installs
}
}
Summary: The only big difference is that an already installed module with fuzzy versioning ...
npm install
npm update
Additionally: install
and update
by default handle devDependencies differently
npm install
will install/update devDependencies unless --production
flag is addednpm update
will ignore devDependencies unless --dev
flag is addedWhy use npm install
at all?
Because npm install
does more when you look besides handling your dependencies in package.json
.
As you can see in npm install you can ...
PATH
) using npm install -g <name>
--force
If you are just looking for the available colors that already exist with
@android:color/<color>
then you need to look in android.jar >> android >> R.class >> R >> color
.
Here is the list that come with Android 4.4W I'm using:
background_dark
background_light
black
darker_gray
holo_blue_bright
holo_blue_dark
holo_blue_light
holo_green_dark
holo_green_light
holo_orange_dark
holo_orange_light
holo_purple
holo_red_dark
holo_red_light
primary_text_dark
primary_text_dark_nodisable
primary_text_light
primary_text_lignt_nodisable
secondary_text_dark
secondary_text_dark_nodisable
secondaryy_text_light
secondary_text_lignt_nodisable
tab_indicator_text
tertiary_text_dark
tertiary_text_light
transparent
white
widget_edittext_dark
There are some great answers already, but none of them address a complete list of what the __future__
statement currently supports.
Put simply, the __future__
statement forces Python interpreters to use newer features of the language.
The features that it currently supports are the following:
nested_scopes
Prior to Python 2.1, the following code would raise a NameError:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The from __future__ import nested_scopes
directive will allow for this feature to be enabled.
generators
Introduced generator functions such as the one below to save state between successive function calls:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
division
Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y
, whereas floor division is specified by x//y
.
The from __future__ import division
directive forces the use of Python 3.0 style division.
absolute_import
Allows for parenthesis to enclose multiple import
statements. For example:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
LEFT, DISABLED, NORMAL, RIDGE, END)
Instead of:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
Or:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END
with_statement
Adds the statement with
as a keyword in Python to eliminate the need for try/finally
statements. Common uses of this are when doing file I/O such as:
with open('workfile', 'r') as f:
read_data = f.read()
print_function
:
Forces the use of Python 3 parenthesis-style print()
function call instead of the print MESSAGE
style statement.
unicode_literals
Introduces the literal syntax for the bytes
object. Meaning that statements such as bytes('Hello world', 'ascii')
can be simply expressed as b'Hello world'
.
generator_stop
Replaces the use of the StopIteration
exception used inside generator functions with the RuntimeError
exception.
One other use not mentioned above is that the __future__
statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.
I got confused by the answer to this question, so I created a test case in MySQL, hope this helps
-- Schema
CREATE TABLE T1 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE T2 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE TT (
`IDT1` int not null,
`IDT2` int not null,
primary key (`IDT1`,`IDT2`)
);
ALTER TABLE `TT`
ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);
-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
My original suggestion was
s12 := fmt.Sprint(s1,s2)
But above answer using bytes.Buffer - WriteString() is the most efficient way.
My initial suggestion uses reflection and a type switch. See (p *pp) doPrint
and (p *pp) printArg
There is no universal Stringer() interface for basic types, as I had naively thought.
At least though, Sprint() internally uses a bytes.Buffer. Thus
`s12 := fmt.Sprint(s1,s2,s3,s4,...,s1000)`
is acceptable in terms of memory allocations.
=> Sprint() concatenation can be used for quick debug output.
=> Otherwise use bytes.Buffer ... WriteString
Go to "Tomcat Directory"/bin directory
if Linux then create setenv.sh else if Windows then create setenv.bat
content of setenv.* file :
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
after this restart tomcat with new params.
explanation and full information is here
http://crunchify.com/how-to-change-jvm-heap-setting-xms-xmx-of-tomcat/
Try like this.
You must give a function as value to onClick()
You button:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
refreshPage function:
function refreshPage(){
window.location.reload();
}
I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py
uses to reload modules.
This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.
def reload_module(full_module_name):
"""
Assuming the folder `full_module_name` is a folder inside some
folder on the python sys.path, for example, sys.path as `C:/`, and
you are inside the folder `C:/Path With Spaces` on the file
`C:/Path With Spaces/main.py` and want to re-import some files on
the folder `C:/Path With Spaces/tests`
@param full_module_name the relative full path to the module file
you want to reload from a folder on the
python `sys.path`
"""
import imp
import sys
import importlib
if full_module_name in sys.modules:
module_object = sys.modules[full_module_name]
module_object = imp.reload( module_object )
else:
importlib.import_module( full_module_name )
def run_tests():
print( "\n\n" )
reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )
from .tests import semantic_linefeed_unit_tests
from .tests import semantic_linefeed_manual_tests
semantic_linefeed_unit_tests.run_unit_tests()
semantic_linefeed_manual_tests.run_manual_tests()
if __name__ == "__main__":
run_tests()
If you run for the first time, this should load the module, but if later you can again the method/function run_tests()
it will reload the tests files. With Sublime Text (Python 3.3.6
) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3
interpreter).
The solution is to create the php.ini file under your root directory. If the site is the wordpress installation then create the php.ini under your/path/to/wordpress/wp-admin/php.ini and add the following line of codes
[PHP]
post_max_size=120M
upload_max_filesize=132M
I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).
@echo off
setlocal
set "str=string1&with spaces by string2&with spaces.txt"
set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"
echo "%string1%"
echo "%string2%"
For further details on the split method, see this post.
I agree with the current answers, I just wanna add little more information, Here's a good functionality
if you want to require just zip file but the owner has not prepared a zip file,
To simply download a repository as a zip file: add the extra path /zipball/master/ to the end of the repository URL, This will give you a full ZIP file
For example, here is your repository
https://github.com/spring-projects/spring-data-graph-examples
Add zipball/master/ in your repository link
https://github.com/spring-projects/spring-data-graph-examples/zipball/master/
Paste the URL into your browser and it will give you a zip file to download
Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
Many answers here conflate type-safety with static-typing and dynamic-typing. A dynamically typed language (like smalltalk) can be type-safe as well.
A short answer: a language is considered type-safe if no operation leads to undefined behavior. Many consider the requirement of explicit type conversions necessary for a language to be strictly typed, as automatic conversions can sometimes leads to well defined but unexpected/unintuitive behaviors.
SQL Server Management Studio 2008 R2 Express commandline:
The answer by dyslexicanaboko hits the crucial point, but this one is even simpler and suited for command line (unattended scenarios):
(tried out with SQL Server 2008 R2 Express, one instance installed and having downloaded SQLManagementStudio_x64_ENU.exe)
As pointed out in this thread often enough, it is better to use the original SQL server setup (e.g. SQL Express with Tools), if possible, but there are some scenarios, where you want to add SSMS at a SQL derivative without that tools, afterwards:
I´ve already put it in a batch syntax here:
@echo off
"%~dp0SQLManagementStudio_x64_ENU.exe" /Q /ACTION="Install" /FEATURES="SSMS" /IACCEPTSQLSERVERLICENSETERMS
Remarks:
For 2008 without R2 it should be enough to omit the /IACCEPTSQLSERVERLICENSETERMS flag, i guess.
The /INDICATEPROGRESS parameter is useless here, the whole command takes a number of minutes and is 100% silent without any acknowledgement. Just look at the start menu, if the command is ready, if it has succeeded.
This should work for the "ADV_SSMS" Feature (instead of "SSMS") too, which is the management studio extended variant (profiling, reporting, tuning, etc.)
No need to use BufferedImage, as you already have the image file in a byte array
byte dearr[] = Base64.decodeBase64(crntImage);
FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp"));
fos.write(dearr);
fos.close();
In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.
/workspace/android-support-v7-appcompat
being a common one.
In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.
To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.
<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>
That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
}
Add the following script:
<script type="text/javascript">
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '');
replace(/\*\/[^\/]+$/, '');
}
function run_onload() {
console.log("Sample text for console");
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
var fragment = document.createDocumentFragment();
for (var i = 0; i < filenames.length; ++i) {
var extension = filenames[i].substring(filenames[i].length-3);
if (extension == "png" || extension == "jpg") {
var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);
var image = document.createElement("img");
image.className = "fancybox";
image.src = "images/" + filenames[i];
fragment.appendChild(image);
}
}
document.getElementById("images").appendChild(fragment);
}
</script>
then create a js file with the following:
var g_FOLDER_CONTENTS = mlString(function() { /*!
1.png
2.png
3.png
*/});
A multiple select is really just a select with a multiple
attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the []
will return it as an array when you use Input::get('sports')
.
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple
property to the actual select element..
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
In View use this:
form.field.errors|striptags
for getting validation messages without html
Input elements are inline by default. Add display:block
to get the margins to apply. This will, however, break the buttons onto two separate lines. Use a wrapping <div>
with text-align: center
as suggested by others to get them on the same line.
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
If you are in same WORKGROUP you need software to connect and control the target server.shutdown.exe /s /m \\<target-computer-name>
should be enough shutdown /?
for more, otherwise
UPDATE:
Seems shutdown.bat here is for shutting down apache-tomcat.
So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client
As native solution could be wmic
Example:
wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"
In your example should be:
wmic /node:inidsoasrv01 process call create ^
"cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"
wmic /?
and wmic /node /?
for more
A lot of student exercises use Scanner
because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:
import java.io.*;
public class FilterLine {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
}
}
Very old question, but in case someone else stumbles across it, I would recommend trying:
$j("html, body").stop(true, true).animate({
scrollTop: $j('#main').offset().top
}, 300);
You can even say:
FollowHyperlink "www.google.com"
If you get Automation Error then use http://
:
ThisWorkbook.FollowHyperlink("http://www.google.com")
It seems that your nginx hasn't been installed correctly. Pay attention to the output of the installation commands:
sudo apt-get install nginx
To check the nginx version, you can use this command:
$ nginx -v
nginx version: nginx/0.8.54
$ nginx -V
nginx version: nginx/0.8.54
TLS SNI support enabled
configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module --add-module=/build/buildd/nginx-0.8.54/debian/modules/nginx-upstream-fair
For more information: http://nginxlibrary.com/check-nginx-version/
You can use -v
parameter to display the Nginx version only, or use the -V
parameter to display the version, along with the compiler version and configuration parameters.
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
Most easiest way in a single line of code
var base64Image = new Buffer( blob, 'binary' ).toString('base64');
You can do with create new one like this.
var list1 = ArrayList<Int>()
var list2 = list1.toMutableList()
list2.add(item)
Now you can use list2, Thank you.
To long from DateTime:
To DateTime from long:
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
USING PHP, HTML AND JAVASCRIPT for prompting
Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.
<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>
the reason i used php code in the middle is because i cant use it from the beginning..
the code below doesnt work for me:-
echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";
and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.
if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.
<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
<item name="android:windowLightStatusBar" tools:targetApi="23">true</item>
struct
and typedef
are two very different things.
The struct
keyword is used to define, or to refer to, a structure type. For example, this:
struct foo {
int n;
};
creates a new type called struct foo
. The name foo
is a tag; it's meaningful only when it's immediately preceded by the struct
keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespace
s.)
A typedef
, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:
typedef int my_int;
my_int
is a new name for int
; my_int
and int
are exactly the same type. Similarly, given the struct
definition above, you can write:
typedef struct foo foo;
The type already has a name, struct foo
. The typedef
declaration gives the same type a new name, foo
.
The syntax allows you to combine a struct
and typedef
into a single declaration:
typedef struct bar {
int n;
} bar;
This is a common idiom. Now you can refer to this structure type either as struct bar
or just as bar
.
Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct
version to refer to it:
typedef struct node {
int data;
struct node *next; /* can't use just "node *next" here */
} node;
Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:
typedef struct node_s {
/* ... */
} node;
(Personally, I prefer to omit the typedef
and refer to the type as struct bar
. The typedef
save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n
by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)
(C++ has different rules. Given a declaration of struct blah
, you can refer to the type as just blah
, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
You can define attributes for your properties.
[StringLength(100)]
public string Body { get; set; }
This is known as System.ComponentModel.DataAnnotations
.
If you can't find the ValidationAttribute
that you need you can allways define custom attributes.
Best Regards, Carlos
import org.apache.spark.sql.functions.desc
df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))
<li *ngFor="let obj of myArray">{{obj | json}}</li>
The output window isn't the console. Try the methods in System.Diagnostics.Debug
Tried this in the console, and it works.
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));
classes are specially made for this, here is the code from which you can understand
<html>
<head>
<style type="text/css">
.personal{
height:100px;
width: 100px;
}
.fam{
border: 2px solid #ccc;
}
.x{
background-color:#ccc;
}
</style>
</head>
<body>
<div class="personal fam x"></div>
</body>
</html>
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
All these others answers make sense, but are incomplete. Visual Studio will process XML comments but you have to turn them on. Here's how to do that:
Intellisense will use XML comments you enter in your source code, but you must have them enabled through Visual Studio Options. Go to Tools
> Options
> Text Editor
. For Visual Basic, enable the Advanced
> Generate XML documentation comments for '''
setting. For C#, enable the Advanced
> Generate XML documentation comments for ///
setting. Intellisense will use the summary comments when entered. They will be available from other projects after the referenced project is compiled.
To create external documentation, you need to generate an XML file through the Project Settings
> Build
> XML documentation file:
path that controls the compiler's /doc
option. You will need an external tool that will take the XML file as input and generate the documentation in your choice of output formats.
Be aware that generating the XML file can noticeably increase your compile time.
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has
.bind("change", function(){ ... });
Or
.change(function(){ ... });
which are equivalents.
for a unique selector change your name attribute to id and then jQuery("#imafile")
or a general jQuery('input[type="file"]')
for all the file inputs
You cannot use CSS for this purpose. I recommend using JavaScript if it's applicable. Take a look at this for more information: JavaScript equivalent to printf/string.format
Also As Petr mentioned you can handle it on server-side but it's totally depends on your scenario.
If you are using form data to upload file,in which a parameter name must be specified , you can use:
curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
just for future reference:
function getscreenresolution()
{
window.alert("Your screen resolution is: " + screen.height + 'x' + screen.width);
}
The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.
A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.
Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.
Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).
With that in mind, GOAs can be initialised like this:
namespace {
T1 * pt1 = NULL;
T2 * pt2 = NULL;
T3 * pt3 = NULL;
T4 * pt4 = NULL;
}
int main( int argc, char* argv[])
{
T1 t1(args1);
T2 t2(args2);
T3 t3(args3);
T4 t4(args4);
pt1 = &t1;
pt2 = &t2;
pt3 = &t3;
pt4 = &t4;
dostuff();
}
T1& getT1()
{
return *pt1;
}
T2& getT2()
{
return *pt2;
}
T3& getT3()
{
return *pt3;
}
T4& getT4()
{
return *pt4;
}
It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).
As for when I use singletons? I used them for 2 things - A singleton table that indicates what libraries have been loaded with dlopen - A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.
If you don't want to pass the parameter when you don't want to search, then you should make the parameter optional instead of assuming that ''
and NULL
are the same thing.
ALTER PROCEDURE [dbo].[psProducts]
(
@SearchType varchar(50) = NULL
)
AS
BEGIN
SET NOCOUNT ON;
SELECT P.[ProductId]
,P.[ProductName]
,P.[ProductPrice]
,P.[Type]
FROM dbo.[Product] AS P
WHERE p.[Type] = COALESCE(NULLIF(@SearchType, ''), p.[Type]);
END
GO
Now if you pass NULL
, an empty string (''
), or leave out the parameter, the where clause will essentially be ignored.
in my case: invalidateOptionsMenu
just re-setted the text to the original one,
but directly accessing the menu item and re-writing the desire text worked without problems:
if (mnuTopMenuActionBar_ != null) {
MenuItem mnuPageIndex = mnuTopMenuActionBar_
.findItem(R.id.menu_magazin_pageOfPage_text);
if (mnuPageIndex != null) {
if (getScreenOrientation() == 1) {
mnuPageIndex.setTitle((i + 1) + " von " + pages);
}
else {
mnuPageIndex.setTitle(
(i + 1) + " + " + (i + 2) + " " + " von " + pages);
}
// invalidateOptionsMenu();
}
}
due to the comment below, I was able to access the menu item via the following code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.magazine_swipe_activity, menu);
mnuTopMenuActionBar_ = menu;
return true;
}
You don't need to learn JPA. You can use my easy-criteria for JPA2 (https://sourceforge.net/projects/easy-criteria/files/). Here is the example
CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(Ower_.name,EQUAL, "foo");
List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);
OR
List<Tuple> result = CriteriaProcessor.findAllTuple(petCriteria);
String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
byteData[start + i] = byteSalt[i];
}
The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:
for (int i = 0; i < byteData.length; i ++)
with:
for (int i = 0; i < byteSalt.length; i ++)
Actually just adding margin-bottom: -20px; to the tag class fixed it right up.
Being block elements, div's naturally have defined borders that they try not to violate. To get them to layer for images, which have no content beside the image because they have no closing tag, you just have to force them to do what they do not want to do, like violate their natural boundaries.
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
}
.tag {
float: left;
position: relative;
left: 0px;
top: 0px;
background-color: green;
z-index: 1000;
margin-bottom: -20px;
}
Another toue to take would be to create div's using an image as the background, and then place content where ever you like.
<div id="imgContainer" style="
background-image: url("foo.jpg");
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
-mox-background-size: cover;
-o-background-size: cover;">
<div id="theTag">BLAH BLAH BLAH</div>
</div>
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
High cohesion within modules and low coupling between modules are often regarded as related to high quality in OO programming languages.
For example, the code inside each Java class must have high internal cohesion, but be as loosely coupled as possible to the code in other Java classes.
Chapter 3 of Meyer's Object-Oriented Software Construction (2nd edition) is a great description of these issues.
public DataTable TopDataRow(DataTable dt, int count)
{
DataTable dtn = dt.Clone();
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i < count)
{
dtn.ImportRow(row);
i++;
}
if (i > count)
break;
}
return dtn;
}
This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5
in this case) will be? Then I can try to provide a more complete answer.
Sub setCondFormat()
Range("B3").Select
With Range("B3:H63")
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
End With
End With
End With
End Sub
Note: this is tested in Excel 2010.
Edit: Updated code based on comments.
The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.
I'd say just use a while loop:
i = 0.0
while i <= 1.0:
print i
i += 0.1
If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.
The correct fix is to add the property in the type definition as explained by @Nitzan Tomer.
But also you can just define property as any
, if you want to write code almost as in JavaScript:
arr.filter((item:any) => {
return item.isSelected == true;
}
If you use Python3x then string
is not the same type as for Python 2.x, you must cast it to bytes (encode it).
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
Also do not use variable names like string
or file
while those are names of module or function.
EDIT @Tom
Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:
plaintext = 'Polish text: acelnószzACELNÓSZZ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
outfile_content = infile.read().decode('UTF-8')
print(outfile_content)
Their are a few differences.
#define HELLO "Hello World"
The statement above can be used with preprocessor and can only be change in the preprocessor.
const char *HELLO2 = "Howdy";
The statement above can be changed with c code. Now you can't change the each individual character around like the statement below because its constant.
HELLO2[0] = 'a'
But you what you can do is have it point to a different string like the statement below
HELLO2 = "HELLO WOLRD"
It really depends on how you want to be able to change the variable around. With the preprocessor or c code.
You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)
To move (to & from) a single string field you must use strncpy
and a transient string buffer '\0'
terminating.
Somewhere you must remember the length of the record string field.
To move other fields you can use the dot notation, ex.:
NodeB->one=intvar;
floatvar2=(NodeA->insidebisnode_subvar).myfl;
struct mynode {
int one;
int two;
char txt3[3];
struct{char txt2[6];}txt2fi;
struct insidenode{
char txt[8];
long int myl;
void * mypointer;
size_t myst;
long long myll;
} insidenode_subvar;
struct insidebisnode{
float myfl;
} insidebisnode_subvar;
} mynode_subvar;
typedef struct mynode* Node;
...(main)
Node NodeA=malloc...
Node NodeB=malloc...
You can embed each string into a structs that fit it,
to evade point-2 and behave like Cobol:
NodeB->txt2fi=NodeA->txt2fi
...but you will still need of a transient string
plus one strncpy
as mentioned at point-2 for scanf
, printf
otherwise an operator longer input (shorter),
would have not be truncated (by spaces padded).
(NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer
will create a pointer alias.NodeB.txt3=NodeA.txt3
causes the compiler to reject:
error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
point-4 works only because NodeB->txt2fi
& NodeA->txt2fi
belong to the same typedef
!!
A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!
I don't know if the solution below is more or less efficient than jspcal's answer, but I'm pretty sure it requires less object creation than Jamie's and George's.
string s = "THIS IS MY TEXT RIGHT NOW";
StringBuilder sb = new StringBuilder(s.Length);
bool capitalize = true;
foreach (char c in s) {
sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
capitalize = !Char.IsLetter(c);
}
return sb.ToString();
A checkbox has a linked cell, which contains the True/False representing the state of the checkbox. It is much easier to reference this cell's value than the value of the embedded object which is the checkbox.
Manually: Right click on the checkbox, choose Format, click in the Linked Cell box, and select the cell to contain the checkbox value.
In code:
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Value = xlOff ' = unchecked xlOn = checked
.LinkedCell = "$A$1"
End With
Look up NR
and FNR
in the awk manual and then ask yourself what is the condition under which NR==FNR
in the following example:
$ cat file1
a
b
c
$ cat file2
d
e
$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e
How about just chaining the greps?
grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'
You can use:
navigator.userAgent.indexOf("Chrome") != -1
It is working on v.71