On 32-bit machines:
cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
or on 64 bit machines:
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
These need to be run as administrator.
PCDATA
is text that will be parsed by a parser. Tags inside the text
will be treated as markup and entities will be expanded. CDATA
is text that will not be parsed by a parser. Tags inside the text will
not be treated as markup and entities will not be expanded.By default, everything is PCDATA
. In the following example, ignoring the root, <bar>
will be parsed, and it'll have no content, but one child.
<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>
When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA
, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<
) , greater-than (>
) , ampersand (&
), quote('
) and double quote ("
).
In the next example, <bar>
contains CDATA
. Its content will not be parsed and is thus <test>content!</test>
.
<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>
There are several content models in SGML. The #PCDATA
content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.
Another type of content model allowing plain text contents is CDATA
. In XML, the element content model may not implicitly be set to CDATA
, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA
type however, entity references are replaced.
In XML, #PCDATA
is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA
content model may be used explicitly through the CDATA
block markup in #PCDATA
, but element contents may not be defined as CDATA
per default.
In a DTD, the type of an attribute that contains text must be CDATA
. The CDATA
keyword in an attribute declaration has a different meaning than the CDATA
section in an XML document. In a CDATA
section all characters are legal (including <
,>
,&
,'
and "
characters), except the ]]>
end tag.
#PCDATA
is not appropriate for the type of an attribute. It is used for the type of "leaf" text.
#PCDATA
is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA
(which would be perfectly legal).
I will second madExcept and similar tools, like Eurekalog, but I think you can come a good way with FastMM also. With full debugmode enabled, it should give you some clues of whats wrong.
Anyway, even though Delphi uses FastMM as default, it's worth getting the full FastMM for it's additional control over logging.
Does an implicit conversion occur between Task<> and int?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of type T
in an async manner)The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDoubleAsync()
{
var task = AccessTheWebAsync();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWebAsync() * 2;
of course.)
If you prefer a solution that does not require the initialization of the counter outside the loop, I propose comparing the current iteration key against the function that tells you the last / first key of the array.
This becomes somewhat more efficient (and more readable) with the upcoming PHP 7.3.
foreach($array as $key => $element) {
if ($key === array_key_first($array))
echo 'FIRST ELEMENT!';
if ($key === array_key_last($array))
echo 'LAST ELEMENT!';
}
foreach($array as $key => $element) {
reset($array);
if ($key === key($array))
echo 'FIRST ELEMENT!';
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization
#include <MyClass>
extern template class CMyClass<int>;
The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)
template class CMyClass<int>;
template class CMyClass<float>;
This should be faster:
DELETE * FROM table_name;
because RDBMS don't have to look where
is what.
You should be fine with truncate
though:
truncate table table_name
You can redirect stdout to /dev/null.
yum install nano > /dev/null
Or you can redirect both stdout and stderr,
yum install nano &> /dev/null
.
But if the program has a quiet option, that's even better.
The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:
SELECT Name,
SUM(Value) AS "SUM(VALUE)",
SUM(Value) / totals.total AS "% of Total"
FROM table1,
(
SELECT Name,
SUM(Value) AS total
FROM table1
GROUP BY Name
) AS totals
WHERE table1.Name = totals.Name
AND Year BETWEEN 2000 AND 2001
GROUP BY Name;
Note that the subquery does not have the WHERE clause filtering the years.
For those like me just looking for a simple solution, this does almost exactly what you expect from using normal $watch in controllers. The only difference is, that it evaluates the string in it's javascript context and not on a specific scope. You'll have to inject $rootScope into your service, although it is only used to hook into the digest cycles properly.
function watch(target, callback, deep) {
$rootScope.$watch(function () {return eval(target);}, callback, deep);
};
scanf()
and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
Here's the documentation:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
A basic connection string looks like:
jdbc:mysql://localhost:3306/dbname
The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).
Add list-style-position: inside
to the ul
element. (example)
The default value for the list-style-position
property is outside
.
ul {_x000D_
text-align: center;_x000D_
list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>
_x000D_
Another option (which yields slightly different results) would be to center the entire ul
element:
.parent {_x000D_
text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Here is other example:
import numpy as np
import pandas as pd
""" This just creates a list of touples, and each element of the touple is an array"""
a = [ (np.random.randint(1,10,10), np.array([0,1,2,3,4,5,6,7,8,9])) for i in
range(0,10) ]
""" Panda DataFrame will allocate each of the arrays , contained as a touple
element , as column"""
df = pd.DataFrame(data =a,columns=['random_num','sequential_num'])
The secret in general is to allocate the data in the form a = [ (array_11, array_12,...,array_1n),...,(array_m1,array_m2,...,array_mn) ] and panda DataFrame will order the data in n columns of arrays. Of course , arrays of arrays could be used instead of touples, in that case the form would be : a = [ [array_11, array_12,...,array_1n],...,[array_m1,array_m2,...,array_mn] ]
This is the output if you print(df) from the code above:
random_num sequential_num
0 [7, 9, 2, 2, 5, 3, 5, 3, 1, 4] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 [8, 7, 9, 8, 1, 2, 2, 6, 6, 3] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2 [3, 4, 1, 2, 2, 1, 4, 2, 6, 1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 [3, 1, 1, 1, 6, 2, 8, 6, 7, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4 [4, 2, 8, 5, 4, 1, 2, 2, 3, 3] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5 [3, 2, 7, 4, 1, 5, 1, 4, 6, 3] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6 [5, 7, 3, 9, 7, 8, 4, 1, 3, 1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7 [7, 4, 7, 6, 2, 6, 3, 2, 5, 6] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8 [3, 1, 6, 3, 2, 1, 5, 2, 2, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9 [7, 2, 3, 9, 5, 5, 8, 6, 9, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Other variation of the example above:
b = [ (i,"text",[14, 5,], np.array([0,1,2,3,4,5,6,7,8,9])) for i in
range(0,10) ]
df = pd.DataFrame(data=b,columns=['Number','Text','2Elemnt_array','10Element_array'])
Output of df:
Number Text 2Elemnt_array 10Element_array
0 0 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 1 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2 2 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 3 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4 4 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5 5 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6 6 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7 7 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8 8 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9 9 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you want to add other columns of arrays, then:
df['3Element_array']=[([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3])]
The final output of df will be:
Number Text 2Elemnt_array 10Element_array 3Element_array
0 0 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
1 1 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
2 2 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
3 3 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
4 4 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
5 5 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
6 6 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
7 7 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
8 8 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
9 9 text [14, 5] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
As we read in the previous comments this error is occurring because the current SDK version is incompatible with the newest Java versions: 9 and 10.
So, to solve it, you can downgrade your java version to Java 8, or as a workaround, you can export the following option on your terminal:
Linux:
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
Windows:
set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
If this does not work try to exports the java.xml.bind
instead.
Linux:
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'
Windows:
set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'
This will solve this error for the sdkmanager
And to make it saved permanently you can export the JAVA_OPTS in your profile file on Linux (.zshrc
, .bashrc
and etc.) or add it as an environment variable permanently on Windows.
ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.
Check your real my.ini
file location and set --defaults-file="location"
with this command
mysql --defaults-file="C:\MYSQL\my.ini" -u root -p
This solution is permanently for your cmd Screen.
mod_php is a PHP interpreter.
From docs, one important catch of mod_php is,
"mod_php is not thread safe and forces you to stick with the prefork mpm (multi process, no threads), which is the slowest possible configuration"
declare @hours int = 5;
select dateadd(hour,@hours,getdate())
I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.
Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.
Declare @MainTable table(id int identity(1,1),TextField varchar(100))
INSERT INTO @MainTable (TextField)
VALUES
('6B32E')
declare @i int=1
Declare @originalWord varchar(100)=''
WHile @i<=(Select count(*) from @MainTable)
BEGIN
Select @originalWord=TextField from @MainTable where id=@i
Declare @r varchar(max) ='', @len int ,@c char(1), @x int = 0
Select @len = len(@originalWord)
declare @pn varchar(100)=@originalWord
while @x <= @len
begin
Select @c = SUBSTRING(@pn,@x,1)
if(@c!='')
BEGIN
if ISNUMERIC(@c) = 0 and @c <> '-'
BEGIN
Select @r = cast(@r as varchar) + cast(replace((SELECT ASCII(@c)-64),'-','') as varchar)
end
ELSE
BEGIN
Select @r = @r + @c
END
END
Select @x = @x +1
END
Select @r
Set @i=@i+1
END
I altered the jQuery plugin posted above so it would work on live elements.
(function ($) {
$.fn.disableSelection = function () {
return this.each(function () {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
};
})(jQuery);
Then you could so something like:
$(document).ready(function() {
$('label').disableSelection();
// Or to make everything unselectable
$('*').disableSelection();
});
You should use whatever is cheapest and best known for your platform and call it a day. Obfuscation of high-level languages is a hard problem, because VM opcode streams don't suffer from the two biggest problems native opcode streams do: function/method identification and register aliasing.
What you should know about bytecode reversing is that it is already standard practice for security testers to review straight X86 code and find vulnerabilities in it. In raw X86, you cannot necessarily even find valid functions, let alone track a local variable throughout a function call. In almost no circumstances do native code reversers have access to function and variable names --- unless they're reviewing Microsoft code, for which MSFT helpfully provides that information to the public.
"Dotfuscation" works principally by scrambling function and variable names. It's probably better to do this than publish code with debug-level information, where the Reflector is literally giving up your source code. But anything you do beyond this is likely to get into diminishing returns.
I know it is usually considered only for testing but you could use the Hamcrest JSON comparitorSameJSONAs in Hamcrest JSON.
Here is an example using jQuery...
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
var frm = $(document.myform);
var dat = JSON.stringify(frm.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.
In Laravel 3, call path('storage')
.
In Laravel 4, use the storage_path()
helper function.
You're currently writing the binary data in the string
-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream
, an "out-file-stream". It behaves exactly like std::cout
, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close()
isn't strictly neccessary here: the deconstructor of ofstream
can handle this for us as soon as out
goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str()
. So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
All necessary git bash commands to push and pull into Github:
git status
git pull
git add filefullpath
git commit -m "comments for checkin file"
git push origin branch/master
git remote -v
git log -2
If you want to edit a file then:
edit filename.*
To see all branches and their commits:
git show-branch
Here is a simple example.
this method will return a 2 dimensional tType
array
public tType[][] allocate(Class<tType> c,int row,int column){
tType [][] matrix = (tType[][]) Array.newInstance(c,row);
for (int i = 0; i < column; i++) {
matrix[i] = (tType[]) Array.newInstance(c,column);
}
return matrix;
}
say you want a 2 dimensional String array, then call this function as
String [][] stringArray = allocate(String.class,3,3);
This will give you a two dimensional String array with 3 rows and 3 columns;
Note that in Class<tType> c
-> c
cannot be primitive type like say, int
or char
or double
. It must be non-primitive like, String
or Double
or Integer
and so on.
A simple for loop which tests the checked
property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked
further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");
You can use with_together for this purpose:
- name: Copy multiple files to multiple directories
copy: src={{ item.0 }} dest={{ item.1 }}
with_together:
- [ 'file1', 'file2', 'file3' ]
- [ '/dir1/', '/dir2/', '/dir3/' ]
$('#my_select option:selected').attr('id');
I came here having a great belief that I know beautiful solution for this problem. Code in C:
short numberOfOnes(unsigned int d) {
short count = 0;
for (; (d != 0); d &= (d - 1))
++count;
return count;
}
But after I've taken a little research on this topic (read other answers:)) I found 5 more efficient algorithms. Love SO!
There is even a CPU instruction designed specifically for this task: popcnt
.
(mentioned in this answer)
Description and benchmarking of many algorithms you can find here.
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
Use this manual http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/ This guide really helped me. It is important to observe a sequence of certificates in the store. For example: import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.
use this method:-
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
stackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
Caller of method example Code is here:-
public class TestString {
public static void main(String[] args) {
TestString testString = new TestString();
testString.doit1();
testString.doit2();
testString.doit3();
testString.doit4();
}
public void doit() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
}
public void doit1() {
doit();
}
public void doit2() {
doit();
}
public void doit3() {
doit();
}
public void doit4() {
doit();
}
}
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
From the official Node.js documentation:
A Node.js package is also available in the official repo for Debian Sid (unstable), Jessie (testing) and Wheezy (wheezy-backports) as "nodejs". It only installs a nodejs binary.
So, if you only type sudo apt-get install nodejs
, it does not install other goodies such as npm.
You need to type:
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs
Optional: install build tools
To compile and install native add-ons from npm you may also need to install build tools:
sudo apt-get install -y build-essential
More info: Docs
You can use
document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)
or
document.getElementById("parentID").innerHTML+= "new content"
This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.
The modal dialog can be positioned on top by overriding its z-index property:
.modal.fade {
z-index: 10000000 !important;
}
The correct result for me with SQL Server 2017:
USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO
RECONFIGURE
GO
EXEC sp_configure 'clr enabled' -- make sure it took
GO
USE <DATABASE>
GO
EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO
ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;
From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675
If you have the possibility to edit the PHP script, you can artificially populate $_GET array using the following code at the beginning of the script and then call the script with the syntax: php -f script.php name1=value1 name2=value2
// When invoking the script via CLI like "php -f script.php name1=value1 name2=value2", this code will populate $_GET variables called "name1" and "name2", so a script designed to be called by a web server will work even when called by CLI
if (php_sapi_name() == "cli") {
for ($c = 1; $c < $argc; $c++) {
$param = explode("=", $argv[$c], 2);
$_GET[$param[0]] = $param[1]; // $_GET['name1'] = 'value1'
}
}
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.
Here is my solution, based on previous answers by Paul Grimshaw and Anthony VO. I've submitted the code in a C# project on Github.
My main contribution is to eliminate explicitly creating and manipulating a StringBuilder
and instead working only with IEnumerable
. This avoids the allocation of a big buffer in memory.
public static class Util
{
public static string EscapeQuotes(this string self) {
return self?.Replace("\"", "\"\"") ?? "";
}
public static string Surround(this string self, string before, string after) {
return $"{before}{self}{after}";
}
public static string Quoted(this string self, string quotes = "\"") {
return self.Surround(quotes, quotes);
}
public static string QuotedCSVFieldIfNecessary(this string self) {
return (self == null) ? "" : self.Contains('"') ? self.Quoted() : self;
}
public static string ToCsvField(this string self) {
return self.EscapeQuotes().QuotedCSVFieldIfNecessary();
}
public static string ToCsvRow(this IEnumerable<string> self){
return string.Join(",", self.Select(ToCsvField));
}
public static IEnumerable<string> ToCsvRows(this DataTable self) {
yield return self.Columns.OfType<object>().Select(c => c.ToString()).ToCsvRow();
foreach (var dr in self.Rows.OfType<DataRow>())
yield return dr.ItemArray.Select(item => item.ToString()).ToCsvRow();
}
public static void ToCsvFile(this DataTable self, string path) {
File.WriteAllLines(path, self.ToCsvRows());
}
}
This approach combines nicely with converting IEnumerable
to DataTable as asked here.
getElementsByName()
method accesses all elements with the
specified name.
this method returns collection of elements that is an array.getElementsByTagName()
method accesses all elements with the
specified tagname.
this method returns collection of elements that is an array.eg:
<script type="text/javascript">
function getElements() {
var x=document.getElementById("y");
alert(x.value);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
This will return a single HTML element and display the value attribute of it.
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("x");
alert(x.length);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
<input name="x" id="y" type="text" size="20" /><br />
this will return an array of HTML elements and number of elements that match the name attribute.
Extracted from w3schools.
use with responsive website (view in mobile or ipad)
jQuery(window).height(); // return height of browser viewport
jQuery(window).width(); // return width of browser viewport
rarely use
jQuery(document).height(); // return height of HTML document
jQuery(document).width(); // return width of HTML document
I took jbarlow idea, but I added an if in the onblur function so the fields only change its type if the value is empty
<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.value == '' ? this.type='text' : this.type='date')" id="date">
Check whether your template in theme
folder contains search.php
and searchform.php
or not.
If you are using babel, you should check out babel-plugin-lodash, it will cherry-pick the parts of lodash you are using for you, less hassle and a smaller bundle.
It has a few limitations:
The way to get the results of your formula would be to start in a new sheet.
In cell A1 put the formula
=IF('testsheet'!C1 <= 99,'testsheet'!A1,"")
Copy that cell down to row 40 In cell B1 put the formula
=A1
In cell B2 put the formula
=B1 & A2
Copy that cell down to row 40.
The value you want is now in that column in row 40.
Not really the answer you want, but that is the fastest way to get things done excel wise without creating a custom formula that takes in a range and makes the calculation (which would be more fun to do).
One way to solve this problem is by turning the warnings off.
SET ANSI_WARNINGS OFF;
GO
You can also use matches with regular expression like this:
boolean bool = List.matches("(?i).*SOME STRING HERE.*")
A little extension to the above answers. The trailing >
directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >>
that appends, adding your new content to the end of the file, as in:
cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert /var/sharedFolder/sometin/vsdc/cert nfs
EOF
This extends your fstab
without you having to worry about accidentally modifying any of its contents.
Thanks for above answer , here is my jQuery code that is working now:
$(".header-login-li").click(function(){
activaTab('pane_login');
});
$(".header-register-li").click(function(){
activaTab('pane_reg');
$("#reg_log_modal_header_text").css()
});
function activaTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
this just happened to me. Rebuilding or restarting Eclipse didn't help.
I solved it by renaming one of the test methods to start with "test..." (JUnit3 style) and then all tests are found. I renamed it back to what it was previously, and it still works.
The Instagram API requires user authentication through OAuth to access the recent media endpoint for a user. There doesn't appear to be any other way right now to get all media for a user.
Are you interested in counting the executable lines rather than the total file line count? If so you could try a code coverage tool such as EclEmma. As a side effect of the code coverage stats you get stats on the number of executable lines and blocks (and methods and classes). These are rolled up from the method level upwards, so you can see line counts for the packages, source roots and projects as well.
That's the error you get when a function makes too many recursive calls to itself. It might be doing this because the base case is never met (and therefore it gets stuck in an infinite loop) or just by making an large number of calls to itself. You could replace the recursive calls with while loops.
To run your app on a real device, you need to have an Apple ID, and have registered your device with that ID. That is why you are getting this error.
Here's how you do it.
Go to the project Navigator. Cmd-1 if you can't find it.
Sign in with your Apple ID that is linked to your developer account, or just your Apple if you don't have a dev account.
If you haven't registered your device with that account yet, a button will appear, something like 'Register device'. Click that and Apple will register the device and do the certificates and code signing. (Oh my unicorns certificates and signing is so much easier than it used to be)
Pick your physical device and hit run and it should load onto your device without error.
You can use Janel. This last works as an application launcher or service launcher (available from 4.x).
If you also have SDKMAN...
Somehow SDKMAN was conflicting with my NVM. If you're at your wits end with this and still can't figure it out, I just fixed it by ignoring the "THIS MUST BE AT THE END OF THE FILE..." from SDKMAN and putting the NVM lines after it.
#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="/Users/myname/.sdkman"
[[ -s "/Users/myname/.sdkman/bin/sdkman-init.sh" ]] && source "/Users/myname/.sdkman/bin/sdkman-init.sh"
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
I am using python 3.6.8, on ubunu 18.04, for me the solution was to just upgrade pip
pip install --upgrade pip
pip install tensorflow==2.1.0
The right way is to fix the overflow, but....
You can give yourself a bigger stack:-
using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();
You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.
Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-
class Program
{
static int n;
static int topOfStack;
const int stackSize = 1000000; // Default?
// The func is 76 bytes, but we need space to unwind the exception.
const int spaceRequired = 18*1024;
unsafe static void Main(string[] args)
{
int var;
topOfStack = (int)&var;
n=0;
recurse();
}
unsafe static void recurse()
{
int remaining;
remaining = stackSize - (topOfStack - (int)&remaining);
if (remaining < spaceRequired)
throw new Exception("Cheese");
n++;
recurse();
}
}
Just catch the Cheese. ;)
To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.
Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.
EDIT:
Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.
Why don't you use $BUILD_URL
then? Isn't it available in the extended email plugin?
Yes you can use ALTER TABLE
as follows:
ALTER TABLE [table name] ALTER COLUMN [column name] [data type] NULL
Quoting from the ALTER TABLE
documentation:
NULL
can be specified inALTER COLUMN
to force aNOT NULL
column to allow null values, except for columns in PRIMARY KEY constraints.
If you're using this for currency, and also want the value to be seperated by ,
's you can use
$ {:,.f2}.format(currency_value)
.
e.g.:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
$ 1,234.50
Here is a bit of code I wrote some time ago:
print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
See Samples Environment for Microsoft Chart Controls:
The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.
Seems to be more business oriented, but may be of some value to science students and scientists.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
It is because the Creation was delayed. If you want the picture to be loaded immediately, you can simply add this code into the init phase.
src.CacheOption = BitmapCacheOption.OnLoad;
like this:
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
You can use a constant (i.e. a static, final variable) as the parameter for an annotation. As a quick example, I use something like this fairly often:
import org.junit.Test;
import static org.junit.Assert.*;
public class MyTestClass
{
private static final int TEST_TIMEOUT = 60000; // one minute per test
@Test(timeout=TEST_TIMEOUT)
public void testJDK()
{
assertTrue("Something is very wrong", Boolean.TRUE);
}
}
Note that it's possible to pass the TEST_TIMEOUT
constant straight into the annotation.
Offhand, I don't recall ever having tried this with an array, so you may be running into some issues with slight differences in how arrays are represented as annotation parameters compared to Java variables? But as for the other part of your question, you could definitely use a constant String without any problems.
EDIT: I've just tried this with a String array, and didn't run into the problem you mentioned - however the compiler did tell me that the "attribute value must be constant" despite the array being defined as public static final String[]
. Perhaps it doesn't like the fact that arrays are mutable? Hmm...
This is an old post but for anyone wanting to use variables as @centurian said the single quotes mean nothing will be expanded.
A simple way to get variables in is to do string concatenation since this is done by juxtaposition in bash the following should work:
sed -i -e "s/$var1/$var2/g" /tmp/file.txt
\s
is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.
str.replace(/\s/g, "X")
I just had a similar problem, and found this question and the answers really useful. Here's the part I was confused about. I'm writing it explicitly because no one actually stated it simply in English:
The iteration goes at the end.
Normally, a loop goes
for this many times:
if conditional:
do this thing
else:
do something else
Everyone states the list comprehension part simply as the first answer did,
[ expression for item in list if conditional ]
but that's actually not what you do in this case. (I was trying to do it that way)
In this case, it's more like this:
[ expression if conditional else other thing for this many times ]
You can use
android:ellipsize="marquee"
with your textview.
But remember to put focus on the desired textview.
here for i know here
SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.TABLES where table_schema in ('databasename1','databasename2');
If cannot delete or update a parent row: a foreign key constraint fails
That happens if there are tables with foreign keys references to the table you are trying to drop/truncate.
Before truncating tables All you need to do is:
SET FOREIGN_KEY_CHECKS=0;
Truncate your tables and change it back to
SET FOREIGN_KEY_CHECKS=1;
user this php code
$truncate = mysql_query("SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') as tables_query FROM INFORMATION_SCHEMA.TABLES where table_schema in ('databasename')");
while($truncateRow=mysql_fetch_assoc($truncate)){
mysql_query($truncateRow['tables_query']);
}
?>
check detail here link
You can write a theme:
<pre>
android:name=".List10" android:theme="@style/Theme"
theme.xml
<style name="Theme" parent="android:Theme">
<item name="android:listViewStyle">@style/MyListView</item>
</style>
styles.xml
<style name="MyListView" parent="@android:style/Widget.ListView">
<item name="android:listSelector">@drawable/my_selector</item>
my_selector is your want to custom selector I am sorry i donot know how to write my code
You can also use blank single quotes for the auto_increment column. something like this. It worked for me.
$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";
Today I designed this Ant MacroDef for the same problem as yours :
<!--
Recursively read a source directory for TypeScript files, generate a compile list in the
format needed by the TypeScript compiler adding every parameters it take.
-->
<macrodef name="TypeScriptCompileDir">
<!-- required attribute -->
<attribute name="src" />
<!-- optional attributes -->
<attribute name="out" default="" />
<attribute name="module" default="" />
<attribute name="comments" default="" />
<attribute name="declarations" default="" />
<attribute name="nolib" default="" />
<attribute name="target" default="" />
<sequential>
<!-- local properties -->
<local name="out.arg"/>
<local name="module.arg"/>
<local name="comments.arg"/>
<local name="declarations.arg"/>
<local name="nolib.arg"/>
<local name="target.arg"/>
<local name="typescript.file.list"/>
<local name="tsc.compile.file"/>
<property name="tsc.compile.file" value="@{src}compile.list" />
<!-- Optional arguments are not written to compile file when attributes not set -->
<condition property="out.arg" value="" else='--out "@{out}"'>
<equals arg1="@{out}" arg2="" />
</condition>
<condition property="module.arg" value="" else="--module @{module}">
<equals arg1="@{module}" arg2="" />
</condition>
<condition property="comments.arg" value="" else="--comments">
<equals arg1="@{comments}" arg2="" />
</condition>
<condition property="declarations.arg" value="" else="--declarations">
<equals arg1="@{declarations}" arg2="" />
</condition>
<condition property="nolib.arg" value="" else="--nolib">
<equals arg1="@{nolib}" arg2="" />
</condition>
<!-- Could have been defaulted to ES3 but let the compiler uses its own default is quite better -->
<condition property="target.arg" value="" else="--target @{target}">
<equals arg1="@{target}" arg2="" />
</condition>
<!-- Recursively read TypeScript source directory and generate a compile list -->
<pathconvert property="typescript.file.list" dirsep="\" pathsep="${line.separator}">
<fileset dir="@{src}">
<include name="**/*.ts" />
</fileset>
<!-- In case regexp doesn't work on your computer, comment <mapper /> and uncomment <regexpmapper /> -->
<mapper type="regexp" from="^(.*)$" to='"\1"' />
<!--regexpmapper from="^(.*)$" to='"\1"' /-->
</pathconvert>
<!-- Write to the file -->
<echo message="Writing tsc command line arguments to : ${tsc.compile.file}" />
<echo file="${tsc.compile.file}" message="${typescript.file.list}${line.separator}${out.arg}${line.separator}${module.arg}${line.separator}${comments.arg}${line.separator}${declarations.arg}${line.separator}${nolib.arg}${line.separator}${target.arg}" append="false" />
<!-- Compile using the generated compile file -->
<echo message="Calling ${typescript.compiler.path} with ${tsc.compile.file}" />
<exec dir="@{src}" executable="${typescript.compiler.path}">
<arg value="@${tsc.compile.file}"/>
</exec>
<!-- Finally delete the compile file -->
<echo message="${tsc.compile.file} deleted" />
<delete file="${tsc.compile.file}" />
</sequential>
</macrodef>
Use it in your build file with :
<!-- Compile a single JavaScript file in the bin dir for release -->
<TypeScriptCompileDir
src="${src-js.dir}"
out="${release-file-path}"
module="amd"
/>
It is used in the project PureMVC for TypeScript I'm working on at the time using Webstorm.
The exec
built-in command mirrors functions in the kernel, there are a family of them based on execve
, which is usually called from C.
exec
replaces the current program in the current process, without fork
ing a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;
We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile
, the last statement says something like:
exec appln-program
so now there is no shell to go back to. Even if appln-program
crashes, the end-user cannot get to a shell, because it is not there - the exec
replaced it.
We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh
, and everyone just put into their .login
(csh start-up file) a call to ksh
. While that worked, it left a stray csh
process running, and the logout was two stage which could get confusing. So we changed it to exec ksh
which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh
is not a login-shell).
Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4
etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.
You have obviously seen exec
used somewhere, perhaps if you showed the code that's bugging you we could justify its use.
Edit: I realised that my answer above is incomplete. There are two uses of exec
in shells like ksh
and bash
- used for opening file descriptors. Here are some examples:
exec 3< thisfile # open "thisfile" for reading on file descriptor 3
exec 4> thatfile # open "thatfile" for writing on file descriptor 4
exec 8<> tother # open "tother" for reading and writing on fd 8
exec 6>> other # open "other" for appending on file descriptor 6
exec 5<&0 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4 # copy write file descriptor 4 onto 7
exec 3<&- # close the read file descriptor 3
exec 6>&- # close the write file descriptor 6
Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec
reverts to the original meaning:
exec 3 < thisfile # oops, overwrite the current program with command "3"
There are several ways you can use these, on ksh use read -u
or print -u
, on bash
, for example:
read <&3
echo stuff >&4
You should check if the callback exists, and is an executable function:
if (callback && typeof(callback) === "function") {
// execute the callback, passing parameters as necessary
callback();
}
A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes error
and data
to the callback). Looking into their source code would help!
Go to Right click->Debug Configuration
and check if too many debug instances are created.
My issue was resolved when i deleted multiple debug instances from configuration and freshly started debugging.
Reusing An Angular.js Filter - View / Controller
This Solution is covering reusing Angular Filters. Which is yet another way to filter data, and Google landed me here when I needed such; and I like to share.
Use Case
If you are already filtering, say in an ng-repeat in your view (as below), then you might have defined a filter in the controller as further follows. And then you can reuse as in the final examples.
Filter Use Example - Filtered Repeat in View
<div ng-app="someApp" ng-controller="someController">
<h2>Duplicates</h2>
<table class="table table-striped table-light table-bordered-light">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in data | filter: searchDuplicate:true">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
</tr>
</tbody>
</table>
</div>
Angular Filter Definition Example
angular.module('someApp',[])
.controller('someController', function($scope, $filter ) {
$scope.people = [{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'female', hasDuplicate: false}];
$scope.searchDuplicate = { hasDuplicate : true };
})
So, the concept here is that you are already using a filter created for your view, and then realize you would like to use it in your controller also.
Filter Function Use Within Controller Example 1
var dup = $filter('filter')($scope.people, $scope.searchDuplicate, true)
Filter Function Use Within Controller Example 2
Show a Button only if no duplicates are found, using the prior filter.
Html Button
<div ng-if="showButton()"><button class="btn btn-primary" ng-click="doSomething();"></button></div>
Show/Hide Button
$scope.doSomething = function(){ /* ... */ };
$scope.showButton = function(){ return $filter('filter')($scope.people, $scope.searchDuplicate, true).length == 0; };
Some may find this version of filtering easy, and it is an Angular.js option.
The optional comparator parameter "true" used in the view and in the $filter function call specifies you want a strict comparison. If you omit, values can be searched for over multiple columns.
By default the last expression of a function will be returned.
In your example there is another expression after the point, where you want your return value.
If you want to return anything prior to your last expression, you still have to use return
.
You could modify your example like this, to return a Boolean
from the first part
def balanceMain(elem: List[Char]): Boolean = {
if (elem.isEmpty) {
// == is a Boolean resulting function as well, so your can write it this way
count == 0
} else {
// keep the rest in this block, the last value will be returned as well
if (elem.head == "(") {
balanceMain(elem.tail, open, count + 1)
}
// some more statements
...
// just don't forget your Boolean in the end
someBoolExpression
}
}
Let me try example
for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } & done ; sleep 10
And use jobs
to see what's running.
I use this and it works fine
#/bin/bash
/usr/bin/python python python_script.py
If you want to do it while keeping the user interaction on.
In my case I am using (or rather misusing) isFocused
self.myField.inputView = UIView()
This way it will focus but keyboard won't show up.
To check if WhatsApp is installed in device and initiate "click to chat" in WhatsApp:
Kotlin:
try {
// Check if whatsapp is installed
context?.packageManager?.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$internationalPhoneNumber"))
startActivity(intent)
} catch (e: NameNotFoundException) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
Java:
try {
// Check if whatsapp is installed
getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/" + internationalPhoneNumber));
startActivity(intent);
} catch (NameNotFoundException e) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}
getPackageInfo()
throws NameNotFoundException
if WhatsApp is not installed.
The internationalPhoneNumber
variable is used to access the phone number.
Reference:
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
JavaScript will "convert" numeric string to integer, if you perform calculations on it (as JS is weakly typed). But you can convert it yourself using parseInt
or parseFloat
.
Just remember to put radix in parseInt
!
In case of integer inputs:
var x = parseInt(prompt("Enter a Value", "0"), 10);
var y = parseInt(prompt("Enter a Value", "0"), 10);
In case of float:
var x = parseFloat(prompt("Enter a Value", "0"));
var y = parseFloat(prompt("Enter a Value", "0"));
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
Use <property name="build.sysclasspath" value="last"/>
in your build.xml file
For more details search includeAntRuntime
in Ant javac
Other possible values could be found here
if you are going to do a query you can join in your Inline Table Valued function like:
SELECT
a.*,b.*
FROM AAAA a
INNER JOIN MyNS.GetUnshippedOrders() b ON a.z=b.z
it will incur little overhead and run fine.
if you try to use your the Multi Statement Table Valued in a similar query, you will have performance issues:
SELECT
x.a,x.b,x.c,(SELECT OrderQty FROM MyNS.GetLastShipped(x.CustomerID)) AS Qty
FROM xxxx x
because you will execute the function 1 time for each row returned, as the result set gets large, it will run slower and slower.
Have you tried this:
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class cat{
public static void main (String [] args) throws Exception{
try{
FileSystem fs = FileSystem.get(new Configuration());
FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in")); // you need to pass in your hdfs path
for (int i=0;i<status.length;i++){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
String line;
line=br.readLine();
while (line != null){
System.out.println(line);
line=br.readLine();
}
}
}catch(Exception e){
System.out.println("File not found");
}
}
}
Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.
Something that (surprisingly) hasn't been mentioned here is simple concatenation.
Example:
foo = "seven"
print("She lives with " + foo + " small men")
Result:
She lives with seven small men
Additionally, as of Python 3, the %
method is deprecated. Don't use that.
This is my solution:
# your test class
class TestingClass(unittest.TestCase):
# This will only run once for all the tests within this class
@classmethod
def setUpClass(cls) -> None:
if len(sys.argv) > 1:
cls.email = sys.argv[1]
def testEmails(self):
assertEqual(self.email, "[email protected]")
if __name__ == "__main__":
unittest.main()
you could have a runner.py
file with something like this:
# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests
with the above code, you should be to run your tests with runner.py [email protected]
A global variable would be best expressed in an external JavaScript file:
var system_status;
Make sure that this has not been used anywhere else. Then to access the variable on your page, just reference it as such. Say, for example, you wanted to fill in the results on a textbox,
document.getElementById("textbox1").value = system_status;
To ensure that the object exists, use the document ready feature of jQuery.
Example:
$(function() {
$("#textbox1")[0].value = system_status;
});
this is what i did to loose the double values when using the Html.CheckBox(...
Replace("true,false","true").Split(',')
with 4 boxes checked, unchecked, unchecked, checked it turns true,false,false,false,true,false into true,false,false,true. just what i needed
This works for me:
URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));
for ( int i; (i = in.read()) != -1; ) {
out.write(i);
}
in.close();
out.close();
try:
git ls-files --error-unmatch <file name>
will exit with 1 if file is not tracked
Here is another variation using views:
CREATE VIEW digits AS
SELECT 0 AS digit UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9;
CREATE VIEW numbers AS
SELECT
ones.digit + tens.digit * 10 + hundreds.digit * 100 + thousands.digit * 1000 AS number
FROM
digits as ones,
digits as tens,
digits as hundreds,
digits as thousands;
CREATE VIEW dates AS
SELECT
SUBDATE(CURRENT_DATE(), number) AS date
FROM
numbers;
And then you can simply do (see how elegant it is?):
SELECT
date
FROM
dates
WHERE
date BETWEEN '2010-01-20' AND '2010-01-24'
ORDER BY
date
Update
It is worth noting that you will only be able to generate past dates starting from the current date. If you want to generate any kind of dates range (past, future, and in between), you will have to use this view instead:
CREATE VIEW dates AS
SELECT
SUBDATE(CURRENT_DATE(), number) AS date
FROM
numbers
UNION ALL
SELECT
ADDDATE(CURRENT_DATE(), number + 1) AS date
FROM
numbers;
Combining the answers above, you can implement something that works like the gem colorize without needing another dependency.
class String
# colorization
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def pink
colorize(35)
end
def light_blue
colorize(36)
end
end
I found that when within a Miniconda3 environment I had to run:
conda deactivate
Neither deactivate
nor source deactivate
worked for me.
Use @SessionAttributes
See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests
"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttribute
s are transferred into the session (if the controller is @SessionAttributes
annotated).
That article also explains that it is better to use @SessionAttributes
on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.
i think unlink & link php versions are not enough because we are often using php with apache(httpd), so need to update httpd.conf after switch php version.
i have write shell script for disable/enable php_module
automatically inside httpd.conf
, look at line 46 to line 54 https://github.com/dangquangthai/switch-php-version-on-mac-sierra/blob/master/switch-php#L46
Follow my steps:
1) Check installed php versions by brew, for sure everything good
> brew list | grep php
#output
php56
php56-intl
php56-mcrypt
php71
php71-intl
php71-mcrypt
2) Run script
> switch-php 71 # or switch-php 56
#output
PHP version [71] found
Switching from [php56] to [php71] ...
Unlink php56 ... [OK] and Link php71 ... [OK]
Updating Apache2.4 Configuration /usr/local/etc/httpd/httpd.conf ... [OK]
Restarting Apache2.4 ... [OK]
PHP 7.1.11 (cli) (built: Nov 3 2017 08:48:02) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
3) Finally, when your got above message, check httpd.conf
, in my laptop:
vi /usr/local/etc/httpd/httpd.conf
You can see near by LoadModule lines
LoadModule php7_module /usr/local/Cellar/php71/7.1.11_22/libexec/apache2/libphp7.so
#LoadModule php5_module /usr/local/Cellar/php56/5.6.32_8/libexec/apache2/libphp5.so
4) open httpd://localhost/info.php
i hope it helpful
I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .
I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
Ed: phpMyAdmin is for MySQL, but the asker needs something for Microsoft SQL Server.
Most solutions that I found involve using an ODBC Driver and then whatever client application you use. For example, Gorilla SQL claims to be able to do that, even though the project seems abandoned.
Most good solutions are either using Remote Desktop or VMware/Parallels.
Regarding @Cherian's answer, the following lines can be removed:
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ANSI';
...
SET SQL_MODE=@OLD_SQL_MODE;
...
This was a bug pre 5.1.23. After that version these are no longer required. So, for copy/paste convenience, here is the same with the above lines removed. Again, for example purposes "test" is the user and "databaseName" is the database; and this was from this bug.
DROP PROCEDURE IF EXISTS databaseName.drop_user_if_exists ;
DELIMITER $$
CREATE PROCEDURE databaseName.drop_user_if_exists()
BEGIN
DECLARE foo BIGINT DEFAULT 0 ;
SELECT COUNT(*)
INTO foo
FROM mysql.user
WHERE User = 'test' and Host = 'localhost';
IF foo > 0 THEN
DROP USER 'test'@'localhost' ;
END IF;
END ;$$
DELIMITER ;
CALL databaseName.drop_user_if_exists() ;
DROP PROCEDURE IF EXISTS databaseName.drop_users_if_exists ;
CREATE USER 'test'@'localhost' IDENTIFIED BY 'a';
GRANT ALL PRIVILEGES ON databaseName.* TO 'test'@'localhost'
WITH GRANT OPTION
For iOS SWIFT I found this helpful,
let phoneRegEx = "^((\\+)|(00)|(\\*)|())[0-9]{3,14}((\\#)|())$"
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
Original answer 2010:
If all of those directories are separate git repo, you should reference them as submodules.
That means your "origin" would be that remote repo 'plugins
' which only contains references to subrepos 'cms
', 'admin
', 'chart
'.
A git pull
followed by a git submodule update
would achieve what your are looking for.
Update January 2016:
With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2
.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"
If you don't have password you can use the command without
-u
Like this
C:\wamp>bin\mysql\mysql5.7.11\bin\mysql.exe -u {User Name} {Database Name} < C:\File.sql
Or on the SQL console
mysql -u {User Name} -p {Database Name} < C:/File.sql
Lets say your HTML looks something like this:
<div class="box">
<!-- stuff -->
<p class="bet_time">Bet 5 days ago</p>
</div>
Then, with CSS, you can make that text appear in the bottom right like so:
.box {
position:relative;
}
.bet_time {
position:absolute;
bottom:0;
right:0;
}
The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time
positions its right edge to the right edge of .box
and its bottom edge to the bottom edge of .box
In my case i haven't given the
orientation of LinearLayout(ScrollView's Child)
So by default it takes horizontal, but scrollview scrols vertically, so please check if 'android:orientation="vertical"' is set to your ScrollView's Child(In the case of LinearLayout).
This was my case hopes it helps somebody
.
Mark Berry's answer worked fine here. I just add to split the previous code:
$.clearFormFields = function(area) {
$(area).find('input[type="text"],input[type="email"],textarea,select').val('');
};
to:
$.clearFormFields = function(area) {
$(area).find('input#name').val('');
$(area).find('input#phone').val("");
$(area).find('input#email').val("");
$(area).find('select#topic').val("");
$(area).find('textarea#description').val("");
};
you can do it using aws cli : https://aws.amazon.com/cli/ and some unix command.
this aws cli commands should work:
aws s3 rm s3://<your_bucket_name> --exclude "*" --include "<your_regex>"
if you want to include sub-folders you should add the flag --recursive
or with unix commands:
aws s3 ls s3://<your_bucket_name>/ | awk '{print $4}' | xargs -I% <your_os_shell> -c 'aws s3 rm s3:// <your_bucket_name> /% $1'
explanation:
Use:
dqote='"'
sqote="'"
Use the '+' operator and dqote
and squote
variables to get what you need.
If I want sed -e s/",u'"/",'"/g -e s/^"u'"/"'"/
, you can try the following:
dqote='"'
sqote="'"
cmd1="sed -e s/" + dqote + ",u'" + dqote + "/" + dqote + ",'" + dqote + '/g -e s/^"u' + sqote + dqote + '/' + dqote + sqote + dqote + '/'
I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:
internal class Parent
{
public Parent()
{
Console.WriteLine("Parent ctor");
Console.WriteLine(Something);
}
protected virtual string Something { get; } = "Parent";
}
internal class Child : Parent
{
public Child()
{
Console.WriteLine("Child ctor");
Console.WriteLine(Something);
}
protected override string Something { get; } = "Child";
}
The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.
My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.
The output of the above when instantiating the child class is:
Parent ctor
Child
Child ctor
Child
I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).
This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.
Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.
Then under Tfvc: Location you can paste the location of the executable.
For 2017 it'll be
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Or for 2019 (Preview)
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.
After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone
pasted my repo:
Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen
Then chose the new method of authentication
Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).
Click Continue
Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.
Cheers!
Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.
The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.
var tabsHeight = 650;
$("tabs").attr('style', 'height: '+ tabsHeight +'px !important');
OR
#CSS
.myclass{height:650px !important;}
then
$("tabs").addClass("myclass");
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
From C# equivalent to Java HashMap
I needed a Dictionary which accepted a "null" key, but there seems to be no native one, so I have written my own. It's very simple, actually. I inherited from Dictionary, added a private field to hold the value for the "null" key, then overwritten the indexer. It goes like this :
public class NullableDictionnary : Dictionary<string, string>
{
string null_value;
public StringDictionary this[string key]
{
get
{
if (key == null)
{
return null_value;
}
return base[key];
}
set
{
if (key == null)
{
null_value = value;
}
else
{
base[key] = value;
}
}
}
}
Hope this helps someone in the future.
==========
I modified it to this format
public class NullableDictionnary : Dictionary<string, object>
time = Time.zone.now()
It will work as
irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC
/*
Double click behaves as one single click
"It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable."
That way we have to check what is the event that is being executed at any sequence.
*/
var totalClicks = 1;
$('#elementId').on('click dblclick', function (e) {
if (e.type == "dblclick") {
console.log("e.type1: " + e.type);
return;
} else if (e.type == "click") {
if (totalClicks > 1) {
console.log("e.type2: " + e.type);
totalClicks = 1;
return;
} else {
console.log("e.type3: " + e.type);
++totalClicks;
}
//execute the code you want to execute
}
});
Since it seems to be missing from the current list of answers, I think it is worth mentioning that the standard library includes a zipapp
module that can be used for this purpose. Its basic usage is just compressing a bunch of Python files into a zip file with extension .pyz
than can be directly executed as python myapp.pyz
, but you can also make a self-contained package from a requirements.txt
file:
$ python -m pip install -r requirements.txt --target myapp
$ python -m zipapp -p "interpreter" myapp
Where interpreter
can be something like /usr/bin/env python
(see Specifying the Interpreter).
Usually, the generated .pyz
/ .pyzw
file should be executable, in Unix because it gets marked as such and in Windows because Python installation usually registers those extensions. However, it is relatively easy to make a Windows executable that should work as long as the user has python3.dll
in the path.
If you don't want to require the end user to install Python, you can distribute the application along with the embeddable Python package.
An empty string has one single null byte. So test if (s[0] == (char)0)
echo %DATE:~10,4%%DATE:~7,2%%DATE:~4,2%
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
I took the above but had to add one more piece because it was putting a space after the hour which gave a syntax error with the rename command. I used:
set HR=%time:~0,2%
set HR=%Hr: =0%
set HR=%HR: =%
rename c:\ops\logs\copyinvoices.log copyinvoices_results_%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%.log
This gave me my format I needed: copyinvoices_results_2013-09-13_0845.log
I like this way:
using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());
Lifted from this MSDN article.
If you're using docker-machine
(docker on Windows or OSX).
Currently docker-machine has a bug that it loses internet connection if you switch between wifi networks or wifi and cable.
Make sure you restart your docker-machine
usually: docker-machine restart default
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
In my case, I was installing a project with MinimumSDK bigger than the Android version of my real device. I used another device and it solved MinSDK -> 24 My Phone -> 21
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
In my case, files were exactly the same (content, line endings, filemodes, md5 checksum, everything), yet were still visible in git status
.
What helped was
# Garbage collect stuffs from .git
git gc
# commit stuff
git add .
git commit -m "temporary"
# this doesn't change contents
git reset HEAD^1 --soft
After that, git status
showed only one editted file that I editted.
I know it's 2 years late, but these answers helped me to formulate a filter function to output objects and trim the resulting strings. Since I have to format everything into a string in my final solution I went about things a little differently. Long-hand, my problem is very similar, and looks a bit like this
$verbosepreference="Continue"
write-verbose (ls | ft | out-string) # this generated too many blank lines
Here is my example:
ls | Out-Verbose # out-verbose formats the (pipelined) object(s) and then trims blanks
My Out-Verbose function looks like this:
filter Out-Verbose{
Param([parameter(valuefrompipeline=$true)][PSObject[]]$InputObject,
[scriptblock]$script={write-verbose "$_"})
Begin {
$val=@()
}
Process {
$val += $inputobject
}
End {
$val | ft -autosize -wrap|out-string |%{$_.split("`r`n")} |?{$_.length} |%{$script.Invoke()}
}
}
Note1: This solution will not scale to like millions of objects(it does not handle the pipeline serially)
Note2: You can still add a -noheaddings option. If you are wondering why I used a scriptblock here, that's to allow overloading like to send to disk-file or other output streams.
In SQL 2005:
select object_name(object_id), name
from sys.columns
where is_identity = 1
I got similar issue. The mistake i made was I did not add service in the providers array in app.module.ts. Hope this helps, Thank You.
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:
function SetHeight(){
var h = $(window).height();
$("#inner-right").height(h-200);
}
$(document).ready(SetHeight);
$(window).resize(SetHeight);
The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.
Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.
* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).
Tested and working. Check this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
xml
<RadioGroup
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_male"
android:checked="true" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.
user1 = pd.read_csv('dataset/1.csv')
If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.
col_names=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=col_names)
To solve above problem we have to add extra filled which is supported by pandas, It is header=None
user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)
After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit
.
You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!
).
class1 item = lst[index];
item.foo = bar;
Use this function.
private String leftPadding(String word, int length, char ch) {
return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}
how to use?
leftPadding(month, 2, '0');
output: 01 02 03 04 .. 11 12
You have to reimplement it using <xsl:choose>
tag:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:when>
<xsl:otherwise>
<h2> dooooooooooooo </h2>
</xsl:otherwise>
</xsl:choose>
Did you try cal.getTime()
? This gets the date representation.
You might also want to look at the javadoc.
Assume that you have MyPayments class like
public class Mypayment
{
public int year { get; set; }
public string month { get; set; }
public string price { get; set; }
public bool ispaid { get; set; }
}
and you have a list of MyPayments
public List<Mypayment> mypayments { get; set; }
and you want group the list by year. You can use linq like this:
List<List<Mypayment>> mypayments = (from IGrouping<int, Mypayment> item in yearGroup
let mypayments1 = (from _payment in UserProjects.mypayments
where _payment.year == item.Key
select _payment).ToList()
select mypayments1).ToList();
This is an old question, but here is something that might help someone.
From the official docs:
Django provides tools for performing URL reversing that match the different layers where URLs are needed: In templates: Using the url template tag. In Python code: Using the reverse() function. In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.
Eg. in templates (url tag)
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
Eg. in python code (using the reverse
function)
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
This can be a huge approximation depending on your polygons, but here's one :
Though, this should be very efficient as any transformation to the polygon applies in the very same way to the center of mass and the center-node distances can be computed only once.
You can also use .gitattributes (instead of .gitignore) to exclude entire filetypes. The file is pretty self-explanatory, but I'm pasting the contents here for reference. Pay attention to the last line (*.class binary):
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.mo binary
*.pdf binary
*.phar binary
*.class binary
This answer by Jaap :
<div class="image"></div>?
and in CSS :
div.image {
content:url(http://placehold.it/350x150);
}?
you can try it on this link : http://jsfiddle.net/XAh2d/
this is a link about css content http://css-tricks.com/css-content/
This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)
Setting isBodyHtml
to true
allows you to use HTML tags in the message body:
msg = new MailMessage("[email protected]",
"[email protected]", "Message from PSSP System",
"This email sent by the PSSP system<br />" +
"<b>this is bold text!</b>");
msg.IsBodyHtml = true;
I had this same issue with dynamic tables. (Tables that are assumed to have an id to be able to join but without any assumption for the rest of the fields.) In this case you don't know the aliases before hand.
In such cases you can first get the table column names for all dynamic tables:
$tblFields = array_keys($zendDbInstance->describeTable($tableName));
Where $zendDbInstance is an instance of Zend_Db or you can use one of the functions here to not rely on Zend php pdo: get the columns name of a table
Then for all dynamic tables you can get the aliases and use $tableName.* for the ones you don't need aliases:
$aliases = "";
foreach($tblKeys as $field)
$aliases .= $tableName . '.' . $field . ' AS ' . $tableName . '_' . $field . ',' ;
$aliases = trim($aliases, ',');
You can wrap this whole process up into one generic function and just have cleaner code or get more lazy if you wish :)
No you cannot get the URL in single action but two :)
First of all, you may have to make the file public before uploading because it makes no sense to get the URL that no one can access. You can do so by setting ACL as Michael Astreiko suggested.
You can get the resource URL either by calling getResourceUrl
or getUrl
.
AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");
Note1:
The different between getResourceUrl
and getUrl
is that getResourceUrl will return null when exception occurs.
Note2:
getUrl
method is not defined in the AmazonS3 interface. You have to cast the object to AmazonS3Client if you use the standard builder.
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
reduced to the simplest and most significant form without losing generality
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
You can use Container to contain your widget:
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff000000),
width: 1,
)),
child: Text()
),
from collections import OrderedDict
OrderedDict((word, True) for word in words)
contains
OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])
If the values are True
(or any other immutable object), you can also use:
OrderedDict.fromkeys(words, True)
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
Try 'build-essential' instead.
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
I succinctified Poyson 1's answer like so:
public static bool IsValidEmailAddress(string candidateEmailAddr)
{
string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) &&
(Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}
var htmlEntities = [
{regex:/&/g,entity:'&'},
{regex:/>/g,entity:'>'},
{regex:/</g,entity:'<'},
{regex:/"/g,entity:'"'},
{regex:/á/g,entity:'á'},
{regex:/é/g,entity:'é'},
{regex:/í/g,entity:'í'},
{regex:/ó/g,entity:'ó'},
{regex:/ú/g,entity:'ú'}
];
total = <some string value>
for(v in htmlEntities){
total = total.replace(htmlEntities[v].regex, htmlEntities[v].entity);
}
A array solution
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.
LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.
LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.
Key features of LXD are:
There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.
However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.
The OpenStack nclxd plugin a list of features supported include:
stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support
By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
It's a placeholder for a parameter much like the %s
format specifier acts within printf
.
You can start adding extra things in there to determine the format too, though that makes more sense with a numeric variable (examples here).
If you're using a <select>
, .val()
gets the 'value' of the selected <option>
. If it doesn't have a value
, it may fallback to the id
. Put the value you want it to return in the value
attribute of each <option>
Edit: See comments for clarification on what value
actually is (not necessarily equal to the value
attribute).
To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:
a) how to return all the VALUES of the dictionary:
>as.numeric(foo)
[1] 12 22 33
b) check whether dictionary CONTAINS KEY:
>'tic' %in% names(foo)
[1] TRUE
c) how to ADD NEW key, value pair to dictionary:
c(foo,tic2=44)
results:
tic tac toe tic2
12 22 33 44
d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)
e) how to DELETE pair BY KEY from dictionary:
foo<-foo[which(foo!=foo[["tac"]])]
Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.
http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager
Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")
Where thisFile = the absolute path of the file you are changing
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
use this:
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
Swift 3:
self.btn.sendActions(for: .touchUpInside)
You can use the following command:
git checkout HEAD -- my-file.txt
... which will update both the working copy of my-file.txt
and its state in the index with that from HEAD.
--
basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
You can see if object has shape or not
def check_array(x):
try:
x.shape
return True
except:
return False
When you use a web service you have a client and a server:
When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.
Consider you've created a procedure like below.
CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
FIRST_NAME IN VARCHAR2,
LAST_NAME IN VARCHAR2,
FULL_NAME OUT VARCHAR2
) IS
BEGIN
FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;
In Oracle SQL Developer, you can run this procedure in two ways.
1. Using SQL Worksheet
Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5
DECLARE
FULL_NAME Varchar2(50);
BEGIN
GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;
2. Using GUI Controls
Expand Procedures
Right click on the procudure you've created and Click Run
In the pop-up window, Fill the parameters and Click OK.
Cheers!
In php.ini
search for upload_max_filesize and post_max_size. I had the same problem and the solution was to change these values to a value greater than the file size.
Can you describe the paradigm shift that is necessary?
Imperative vs Declarative
With jQuery you tell the DOM what needs to happen, step by step. With AngularJS you describe what results you want but not how to do it. More on this here. Also, check out Mark Rajcok's answer.
How do I architect and design client-side web apps differently?
AngularJS is an entire client-side framework that uses the MVC pattern (check out their graphical representation). It greatly focuses on separation of concerns.
What is the biggest difference? What should I stop doing/using; what should I start doing/using instead?
jQuery is a library
AngularJS is a beautiful client-side framework, highly testable, that combines tons of cool stuff such as MVC, dependency injection, data binding and much more.
It focuses on separation of concerns and testing (unit testing and end-to-end testing), which facilitates test-driven development.
The best way to start is going through their awesome tutorial. You can go through the steps in a couple of hours; however, in case you want to master the concepts behind the scenes, they include a myriad of reference for further reading.
Are there any server-side considerations/restrictions?
You may use it on existing applications where you are already using pure jQuery. However, if you want to fully take advantage of the AngularJS features you may consider coding the server side using a RESTful approach.
Doing so will allow you to leverage their resource factory, which creates an abstraction of your server side RESTful API and makes server-side calls (get, save, delete, etc.) incredibly easy.
my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.
$file_name = "a.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
Likov's Substitution Principle states that if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.
Intent - Derived types must be completely substitute able for their base types.
Example - Co-variant return types in java.
This is all that is needed to remove the status bar.
A service creation example of using backslashes with many double quotes.
C:\Windows\system32>sc.exe create teagent binpath= "\"C:\Program Files\Tripwire\TE\Agent\bin\wrapper.exe\" -s \"C:\Program Files\Tripwire\TE\Agent\bin\agent.conf\"" DisplayName= "Tripwire Enterprise Agent"
[SC] CreateService SUCCESS