Check all the references carefully
For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.
Hi it was a challenge to get it work on Mac so anyway here is a solution
rvm requirements
then run rvm install 2.1
gem install compass --pre
I'm not sure but ruby version on Mavericks doesn't support native extensions etc... so if you point to other ruby version like I did "2.1" it works fine.
Make sure that the column values u added in entity class having get set properties also in the same order which is present in target table.
I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.
I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.
The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)
From: http://technet.microsoft.com/en-us/library/ee681792.aspx:
"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."
Edit:
Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE
returned.
If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week
which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll
.
Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206
I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.
Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.
I suspect you haven't set up last_name
properly in the caller.
With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
this will only work if last_name
is a string, i.e.
Dim last_name as String
appears in the caller somewhere.
The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.
1) Force ByVal -- Change your function to pass variable ByVal: Public Function ProcessString(ByVal input_string As String) As String
, or
2) Dim varname -- put Dim last_name As String
in the caller before you use it.
(1) works because for ByVal
, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
Ran into this issue today (Excel crashes on adding rows using .ListRows.Add
).
After reading this post and checking my table, I realized the calculations of the formula's in some of the cells in the row depend on a value in other cells.
In my case of cells in a higher column AND even cells with a formula!
The solution was to fill the new added row from back to front, so calculations would not go wrong.
Excel normally can deal with formula's in different cells, but it seems adding a row in a table kicks of a recalculation in order of the columns (A,B,C,etc..).
Hope this helps clearing issues with .ListRows.Add
No, you can't cast Integer
to Long
, even though you can convert from int
to long
. For an individual value which is known to be a number and you want to get the long value, you could use:
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();
For arrays, it will be trickier...
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
Well, the straightforward method is to create an appropriate class/structure which holds all your parameter values and pass that to the thread.
Another solution in VB10 is to use the fact that lambdas create a closure, which basically means the compiler doing the above automatically for you:
Dim evaluator As New Thread(Sub()
testthread(goodList, 1)
End Sub)
There are two problems:
Integer#set(i)
. You could otherwise just make use of it.To get it to work, you need to reassign the return value of the inc()
method.
integer = inc(integer);
To learn a bit more about passing by value, here's another example:
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
changeReference(strings);
System.out.println(Arrays.toString(strings)); // still [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.
Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"
I recently ran into this issue and none of the solutions proposed fixed it. The issue turned out to be an excessive use of datasets stored in the session. There was a flaw in the code that results in the session size to increase 10x.
There is an article on the msdn blog that also talks about this. http://blogs.msdn.com/b/johan/archive/2006/11/20/sessionstate-performance.aspx
I used a function to write custom trace messages to measure the size of the session data on the live site.
Technically, Python always uses pass by reference values. I am going to repeat my other answer to support my statement.
Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. Any variable is the name bound to the reference value. Always.
You can think about a reference value as the address of the target object. The address is automatically dereferenced when used. This way, working with the reference value, it seems you work directly with the target object. But there always is a reference in between, one step more to jump to the target.
Here is the example that proves that Python uses passing by reference:
If the argument was passed by value, the outer lst
could not be modified. The green are the target objects (the black is the value stored inside, the red is the object type), the yellow is the memory with the reference value inside -- drawn as the arrow. The blue solid arrow is the reference value that was passed to the function (via the dashed blue arrow path). The ugly dark yellow is the internal dictionary. (It actually could be drawn also as a green ellipse. The colour and the shape only says it is internal.)
You can use the id()
built-in function to learn what the reference value is (that is, the address of the target object).
In compiled languages, a variable is a memory space that is able to capture the value of the type. In Python, a variable is a name (captured internally as a string) bound to the reference variable that holds the reference value to the target object. The name of the variable is the key in the internal dictionary, the value part of that dictionary item stores the reference value to the target.
Reference values are hidden in Python. There isn't any explicit user type for storing the reference value. However, you can use a list element (or element in any other suitable container type) as the reference variable, because all containers do store the elements also as references to the target objects. In other words, elements are actually not contained inside the container -- only the references to elements are.
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
In your example, you prepended your source string with AccountKey=
but not your target string.
$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
By not including that in the target string, the resulting string will remove AccountKey=
instead of replacing it. You correctly do this with the AccountName=
example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.
for a solution that really works
html
<remove ng-repeat-start="itemGroup in Groups" ></remove>
html stuff in here including inner repeating loops if you want
<remove ng-repeat-end></remove>
add an angular.js directive
//remove directive
(function(){
var remove = function(){
return {
restrict: "E",
replace: true,
link: function(scope, element, attrs, controller){
element.replaceWith('<!--removed element-->');
}
};
};
var module = angular.module("app" );
module.directive('remove', [remove]);
}());
for a brief explanation,
ng-repeat binds itself to the <remove>
element and loops as it should, and because we have used ng-repeat-start / ng-repeat-end it loops a block of html not just an element.
then the custom remove directive places the <remove>
start and finish elements with <!--removed element-->
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
Steps to solve this problem
note: This problem mainly occurs due to which we haven't assigned our user name and email id in git so what we gonna do is assigning it in git
Open git that you have installed
Now we have to assign our user name and email id
Just type git config --user.name <your_name>
and click enter
(you can mention or type any name you want)
Similarly type git config --user.email <[email protected]>
and
click enter (you have to type your primary mail id)
And that's it.
Have a Good Day!!!.
I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.
how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;
PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0
(swedish translated: 'It is not possible to find the module' )
in this perticular case, the php.ini was: extension_dir = "C:/php"
the dll is put in two places C:\php and C:\php\ext
IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??
I think the easiest way is to do it through the command line like David mentions. The only trick is that the .dll isn't simply located at C:\Windows\Assembly. You have to navigate to C:\Windows\Assembly\GAC\[ASSEMBLY_NAME]\[VERSION_NUMBER]_[PUBLIC KEY]. You can then do a copy using:
copy [ASSEMBLY_NAME].dll c:\ (or whatever location you want)
Hope that helps.
jQuery handles this easy.
let element = $(.myclass);
element.html("Some string");
It changes all the .myclass elements to that text.
my_var: the variable declared
VAR: the variable, whose value is to be checked
param_1, param_2: values of the variable VAR
value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var
my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"
Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.
$(python -c 'print "export MY_DATA=my_export"')
(you can also enclose the statement in backticks in some shells ``)
I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.
Here are some of the db fields i'm using.
id (auto incremented)
name
email
text
datetime
approved
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
I got same problem but different reason. I had "reg.bat" in the current directory. Renaming that into anything else solved the issue.
If you want to make sure that the string is neither red, green nor blue, caskey's answer is it. What is often wanted, however, is to make sure that the line does not contain red, green or blue anywhere in it. For that, anchor the regular expression with ^
and include .*
in the negative lookahead:
^(?!.*(red|green|blue))
Also, suppose that you want lines containing the word "engine" but without any of those colors:
^(?!.*(red|green|blue)).*engine
You might think you can factor the .*
to the head of the regular expression:
^.*(?!red|green|blue)engine # Does not work
but you cannot. You have to have both instances of .*
for it to work.
AngerClown pointed me to the right direction.
This is what I finally did, just in case anyone find it useful.
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<!-- jackson configuration : https://stackoverflow.com/questions/3661769 -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_DEFAULT</value>
</list>
</property>
</bean>
I still have to figure out how to configure the other properties such as:
om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?
/^my/
Import paths are relative to your $GOPATH
and $GOROOT
environment variables. For example, with the following $GOPATH
:
GOPATH=/home/me/go
Packages located in /home/me/go/src/lib/common
and /home/me/go/src/lib/routers
are imported respectively as:
import (
"lib/common"
"lib/routers"
)
you should add charset=UTF-8 in meta tag and use json_encode for special characters
$json = json_encode($arr);
json_encode function converts special characters in UTF8 standard
You can use these ANSI escape codes:
Black 0;30 Dark Gray 1;30
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
Cyan 0;36 Light Cyan 1;36
Light Gray 0;37 White 1;37
And then use them like this in your script:
# .---------- constant part!
# vvvv vvvv-- the code from above
RED='\033[0;31m'
NC='\033[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow\n"
which prints love
in red.
From @james-lim's comment, if you are using the echo
command, be sure to use the -e flag to allow backslash escapes.
# Continued from above example
echo -e "I ${RED}love${NC} Stack Overflow"
(don't add "\n"
when using echo
unless you want to add an additional empty line)
You can use expandtabs
to specify the tabstop, like this:
>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
Could be that using the numeral code is more universal, as it's a direct reference to a character in the html entity table, but I guess they both work everywhere. The first notation is just massively easier to remember for a lot of characters.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
I typically perform the validation on the client side:
<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server" />
<asp:CustomValidator id="vTerms"
ClientValidationFunction="validateTerms"
ErrorMessage="<br/>Terms and Conditions are required."
ForeColor="Red"
Display="Static"
EnableClientScript="true"
ValidationGroup="vg"
runat="server"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
<script>
function validateTerms(source, arguments) {
var $c = $('#<%= chkTerms.ClientID %>');
if($c.prop("checked")){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
My solution is to cover all the range of diacritics:
([A-z0-9À-ž\s]){2,}
A-z
- this is for all latin characters
0-9
- this is for all digits
À-ž
- this is for all diacritics
\s
- this is for spaces
{2,}
- string needs to be at least 2 characters long
declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
It can be used like this, with validation functions:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
You would normally use -stringWithFormat
here.
NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];
You can use
cat file.txt | xargs -i sh -c 'command {} | command2 {} && command3 {}'
{} = variable for each line on the text file
If you want to create a tag from a branch which is something like release/yourbranch
etc
Then you should use something like
git tag YOUR_TAG_VERSION_OR_NAME origin/release/yourbranch
After creating proper tag if you wish to push the tag to remote then use the command
git push origin YOUR_TAG_VERSION_OR_NAME
The complete code is given below
package com.testingContect;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class testingContect extends Activity implements OnClickListener{
/** Called when the activity is first created. */
EditText ed;
Button bt;
int PICK_CONTACT;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt=(Button)findViewById(R.id.button1);
ed =(EditText)findViewById(R.id.editText1);
ed.setOnClickListener(this);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
break;
case R.id.editText1:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(this, "Contect LIST = "+name, Toast.LENGTH_LONG).show();
}
}//onActivityResult
}//class ends
Replace
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
by
f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")
What tutorial are you using?
first , you dont need to use a local assigment for your job, just check the above answer
second, its simple to use locals() and globals() to got the variables table and then change the value
check this sample code:
print [locals().__setitem__('x', 'Hillo :]'), x][-1]
if you need to change the add a global variable to your environ, try to replace locals() with globals()
python's list comp is cool but most of the triditional project dont accept this(like flask :[)
hope it could help
From a performance point of view, Implicit cursors are faster.
Let's compare the performance between an explicit and implicit cursor:
SQL> DECLARE
2 l_loops NUMBER := 100000;
3 l_dummy dual.dummy%TYPE;
4 l_start NUMBER;
5 -- explicit cursor declaration
6 CURSOR c_dual IS
7 SELECT dummy
8 FROM dual;
9 BEGIN
10 l_start := DBMS_UTILITY.get_time;
11 -- explicitly open, fetch and close the cursor
12 FOR i IN 1 .. l_loops LOOP
13 OPEN c_dual;
14 FETCH c_dual
15 INTO l_dummy;
16 CLOSE c_dual;
17 END LOOP;
18
19 DBMS_OUTPUT.put_line('Explicit: ' ||
20 (DBMS_UTILITY.get_time - l_start) || ' hsecs');
21
22 l_start := DBMS_UTILITY.get_time;
23 -- implicit cursor for loop
24 FOR i IN 1 .. l_loops LOOP
25 SELECT dummy
26 INTO l_dummy
27 FROM dual;
28 END LOOP;
29
30 DBMS_OUTPUT.put_line('Implicit: ' ||
31 (DBMS_UTILITY.get_time - l_start) || ' hsecs');
32 END;
33 /
Explicit: 332 hsecs
Implicit: 176 hsecs
PL/SQL procedure successfully completed.
So, a significant difference is clearly visible. Implicit cursor is much faster than an explicit cursor.
More examples here.
To remove one or more double quotes from the start and end of a string in Java, you need to use a regex based solution:
String result = input_str.replaceAll("^\"+|\"+$", "");
If you need to also remove single quotes:
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
NOTE: If your string contains "
inside, this approach might lead to issues (e.g. "Name": "John"
=> Name": "John
).
See a Java demo here:
String input_str = "\"'some string'\"";
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
System.out.println(result); // => some string
For windows eclipse using java: Windows -> Preferences -> Java -> Editor -> Folding
Unfortunately this will not allow for collapsing code, however if it turns off you can re-enable it to get rid of long comments and imports.
You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:
process(b0,b1,b2,b3)
variable bcat : std_logic_vector(0 to 3);
begin
bcat := b0 & b1 & b2 & b3;
case bcat is
when "0000" => x <= 1;
when others => x <= 2;
end case;
end process;
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
This diagram will be faster to read next time. Maybe someone else will find that helpful too. This is clearly explained the difference between.
Either Collections.emptyMap()
, or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()
declare @hours int = 5;
select dateadd(hour,@hours,getdate())
It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:
2015-03-04T00:00:00.000Z //Complete ISO-8601 date
If you try to parse this date as it is you will receive an Invalid Date
error:
new Date('T00:00:00.000Z'); // Invalid Date
So, I guess the way to parse a timestamp in this format is to concat with any date
new Date('2015-03-04T00:00:00.000Z'); // Valid Date
Then you can extract only the part you want (timestamp part)
var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
Keep these three options in mind (you want #3):
1) Whole element is transparent:
visibility: hidden;
2) Whole element is somewhat transparent:
opacity: 0.0 - 1.0;
3) Just the background of the element is transparent:
background-color: transparent;
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:
var offset = $('#whatever').offset();
offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"
#define GENERAL__GET_BITS_FROM_U8(source,lsb,msb) \
((uint8_t)((source) & \
((uint8_t)(((uint8_t)(0xFF >> ((uint8_t)(7-((uint8_t)(msb) & 7))))) & \
((uint8_t)(0xFF << ((uint8_t)(lsb) & 7)))))))
#define GENERAL__GET_BITS_FROM_U16(source,lsb,msb) \
((uint16_t)((source) & \
((uint16_t)(((uint16_t)(0xFFFF >> ((uint8_t)(15-((uint8_t)(msb) & 15))))) & \
((uint16_t)(0xFFFF << ((uint8_t)(lsb) & 15)))))))
#define GENERAL__GET_BITS_FROM_U32(source,lsb,msb) \
((uint32_t)((source) & \
((uint32_t)(((uint32_t)(0xFFFFFFFF >> ((uint8_t)(31-((uint8_t)(msb) & 31))))) & \
((uint32_t)(0xFFFFFFFF << ((uint8_t)(lsb) & 31)))))))
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
Standard way:
@RestController
public class Main {
UserService userService;
public Main(){
userService = new UserServiceImpl();
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
User service interface:
public interface UserService {
String print(String text);
}
UserServiceImpl class:
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
That is a great example of tight coupled classes, bad design example and there will be problem with testing (PowerMockito is also bad).
Now let's take a look at SpringBoot dependency injection, nice example of loose coupling:
Interface remains the same,
Main class:
@RestController
public class Main {
UserService userService;
@Autowired
public Main(UserService userService){
this.userService = userService;
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
ServiceUserImpl class:
@Component
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
and now it's easy to write test:
@RunWith(MockitoJUnitRunner.class)
public class MainTest {
@Mock
UserService userService;
@Test
public void indexTest() {
when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");
String result = new Main(userService).index();
assertEquals(result, "Example test UserServiceImpl");
}
}
I showed @Autowired
annotation on constructor but it can also be used on setter or field.
First of all, thanks to everyone who posted their answers. Here is my "ultimate" wget script to download a website recursively:
wget --recursive ${comment# self-explanatory} \
--no-parent ${comment# will not crawl links in folders above the base of the URL} \
--convert-links ${comment# convert links with the domain name to relative and uncrawled to absolute} \
--random-wait --wait 3 --no-http-keep-alive ${comment# do not get banned} \
--no-host-directories ${comment# do not create folders with the domain name} \
--execute robots=off --user-agent=Mozilla/5.0 ${comment# I AM A HUMAN!!!} \
--level=inf --accept '*' ${comment# do not limit to 5 levels or common file formats} \
--reject="index.html*" ${comment# use this option if you need an exact mirror} \
--cut-dirs=0 ${comment# replace 0 with the number of folders in the path, 0 for the whole domain} \
$URL
Afterwards, stripping the query params from URLs like main.css?crc=12324567
and running a local server (e.g. via python3 -m http.server
in the dir you just wget'ed) to run JS may be necessary. Please note that the --convert-links
option kicks in only after the full crawl was completed.
Also, if you are trying to wget a website that may go down soon, you should get in touch with the ArchiveTeam and ask them to add your website to their ArchiveBot queue.
A matrix is actually an array of arrays.
int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
Of course, to delete the matrix, you should do the following:
for (int i = 0; i < rows; ++i)
delete [] matrix[i];
delete [] matrix;
I have just figured out another possibility:
int rows = ..., cols = ...;
int** matrix = new int*[rows];
if (rows)
{
matrix[0] = new int[rows * cols];
for (int i = 1; i < rows; ++i)
matrix[i] = matrix[0] + i * cols;
}
Freeing this array is easier:
if (rows) delete [] matrix[0];
delete [] matrix;
This solution has the advantage of allocating a single big block of memory for all the elements, instead of several little chunks. The first solution I posted is a better example of the arrays of arrays concept, though.
1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell
. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view.
But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question
2)NSIndexPath
is essentially two things-
Because your table might be divided to many sections and each with its own rows, this NSIndexPath
will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.
It is called if you implement the UITableViewDataSource
protocol in your view controller. A simpler way would be to add a UITableViewController
class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell
object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).
As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':
You could also try:
import csv
import pandas as pd
import re
with open (filename, "r") as file:
df = pd.read_csv(file, delimiter = ",")
df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
print(df.columns)
cv::Mat_<T> mat
just use mat(row, col)
Accessing elements of a matrix with specified type cv::Mat_< _Tp > is more comfortable, as you can skip the template specification. This is pointed out in the documentation as well.
code:
cv::Mat1d mat0 = cv::Mat1d::zeros(3, 4);
std::cout << "mat0:\n" << mat0 << std::endl;
std::cout << "element: " << mat0(2, 0) << std::endl;
std::cout << std::endl;
cv::Mat1d mat1 = (cv::Mat1d(3, 4) <<
1, NAN, 10.5, NAN,
NAN, -99, .5, NAN,
-70, NAN, -2, NAN);
std::cout << "mat1:\n" << mat1 << std::endl;
std::cout << "element: " << mat1(0, 2) << std::endl;
std::cout << std::endl;
cv::Mat mat2 = cv::Mat(3, 4, CV_32F, 0.0);
std::cout << "mat2:\n" << mat2 << std::endl;
std::cout << "element: " << mat2.at<float>(2, 0) << std::endl;
std::cout << std::endl;
output:
mat0:
[0, 0, 0, 0;
0, 0, 0, 0;
0, 0, 0, 0]
element: 0
mat1:
[1, nan, 10.5, nan;
nan, -99, 0.5, nan;
-70, nan, -2, nan]
element: 10.5
mat2:
[0, 0, 0, 0;
0, 0, 0, 0;
0, 0, 0, 0]
element: 0
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Use id as primary key with auto increment
$stmt->execute();
$insertid = $conn->lastInsertId();
incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP
if ($insertid)
echo "record inserted successfully";
else
echo "record insertion failed";
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList
)
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";
To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;
.
If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource
implements IBindingList
; one such structure is BindingList<T>
.
Tip: make sure that you are binding the DisplayMember
to a Property on the class and not a public field. If you class uses public string Name { get; set; }
it will work but if it uses public string Name;
it will not be able to access the value and instead will display the object type for each line in the combo box.
An alternative: you can use a "hidden" applet element which implements this exist-check using a privileged action object and override your run method by:
File file = new File(yourPath);
return file.exists();
None of the above solutions worked for me. But
#include <Windows.h>
worked fine.
First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.
To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar()
method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.
If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:
I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
public class TestedClass {
public LoginContext login(String user, String password) {
LoginContext lc = new LoginContext("login", callbackHandler);
lc.doThis();
lc.doThat();
}
}
-- Test Class:
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestedClass.class)
public class TestedClassTest {
@Test
public void testLogin() {
LoginContext lcMock = mock(LoginContext.class);
whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
//comment: this is giving mock object ( lcMock )
TestedClass tc = new TestedClass();
tc.login ("something", "something else"); /// testing this method.
// test the login's logic
}
}
When calling the actual method tc.login ("something", "something else");
from the testLogin() {
- This LoginContext lc is set to null and throwing NPE while calling lc.doThis();
Found this article on net, very relevant to this topic. So posting here.
To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html
So,
df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days
which returns:
A B C
one 2014-01-01 2014-02-28 58
two 2014-02-03 2014-03-01 26
you should look at multimarkdown http://fletcherpenney.net/multimarkdown/
it has support for metadata (headers, keywords, date, author, etc), tables, asciimath, mathml, hell i'm sure you could stick latex math code right in there. it's basically an extension to markdown to add all these other very useful features. It uses XSLT, so you can easily whip up your own LaTeX styles, and have it directly convert. I use it all the time, and I like it a lot.
I wish the markdown would just incorporate multimarkdown. it would be rather nice.
Edit: Multimarkdown will produce html, latex, and a few other formats. html can come with a style sheet of your choice. it will convert into MathML as well, which displays in Firefox and Safari/Chrome, if I remember correctly.
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
You need to do it on the UI thread. Use:
Dispatcher.BeginInvoke(new Action(() => {GetGridData(null, 0)}));
Use the join
method from the Array type.
a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();
The join
method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.
There is also the possibility of using blocks:
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter]
addObserverForName:@"notificationName"
object:nil
queue:mainQueue
usingBlock:^(NSNotification *notification)
{
NSLog(@"Notification received!");
NSDictionary *userInfo = notification.userInfo;
// ...
}];
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
In Chrome, For "Selenium IDE", I was also struggling that it doesn't pause. It will pause, if you give as below:
This will pause for 10 seconds.
You can't set a favicon from CSS - if you want to do this explicitly you have to do it in the markup as you described.
Most browsers will, however, look for a favicon.ico
file on the root of the web site - so if you access http://example.com most browsers will look for http://example.com/favicon.ico automatically.
A one line solution would be:
item['key'] if 'key' in item else None
This is useful when trying to add dictionary values to a new list and want to provide a default:
eg.
row = [item['key'] if 'key' in item else 'default_value']
When creating the array, why not just skip over the 0s and save yourself the time of having to worry about them later? As mentioned above, arrays are not well-suited for deletion.
It is possible to change only arrow's color (not back button title's color) on this way:
[[self.navigationController.navigationBar.subviews lastObject] setTintColor:[UIColor blackColor]];
Navigation bar contains subview of _UINavigationBarBackIndicatorView type (last item in subviews array) which represents arrow.
Result is navigation bar with different colors of back button arrow and back button title
Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.
As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.
For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.
Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html
Check this out. Just use float and get rid of relative.
#icons{float:left;}
Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.
The solution:
h2:after {
content: "\00a0";
}
FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here
From JQuery Documentation
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax()
request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done()
for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail()
method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always()
method replaces the deprecated .complete()
method.
In response to a successful request, the function's arguments are the same as those of .done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail()
: the jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done()
and .fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then()
for implementation details.
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks are removed as of jQuery 3.0. You can usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.
check the @viewchild
in your .ts
@ViewChild('ngOtpInput') ngOtpInput:any;
set the below code in your method were you want the fields to be clear.
yourMethod(){
this.ngOtpInput.setValue(yourValue);
}
If you have upgraded your PHP version, make sure that the old PHP version configuration in your .htaccess has been deleted. For more info, check this https://www.hostgator.com/help/article/php-configuration-plugin
In the documentation it's stated: Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.
When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
internal static string GetEntityFrameworkVersion()
{
var version = "";
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies().Select(x => x.FullName).ToList();
foreach(var asm in assemblies)
{
var fragments = asm.Split(new char[] { ',', '{', '}' }, StringSplitOptions.RemoveEmptyEntries).Select(x=> x.Trim()).ToList();
if(string.Compare(fragments[0], EntityFramework, true)==0)
{
var subfragments = fragments[1].Split(new char[] { '='}, StringSplitOptions.RemoveEmptyEntries);
version =subfragments[1];
break;
}
}
return version;
}
Short trick: after I only REMOVED SPACES from names of the folders, where the .jar file was, double-clicked worked and the file executed.
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
You could do
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text (note the apostrophe as the first character).
The [A1].Value
is VBA shorthand for Range("A1").Value
.
If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")
These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.
Public Function SHA1(ByVal s As String) As String
Dim Enc As Object, Prov As Object
Dim Hash() As Byte, i As Integer
Set Enc = CreateObject("System.Text.UTF8Encoding")
Set Prov = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))
SHA1 = ""
For i = LBound(Hash) To UBound(Hash)
SHA1 = SHA1 & Hex(Hash(i) \ 16) & Hex(Hash(i) Mod 16)
Next
End Function
<Container>
<Menu>
<MenuItem Header="File">
<MenuItem Header="New">
<MenuItem Header="File1"/>
<MenuItem Header="File2"/>
<MenuItem Header="File3"/>
</MenuItem>
<MenuItem Header="Open"/>
<MenuItem Header="Save"/>
</MenuItem>
</Menu>
</Container>
If you don't want to include NaN values, using Counter
is much much faster than pd.Series.mode
or pd.Series.value_counts()[0]
:
def get_most_common(srs):
x = list(srs)
my_counter = Counter(x)
return my_counter.most_common(1)[0][0]
df.groupby(col).agg(get_most_common)
should work. This will fail when you have NaN values, as each NaN will be counted separately.
You can also specify the TNS name in the JDBC URL as below
jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))
This should work in most of the cases.
/^[\d]*[a-z_][a-z\d_]*$/gi
And by most I mean,
abcd True
abcd12 True
ab12cd True
12abcd True
1234 False
^ ... $
- match the pattern starting and ending with[\d]*
- match zero or more digits[a-z_]
- match an alphabet or underscore[a-z\d_]*
- match an alphabet or digit or underscore/gi
- match globally across the string and case-insensitivestd::list<Object> l;
std::list<Object>::iterator ptr;
int i;
for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );
if( ptr == l.end() ) {
// list too short
} else {
// 'ptr' points to N-th element of list
}
There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:
Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15
Consumer applications
- piracy and theft prevention for software or music;
- music, movies, tunes/music, digital photos – players, recorders and organizers
- games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
- LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
- printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
- household utilities and appliances
Business / systems applications: systems operations, integration and control. Some examples
business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery
transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.
industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC
medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality
applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology
Research /scientific /analytical. Some examples:
business process management (BPM) – business process abstraction and modeling
scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)
data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)
Secure intellectual property delivery and installation. Some examples
software download auto-installers and updaters
license key product protection and similar purchase validation
software and hardware design IP protection
computer aided design (CAD) software and other drafting tools
Note: These regulations are also true for testing your app using TestFlight
return dataSource.getParkingLots()
.stream()
.filter(parkingLot -> Objects.equals(parkingLot.getId(), id))
.findFirst()
.orElse(null);
I had to filter out only one object from a list of objects. So i used this, hope it helps.
What I am wondering is if there is any strange way to make this check even faster, maybe exploiting some strange method in Regexp or some weird construct.
Regexp engines vary in how they implement searches, but, in general, anchor your patterns for speed, and avoid greedy matches, especially when searching long strings.
The best thing to do, until you're familiar with how a particular engine works, is to do benchmarks and add/remove anchors, try limiting searches, use wildcards vs. explicit matches, etc.
The Fruity gem is very useful for quickly benchmarking things, because it's smart. Ruby's built-in Benchmark code is also useful, though you can write tests that fool you by not being careful.
I've used both in many answers here on Stack Overflow, so you can search through my answers and will see lots of little tricks and results to give you ideas of how to write faster code.
The biggest thing to remember is, it's bad to prematurely optimize your code before you know where the slowdowns occur.
These are class stereotypes used in analysis.
boundary classes are ones at the boundary of the system - the classes that you or other systems interact with
entity classes classes are your typical business entities like "person" and "bank account"
control classes implement some business logic or other
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';
See this live example of a canvas that is zoomed in by 4x.
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle = '#eff';_x000D_
_x000D_
ctx.fillRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect( 70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
You can use the 'jQuery Passthrough' module of the angular-ui utils. I successfully binded a jQuery touch carousel plugin to some images that I retrieve async from a web service and render them with ng-repeat.
Now in iOS 6 and above, you can use:
[[Picker presentingViewController] dismissViewControllerAnimated:YES completion:nil];
Instead of:
[[Picker parentViewControl] dismissModalViewControllerAnimated:YES];
...And you can use:
[self presentViewController:picker animated:YES completion:nil];
Instead of
[self presentModalViewController:picker animated:YES];
I was hoping to find similar information for Mac OS X as well. Since it wasn't here, I went out and dug it up myself. Here are some of the things I found. If anyone has any other suggestions, I'd love to hear them.
This one is tricky on Mac OS X because it doesn't use a preset swap partition or file like Linux. Here's an entry from Apple's documentation:
Note: Unlike most Unix-based operating systems, Mac OS X does not use a preallocated swap partition for virtual memory. Instead, it uses all of the available space on the machine’s boot partition.
So, if you want to know how much virtual memory is still available, you need to get the size of the root partition. You can do that like this:
struct statfs stats;
if (0 == statfs("/", &stats))
{
myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;
}
Calling systcl with the "vm.swapusage" key provides interesting information about swap usage:
sysctl -n vm.swapusage
vm.swapusage: total = 3072.00M used = 2511.78M free = 560.22M (encrypted)
Not that the total swap usage displayed here can change if more swap is needed as explained in the section above. So the total is actually the current swap total. In C++, this data can be queried this way:
xsw_usage vmusage = {0};
size_t size = sizeof(vmusage);
if( sysctlbyname("vm.swapusage", &vmusage, &size, NULL, 0)!=0 )
{
perror( "unable to get swap usage by calling sysctlbyname(\"vm.swapusage\",...)" );
}
Note that the "xsw_usage", declared in sysctl.h, seems not documented and I suspect there there is a more portable way of accessing these values.
You can get statistics about your current process using the task_info
function. That includes the current resident size of your process and the current virtual size.
#include<mach/mach.h>
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(),
TASK_BASIC_INFO, (task_info_t)&t_info,
&t_info_count))
{
return -1;
}
// resident size is in t_info.resident_size;
// virtual size is in t_info.virtual_size;
The amount of physical RAM available in your system is available using the sysctl
system function like this:
#include <sys/types.h>
#include <sys/sysctl.h>
...
int mib[2];
int64_t physical_memory;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physical_memory, &length, NULL, 0);
You can get general memory statistics from the host_statistics
system function.
#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>
int main(int argc, const char * argv[]) {
vm_size_t page_size;
mach_port_t mach_port;
mach_msg_type_number_t count;
vm_statistics64_data_t vm_stats;
mach_port = mach_host_self();
count = sizeof(vm_stats) / sizeof(natural_t);
if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&
KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,
(host_info64_t)&vm_stats, &count))
{
long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;
long long used_memory = ((int64_t)vm_stats.active_count +
(int64_t)vm_stats.inactive_count +
(int64_t)vm_stats.wire_count) * (int64_t)page_size;
printf("free memory: %lld\nused memory: %lld\n", free_memory, used_memory);
}
return 0;
}
One thing to note here are that there are five types of memory pages in Mac OS X. They are as follows:
It is good to note that just because Mac OS X may show very little actual free memory at times that it may not be a good indication of how much is ready to be used on short notice.
See the "Virtual Memory Currently Used by my Process" above. The same code applies.
You are missing PIL (Python Image Library and Imaging package). To install PIL I used
pip install pillow
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:
$ gunzip Imaging-1.1.6.tar.gz
$ tar xvf Imaging-1.1.6.tar
$ cd Imaging-1.1.6
$ python setup.py install
Or if you have PIP installed in your Mac
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
then you can use:
from PIL import Image
in your python code.
You can use parameters like that
<jsp:include page='about.jsp'>
<jsp:param name="articleId" value=""/>
</jsp:include>
and
in about.jsp you can take the paramter
<%String leftAds = request.getParameter("articleId");%>
My solution without JavaScript/images. Only CSS used. It works in all browsers.
HTML:
<a class="add_to_cart" href="https://www.redracingparts.com" title="Add to Cart!">
buy now<br />free shipping<br />no further costs
</a>
CSS:
.add_to_cart:hover {
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;
}
.add_to_cart {
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:90px;
height:31px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#E70000;
}
There is an example on https://www.redracingparts.com/english/motorbikesmotorcycles/stackoverflow/examples/div/clickable.php
You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.
You can wait for a file to be ready by using this function in a loop.
What you may want to do is first, on your local machine, make a bare clone of the repository
git clone --bare /path/to/repo /path/to/bare/repo.git # don't forget the .git!
Now, archive up the new repo.git directory using tar/gzip or whatever your favorite archiving tool is and then copy the archive to the server.
Unarchive the repo on your server. You'll then need to set up a remote on your local repository:
git remote add repo-name user@host:/path/to/repo.git #this assumes you're using SSH
You will then be able to push to and pull from the remote repo with:
git push repo-name branch-name
git pull repo-name branch-name
The simplest way is to handle the TextChangedEvent and check what's been typed:
string oldText = string.Empty;
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.All(chr => char.IsLetter(chr)))
{
oldText = textBox2.Text;
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.White;
textBox2.ForeColor = System.Drawing.Color.Black;
}
else
{
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.Red;
textBox2.ForeColor = System.Drawing.Color.White;
}
textBox2.SelectionStart = textBox2.Text.Length;
}
This is a regex-free version if you prefer. It will make the text box blink on bad input. Please note that it also seems to support paste operations as well.
You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B
Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);
At View , you can foreach Keys in dataMap and process your action
In contribution to ellabeauty's answer. you can also use this dynamic percentage values
$('.bar').css('width', function(){ return ($(this).attr('data-percentage')+'%')});
And probably add custom easing to your css
.bar {
-webkit-transition: width 2.50s ease !important;
-moz-transition: width 2.50s ease !important;
-o-transition: width 2.50s ease !important;
transition: width 2.50s ease !important;
}
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)
Pay attention to the opposite position of parameters.
Same error when I copied/pasted a class and forgot to rename it in .m file.
This is not my prefered way to do this, cause of massive CPU consumption.
If that is actually your working code, then just keep it like that. Checking a boolean once a second causes NO measurable CPU load. None whatsoever.
The real problem is that the thread that checks the value may not see a change that has happened for an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.
private volatile boolean value;
Note that putting the access in a synchronized
block, such as when using the notification-based solution described in other answers, will have the same effect.
A stringr
pipelined solution:
library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric
os.walk
is your friend in this situation.
Straight from the documentation:
walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
It's simple: when you get something that's not UTF-8, you must encode that into UTF-8.
So, when you're fetching a certain feed that's ISO 8859-1 parse it through utf8_encode
.
However, if you're fetching an UTF-8 feed, you don't need to do anything.
You can get the version of Python by using the following command
python --version
You can even get the version of any package installed in venv using pip freeze
as:
pip freeze | grep "package name"
Or using the Python interpreter as:
In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)
If you're using Rails 3+, remove the gem from the Gemfile and run bundle install
.
If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install
should do the trick.
Unfortunately, assignment to innerHTML
causes the destruction of all child elements, even if you're trying to append. If you want to preserve child nodes (and their event handlers), you'll need to use DOM functions:
function start() {
var myspan = document.getElementById("myspan");
myspan.onclick = function() { alert ("hi"); };
var mydiv = document.getElementById("mydiv");
mydiv.appendChild(document.createTextNode("bar"));
}
Edit: Bob's solution, from the comments. Post your answer, Bob! Get credit for it. :-)
function start() {
var myspan = document.getElementById("myspan");
myspan.onclick = function() { alert ("hi"); };
var mydiv = document.getElementById("mydiv");
var newcontent = document.createElement('div');
newcontent.innerHTML = "bar";
while (newcontent.firstChild) {
mydiv.appendChild(newcontent.firstChild);
}
}
I would recommend EasyInstall, a package management application for Python.
Once you've installed EasyInstall, you should be able to go to a command window and type:
easy_install simplejson
This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts
).
if($('#test2').is(':checked')) {
$(this).append('stuff');
}
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
My windows laptop has both the clients 32 & 64 bit I started facing all of sudden then I reordered the path variable like below
Before:
C:\app\oracle64\product\12.1.0\client_1\bin;
C:\app\oracle32\product\12.1.0\client_1\bin;
After:
C:\app\oracle32\product\12.1.0\client_1\bin;
C:\app\oracle64\product\12.1.0\client_1\bin;
started working... Hope this helps everyone.
This is defined in PEP8 here:
Global Variable Names
(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.
Modules that are designed for use via
from M import *
should use the__all__
mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").
PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
The IFRAME
element may be a security risk if your site is embedded inside an IFRAME
on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe>
or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY
and hope that the browser knows its job.
In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe>
on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY
and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).
That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.
If somebody claims that using an <iframe>
element on your site is dangerous and causes a security risk, he does not understand what <iframe>
element does, or he is speaking about possibility of <iframe>
related vulnerabilities in browsers. Security of <iframe src="...">
tag is equal to <img src="..."
or <a href="...">
as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>
, <img>
or <a>
element, so it's not worth considering for this issue.
However, be warned that content from <iframe>
can initiate top level navigation by default. That is, content within the <iframe>
is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox
attribute without value allow-top-navigation
. For example, <iframe sandbox="allow-forms allow-scripts" ...>
. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.
Note that X-Frame-Options: DENY
also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").
You are allocating your string on the stack, and then returning a pointer to it. When your function returns, any stack allocations become invalid; the pointer now points to a region on the stack that is likely to be overwritten the next time a function is called.
In order to do what you're trying to do, you need to do one of the following:
malloc
or similar, then return that pointer. The caller will then need to call free
when it is done with the memory.If you need the highlighted tint which the OS provides by default when you tap and hold on a custom button for the selected state as well, use this UIButton subclass. Written in Swift 5:
import Foundation
import UIKit
class HighlightOnSelectCustomButton: UIButton {
override var isHighlighted: Bool {
didSet {
if (self.isSelected != isHighlighted) {
self.isHighlighted = self.isSelected
}
}
}
}
You can use this jsFiddle
And HTML:
<div id="previewBox">
<button id="closeButton">Close</button>
<a class="fragment" href="google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
With JS (jquery required):
$(document).ready(function() {
$('#closeButton').on('click', function(e) {
$('#previewBox').remove();
});
});
If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:
git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
--no-merges
omits the merge commits from the listold-tag^
refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).Why aren't you using a Long Press? Or are you using that already for something else? The advantages of a Long Press over a Double Touch:
Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);
You can retrieve it in another activity. Two ways:
int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
The second way is:
Intent i = getIntent();
String name = i.getStringExtra("name");
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
Why not simply set it up as a Scheduled Task that is scheduled to run at start up?
I like using StringBuilder
with Aggregate()
. The "trick" is that Append()
returns the StringBuilder
instance itself:
var sb = arr.Aggregate( new StringBuilder(), ( s, i ) => s.Append( i ) );
var result = sb.ToString();
because my array was like below: and I used .push function to create it dynamically
my_array = ["234", "23423"];
The only way I converted my array into json is
json = Object.assign({}, my_array);
The best way to solve this problem would be by starting with customizing Bootstrap using their customization tools.
http://getbootstrap.com/customize/
Go down to @headings-color and change it from "inherit" to something that you would like your headers to be across the site (if you like the default just change it to #333).
Note that this will keep all your headings the same color, as you requested.
Now in order to accomplish what you want that after you make this change you can now overwrite them specifically in your own CSS to apply your own color to them. The "inherit" keyword I always have found to be a pain in frameworks.
You might find the Semantic Versioning Specification useful.
If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.
ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
I'm freshly new with Pandas but I wanted to achieve the same thing, automatically avoiding column names with _x or _y and removing duplicate data. I finally did it by using this answer and this one from Stackoverflow
sales.csv
city;state;units Mendocino;CA;1 Denver;CO;4 Austin;TX;2
revenue.csv
branch_id;city;revenue;state_id 10;Austin;100;TX 20;Austin;83;TX 30;Austin;4;TX 47;Austin;200;TX 20;Denver;83;CO 30;Springfield;4;I
merge.py import pandas
def drop_y(df):
# list comprehension of the cols that end with '_y'
to_drop = [x for x in df if x.endswith('_y')]
df.drop(to_drop, axis=1, inplace=True)
sales = pandas.read_csv('data/sales.csv', delimiter=';')
revenue = pandas.read_csv('data/revenue.csv', delimiter=';')
result = pandas.merge(sales, revenue, how='inner', left_on=['state'], right_on=['state_id'], suffixes=('', '_y'))
drop_y(result)
result.to_csv('results/output.csv', index=True, index_label='id', sep=';')
When executing the merge command I replace the _x
suffix with an empty string and them I can remove columns ending with _y
output.csv
id;city;state;units;branch_id;revenue;state_id 0;Denver;CO;4;20;83;CO 1;Austin;TX;2;10;100;TX 2;Austin;TX;2;20;83;TX 3;Austin;TX;2;30;4;TX 4;Austin;TX;2;47;200;TX
You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.
The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.
I use system properties in log4j.xml:
...
<param name="File" value="${catalina.home}/logs/root.log"/>
...
and start tests with:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<systemProperties>
<property>
<name>catalina.home</name>
<value>${project.build.directory}</value>
</property>
</systemProperties>
</configuration>
</plugin>
Wrote this because I had requirements for up to a specific length (9). Pads the left with the @pattern ONLY when the input needs padding. Should always return length defined in @pattern.
declare @charInput as char(50) = 'input'
--always handle NULL :)
set @charInput = isnull(@charInput,'')
declare @actualLength as int = len(@charInput)
declare @pattern as char(50) = '123456789'
declare @prefLength as int = len(@pattern)
if @prefLength > @actualLength
select Left(Left(@pattern, @prefLength-@actualLength) + @charInput, @prefLength)
else
select @charInput
Returns 1234input
You can also use PostCSS and the custom selectors plugin
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
article :--headings {
margin-top: 0;
}
Output:
article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
margin-top: 0;
}
HTML
<Select id="SDistrict" class="form-control">
<option value="1" data-color="yellow" > Mango </option>
</select>
JS when initialized
$('#SDistrict').selectize({
create: false,
sortField: 'text',
onInitialize: function() {
var s = this;
this.revertSettings.$children.each(function() {
$.extend(s.options[this.value], $(this).data());
});
},
onChange: function(value) {
var option = this.options[value];
alert(option.text + ' color is ' + option.color);
}
});
You can access data attribute of option tag with option.[data-attribute]
JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/
class LL(object):
def __init__(self,val):
self.val = val
self.next = None
def pushNodeEnd(self,top,val):
if top is None:
top.val=val
top.next=None
else:
tmp=top
while (tmp.next != None):
tmp=tmp.next
newNode=LL(val)
newNode.next=None
tmp.next=newNode
def pushNodeFront(self,top,val):
if top is None:
top.val=val
top.next=None
else:
newNode=LL(val)
newNode.next=top
top=newNode
def popNodeFront(self,top):
if top is None:
return
else:
sav=top
top=top.next
return sav
def popNodeEnd(self,top):
if top is None:
return
else:
tmp=top
while (tmp.next != None):
prev=tmp
tmp=tmp.next
prev.next=None
return tmp
top=LL(10)
top.pushNodeEnd(top, 20)
top.pushNodeEnd(top, 30)
pop=top.popNodeEnd(top)
print (pop.val)
They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.
For those who want to know the reason, but don't want to read the article referenced in is vs typeof.
THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS
Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideID
For Each curShape In curSlide.Shapes
If curShape.TextFrame.HasText Then
Debug.Print curShape.Id
End If
Next curShape
Next curSlide
End Sub
For Intellij IDEA (and Android Studio) each library is a Module. Think of a Module in Android Studio as an equivalent to project in Eclipse. Project in Android Studio is a collection of modules. Modules can be runnable applications or library modules.
So, in order to add a new android library project to you need to create a module of type "Android library". Then add this library module to the dependency list of your main module (Application module).
Another one with a different concept: http://www.klausbasan.de/misc/telnet/index.html
Here is a quick and simple solution using PowerShell:
powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"
This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16
to CopyHere
answers all questions with yes.
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
The HashMap has forEach
as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:
map.forEach((k,v)-> System.out.println(k+", "+v));
or
map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));
In fact you can use \input{filename}
and \include{filename}
which are latex commands,
directly in Pandoc
, because it supports nearly all html
and latex
syntax.
But beware, the included file will be treated as latex
file. But you can compile your markdown
to latex
with Pandox
easily.
I had same issue after I updated my Android phone to 6.0 (API level 23). The following solution works on me. Hopefully it helps you as well.
Please check your android version. If it is >= 6.0 (API level 23), you need to not only include
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in your AndroidManifest.xml, but also request permission before calling mkdir(). Code snopshot.
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)){
Log.d("myAppName", "Error: external storage is unavailable");
return 0;
}
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Log.d("myAppName", "Error: external storage is read only.");
return 0;
}
Log.d("myAppName", "External storage is not read only or unavailable");
if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted.
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
int result = 0;
if (folder.exists()) {
Log.d("myAppName","folder exist:"+folder.toString());
result = 2; // folder exist
}else{
try {
if (folder.mkdir()) {
Log.d("myAppName", "folder created:" + folder.toString());
result = 1; // folder created
} else {
Log.d("myAppName", "creat folder fails:" + folder.toString());
result = 0; // creat folder fails
}
}catch (Exception ecp){
ecp.printStackTrace();
}
}
return result;
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
More information please read "Requesting Permissions at Run Time"
You may use as following to get Height and Weight of an Numpy array:
int height = arr.shape[0]
int weight = arr.shape[1]
If your array has multiple dimensions, you can increase the index to access them.
Quote from the Python 3 Reference:
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
As said in the reference, in case of several nested functions only variable in the nearest enclosing function is modified:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
x = 2
innermost()
if x == 3: print('Inner x has been modified')
x = 1
inner()
if x == 3: print('Outer x has been modified')
x = 0
outer()
if x == 3: print('Global x has been modified')
# Inner x has been modified
The "nearest" variable can be several levels away:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
innermost()
x = 1
inner()
if x == 3: print('Outer x has been modified')
x = 0
outer()
if x == 3: print('Global x has been modified')
# Outer x has been modified
But it cannot be a global variable:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
innermost()
inner()
x = 0
outer()
if x == 3: print('Global x has been modified')
# SyntaxError: no binding for nonlocal 'x' found
One line solution
new Date(new Date(1422524805305).getTime() - 330*60*1000)
Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)
Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".
def a(): code a
def b(): code b
def c(): code c
def d(): code d
for func in [a, b, c, d]: # change list order to change execution order.
try:
func()
break
except Exception as err:
print (err)
continue
I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).
The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.
In my case I was stupid enough to create the patch file incorrectly in the first place, actually diff-ing the wrong way. I ended up with the exact same error messages.
If you're on master and do git diff branch-name > branch-name.patch
, this tries to remove all additions you want to happen and vice versa (which was impossible for git to accomplish since, obviously, never done additions cannot be removed).
So make sure you checkout to your branch and execute git diff master > branch-name.patch
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
Is there a good reason not to use a hash? Lookups are O(1)
vs. O(n)
for the array.
I also had a problem with the chain and managed to solve using this guide https://gist.github.com/bradmontgomery/6487319
There is a section in the MySQL manual on how to reset the root password which will solve your problem.
Try this...
if(string1.toLowerCase() == string2.toLowerCase()){
return true;
}
Also, it's not a loop, it's a block of code. Loops are generally repeated (although they can possibly execute only once), whereas a block of code never repeats.
I read your note about not using toLowerCase, but can't see why it would be a problem.
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
// data is separated from the query
Best practice is to stick with prepared statements and execute
for increased security.
See also: Are PDO prepared statements sufficient to prevent SQL injection?
Had the same error but with a different scenario. I had my state as
this.state = {
date: new Date()
}
so when I was asking it in my Class Component I had
p>Date = {this.state.date}</p>
Instead of
p>Date = {this.state.date.toLocaleDateString()}</p>
Override the Bootstrap ‘hide’ event of Dialog and stop its default behavior (to dispose the dialog).
Please see the below code snippet:
$('#yourDialogID').on('hide.bs.modal', function(e) {
e.preventDefault();
});
It works fine in our case.
The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:
HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))
Format..., select formatting, OK, OK.
where I have filled yellow the cells that are triggering the red fill result.
If you are able to send the payload in JSON, this is a most convenient way to read the playload:
Example data class:
public class Person {
String firstName;
String lastName;
// Getters and setters ...
}
Example payload (request body):
{ "firstName" : "John", "lastName" : "Doe" }
Code to read payload in servlet (requires com.google.gson.*):
Person person = new Gson().fromJson(request.getReader(), Person.class);
That's all. Nice, easy and clean. Don't forget to set the content-type header to application/json.
Split Method
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:
Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)
with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.
You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.
[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment
#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")
produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token
]
However, for general token pasting, try this:
/*
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define PPCAT_NX(A, B) A ## B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
*/
#define PPCAT(A, B) PPCAT_NX(A, B)
Then, e.g., both PPCAT_NX(s, 1)
and PPCAT(s, 1)
produce the identifier s1
, unless s
is defined as a macro, in which case PPCAT(s, 1)
produces <macro value of s>1
.
Continuing on the theme are these macros:
/*
* Turn A into a string literal without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define STRINGIZE_NX(A) #A
/*
* Turn A into a string literal after macro-expanding it.
*/
#define STRINGIZE(A) STRINGIZE_NX(A)
Then,
#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"
By contrast,
STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"
#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"
I think you are not asking the right question--
A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.
Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:
try:
mystring.decode('ascii')
except UnicodeDecodeError:
print "it was not a ascii-encoded unicode string"
else:
print "It may have been an ascii-encoded unicode string"
This is a verbatim string, and changes the escaping rules - the only character that is now escaped is ", escaped to "". This is especially useful for file paths and regex:
var path = @"c:\some\location";
var tsql = @"SELECT *
FROM FOO
WHERE Bar = 1";
var escaped = @"a "" b";
etc
I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with
$my_url = urlencode("my url");
and then calling
file_get_contents($my_url);
and see if you have better luck.
.center {
display: table;
margin: auto;
}
Instead of naming my invoking class, I started using the following:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.
Go to
Tools > Android > Android Device Monitor
in v0.8.6. That will pull up the DDMS eclipse perspective.
There are many places where someone might want to deploy this kind of scenario, but due to the way integrated authentication works, it is not possible.
As gbn mentioned, integrated authentication uses a special token that corresponds to your Windows identity. There are coding practices called "impersonation" (probably used by the Run As... command) that allow you to effectively perform an activity as another Windows user, but there is not really a way to arbitrarily act as a different user (à la Linux) in Windows applications aside from that.
If you really need to administer multiple servers across several domains, you might consider one of the following:
Hopefully this helps!
In order to see the changes that have been staged already, you can pass the -–staged
option to git diff
(in pre-1.6 versions of Git, use –-cached
).
git diff --staged
git diff --cached
answer = True
myvar = "the answer is " + str(answer)
or
myvar = "the answer is %s" % answer
Adding one more approach :
value = $(this).val().toLowerCase();
$("#product-search-result tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
Use LINQ Aggregate
method to convert array of integers to a comma separated string
var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);
output will be
1,2,3,4
This is one of the solution you can use if you have not .net 4 installed.
You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.
i was looking for changing second row html and you can do cascading selector
$('#tbox1 tr:nth-child(2) td').html(11111)
After having tried everything here I had to simply upgrade Apache to a newer version in order to make curl
extension work.
I was upgrading PHP from 7.0.2 to 7.1.15 after which curl
did not work. Only way to fix it was upgrade Apache (which was version 2.4.18) to the latest 2.4.29.
Didn't have to copy any of the lib/ssleay dll files to either Apache or Windows - possibly because I already have the PHP folder in my system path.
Running Windows 10, 64-bit, thread-safe versions, VC14.
Download this file :- (https://pypi.python.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz#md5=7142a421c8b35d2dac6c47c254db023d):
cd /opt
sudo tar -xvf ~/Downloads/pyserial-3.2.1.tar.gz -C .
cd /opt/pyserial-3.2.1
sudo python setup.py install
This is a good example where you want to get count of Pincode which stored in the last of address field
SELECT DISTINCT
RIGHT (address, 6),
count(*) AS count
FROM
datafile
WHERE
address IS NOT NULL
GROUP BY
RIGHT (address, 6)
The accepted answer is a bad idea in general because the manually created make.exe
will stick around and can potentially cause unexpected problems. It actually breaks RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105
An alternative is installing make via Chocolatey (as pointed out by @Vasantha Ganesh K)
Another alternative is installing MSYS2 from Chocolatey and using make
from C:\tools\msys64\usr\bin
. If make
isn't installed automatically with MSYS2 you need to install it manually via pacman -S make
(as pointed out by @Thad Guidry and @Luke).
The title
attribute works on most HTML tags and is widely supported by modern browsers.
As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run
Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.
Then you can create an ssh batch script such as
ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.
SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF
REM ------------------------------
REM SSH Server details
REM ------------------------------
:WEB1
CLS
call ssh [email protected]
cmd /k
:WEB2
CLS
call ssh [email protected]
cmd /k