django change default runserver port
We created a new 'runserver' management command which is a thin wrapper around the standard one but changes the default port. Roughly, you create management/commands/runserver.py
and put in something like this:
# Override the value of the constant coded into django...
import django.core.management.commands.runserver as runserver
runserver.DEFAULT_PORT="8001"
# ...print out a warning...
# (This gets output twice because runserver fires up two threads (one for autoreload).
# We're living with it for now :-)
import os
dir_path = os.path.splitext(os.path.relpath(__file__))[0]
python_path = dir_path.replace(os.sep, ".")
print "Using %s with default port %s" % (python_path, runserver.DEFAULT_PORT)
# ...and then just import its standard Command class.
# Then manage.py runserver behaves normally in all other regards.
from django.core.management.commands.runserver import Command
LISTAGG function: "result of string concatenation is too long"
You are exceeding the SQL limit of 4000 bytes which applies to LISTAGG
as well.
SQL> SELECT listagg(text, ',') WITHIN GROUP (
2 ORDER BY NULL)
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
SELECT listagg(text, ',') WITHIN GROUP (
*
ERROR at line 1:
ORA-01489: result of string concatenation is too long
As a workaround, you could use XMLAGG.
For example,
SQL> SET LONG 2000000
SQL> SET pagesize 50000
SQL> SELECT rtrim(xmlagg(XMLELEMENT(e,text,',').EXTRACT('//text()')
2 ).GetClobVal(),',') very_long_text
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
VERY_LONG_TEXT
--------------------------------------------------------------------------------
one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen
,fifteen,sixteen,seventeen,eighteen,nineteen,twenty,twenty-one,twenty-two,twenty
-three,twenty-four,twenty-five,twenty-six,twenty-seven,twenty-eight,twenty-nine,
thirty,thirty-one,thirty-two,thirty-three,thirty-four,thirty-five,thirty-six,thi
rty-seven,thirty-eight,thirty-nine,forty,forty-one,forty-two,forty-three,forty-f
our,forty-five,forty-six,forty-seven,forty-eight,forty-nine,fifty,fifty-one,fift
y-two,fifty-three,fifty-four,fifty-five,fifty-six,fifty-seven,fifty-eight,fifty-
nine,sixty,sixty-one,sixty-two,sixty-three,sixty-four,sixty-five,sixty-six,sixty
-seven,sixty-eight,sixty-nine,seventy,seventy-one,seventy-two,seventy-three,seve
nty-four,seventy-five,seventy-six,seventy-seven,seventy-eight,seventy-nine,eight
y,eighty-one,eighty-two,eighty-three,eighty-four,eighty-five,eighty-six,eighty-s
even,eighty-eight,eighty-nine,ninety,ninety-one,ninety-two,ninety-three,ninety-f
our,ninety-five,ninety-six,ninety-seven,ninety-eight,ninety-nine,one hundred,one
hundred one,one hundred two,one hundred three,one hundred four,one hundred five
,one hundred six,one hundred seven,one hundred eight,one hundred nine,one hundre
d ten,one hundred eleven,one hundred twelve,one hundred thirteen,one hundred fou
rteen,one hundred fifteen,one hundred sixteen,one hundred seventeen,one hundred
eighteen,one hundred nineteen,one hundred twenty,one hundred twenty-one,one hund
red twenty-two,one hundred twenty-three,one hundred twenty-four,one hundred twen
ty-five,one hundred twenty-six,one hundred twenty-seven,one hundred twenty-eight
,one hundred twenty-nine,one hundred thirty,one hundred thirty-one,one hundred t
hirty-two,one hundred thirty-three,one hundred thirty-four,one hundred thirty-fi
ve,one hundred thirty-six,one hundred thirty-seven,one hundred thirty-eight,one
hundred thirty-nine,one hundred forty,one hundred forty-one,one hundred forty-tw
o,one hundred forty-three,one hundred forty-four,one hundred forty-five,one hund
red forty-six,one hundred forty-seven,one hundred forty-eight,one hundred forty-
nine,one hundred fifty,one hundred fifty-one,one hundred fifty-two,one hundred f
ifty-three,one hundred fifty-four,one hundred fifty-five,one hundred fifty-six,o
ne hundred fifty-seven,one hundred fifty-eight,one hundred fifty-nine,one hundre
d sixty,one hundred sixty-one,one hundred sixty-two,one hundred sixty-three,one
hundred sixty-four,one hundred sixty-five,one hundred sixty-six,one hundred sixt
y-seven,one hundred sixty-eight,one hundred sixty-nine,one hundred seventy,one h
undred seventy-one,one hundred seventy-two,one hundred seventy-three,one hundred
seventy-four,one hundred seventy-five,one hundred seventy-six,one hundred seven
ty-seven,one hundred seventy-eight,one hundred seventy-nine,one hundred eighty,o
ne hundred eighty-one,one hundred eighty-two,one hundred eighty-three,one hundre
d eighty-four,one hundred eighty-five,one hundred eighty-six,one hundred eighty-
seven,one hundred eighty-eight,one hundred eighty-nine,one hundred ninety,one hu
ndred ninety-one,one hundred ninety-two,one hundred ninety-three,one hundred nin
ety-four,one hundred ninety-five,one hundred ninety-six,one hundred ninety-seven
,one hundred ninety-eight,one hundred ninety-nine,two hundred,two hundred one,tw
o hundred two,two hundred three,two hundred four,two hundred five,two hundred si
x,two hundred seven,two hundred eight,two hundred nine,two hundred ten,two hundr
ed eleven,two hundred twelve,two hundred thirteen,two hundred fourteen,two hundr
ed fifteen,two hundred sixteen,two hundred seventeen,two hundred eighteen,two hu
ndred nineteen,two hundred twenty,two hundred twenty-one,two hundred twenty-two,
two hundred twenty-three,two hundred twenty-four,two hundred twenty-five,two hun
dred twenty-six,two hundred twenty-seven,two hundred twenty-eight,two hundred tw
enty-nine,two hundred thirty,two hundred thirty-one,two hundred thirty-two,two h
undred thirty-three,two hundred thirty-four,two hundred thirty-five,two hundred
thirty-six,two hundred thirty-seven,two hundred thirty-eight,two hundred thirty-
nine,two hundred forty,two hundred forty-one,two hundred forty-two,two hundred f
orty-three,two hundred forty-four,two hundred forty-five,two hundred forty-six,t
wo hundred forty-seven,two hundred forty-eight,two hundred forty-nine
If you want to concatenate multiple columns which itself have 4000 bytes, then you can concatenate the XMLAGG output of each column to avoid the SQL limit of 4000 bytes.
For example,
WITH DATA AS
( SELECT 1 id, rpad('a1',4000,'*') col1, rpad('b1',4000,'*') col2 FROM dual
UNION
SELECT 2 id, rpad('a2',4000,'*') col1, rpad('b2',4000,'*') col2 FROM dual
)
SELECT ID,
rtrim(xmlagg(XMLELEMENT(e,col1,',').EXTRACT('//text()') ).GetClobVal(), ',')
||
rtrim(xmlagg(XMLELEMENT(e,col2,',').EXTRACT('//text()') ).GetClobVal(), ',')
AS very_long_text
FROM DATA
GROUP BY ID
ORDER BY ID;
numpy matrix vector multiplication
Simplest solution
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Other Solutions
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
Rarer options for edge cases
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
How do I get the day month and year from a Windows cmd.exe script?
I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.
Here is how to get the day, month, and year
for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i
Or, here is yesterday's date in yyyy-MM-dd format
for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i
Day of the week
for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d
Current time plus 15 minutes
for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i
Logging POST data from $request_body
FWIW, this config worked for me:
location = /logpush.html {
if ($request_method = POST) {
access_log /var/log/nginx/push.log push_requests;
proxy_pass $scheme://127.0.0.1/logsink;
break;
}
return 200 $scheme://$host/serviceup.html;
}
#
location /logsink {
return 200;
}
MySQL duplicate entry error even though there is no duplicate entry
Your code and schema are OK. You probably trying on previous version of table.
http://sqlfiddle.com/#!2/9dc64/1/0
Your table even has no UNIQUE, so that error is impossible on that table.
Backup data from that table, drop it and re-create.
Maybe you tried to run that CREATE TABLE IF NOT EXIST
. It was not created, you have old version, but there was no error because of IF NOT EXIST
.
You may run SQL like this to see current table structure:
DESCRIBE my_table;
Edit - added later:
Try to run this:
DROP TABLE `my_table`; --make backup - it deletes table
CREATE TABLE `my_table` (
`number` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`),
UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;
Why is it said that "HTTP is a stateless protocol"?
Because a stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests.
HTTP is a stateless protocol, which means that the connection between the browser and the server is lost once the transaction ends.
Switch case: can I use a range instead of a one number
You could have switch
construct "handle" ranges by using it in conjunction with a List
of your bounds.
List<int> bounds = new List<int>() {int.MinValue, 0, 4, 9, 17, 20, int.MaxValue };
switch (bounds.IndexOf(bounds.Last(x => x < j)))
{
case 0: // <=0
break;
case 1: // >= 1 and <=4
break;
case 2: // >= 5 and <=9
break;
case 3: // >= 10 and <=17
break;
case 4: // >= 18 and <=20
break;
case 5: // >20
break;
}
With this approach ranges can have different spans.
How do I detect IE 8 with jQuery?
It is documented in jQuery API Documentation. Check for Internet Explorer with $.browser.msie
and then check its version with $.browser.version
.
UPDATE: $.browser removed in jQuery 1.9
The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.
C++ variable has initializer but incomplete type?
It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef
directive. In this case compiler will just skip definition of the class thinking that it's a duplication.
Htaccess: add/remove trailing slash from URL
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]
## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.
Is this very likely to create a memory leak in Tomcat?
The message is actually pretty clear: something creates a ThreadLocal
with value of type org.apache.axis.MessageContext
- this is a great hint. It most likely means that Apache Axis framework forgot/failed to cleanup after itself. The same problem occurred for instance in Logback. You shouldn't bother much, but reporting a bug to Axis team might be a good idea.
Tomcat reports this error because the ThreadLocal
s are created per HTTP worker threads. Your application is undeployed but HTTP threads remain - and these ThreadLocal
s as well. This may lead to memory leaks (org.apache.axis.MessageContext
can't be unloaded) and some issues when these threads are reused in the future.
For details see: http://wiki.apache.org/tomcat/MemoryLeakProtection
How to tell bash that the line continues on the next line
In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:
# In general
$ echo "foo" \
> "bar"
foo bar
# Pipes
$ echo foo |
> cat
foo
# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar
Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.
$ x="foo
> bar"
$ echo "$x"
foo
bar
With a backslash, you are again splitting the logical line into multiple logical lines.
$ x="foo\
> bar"
$ echo "$x"
foobar
jQuery, get html of a whole element
You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just
var child = $('#div div:nth-child(1)').clone();
var child2 = $('#div div:nth-child(2)').clone();
You will get this for first query as asked in question
<div id="div1">
<p>Some Content</p>
</div>
How to play YouTube video in my Android application?
This answer could be really late, but its useful.
You can play youtube videos in the app itself using android-youtube-player.
Some code snippets:
To play a youtube video that has a video id in the url, you simply call the OpenYouTubePlayerActivity
intent
Intent intent = new Intent(null, Uri.parse("ytv://"+v), this,
OpenYouTubePlayerActivity.class);
startActivity(intent);
where v is the video id.
Add the following permissions in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
and also declare this activity in the manifest file:
<activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>
Further information can be obtained from the first portions of this code file.
Hope that helps anyone!
Necessary to add link tag for favicon.ico?
To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:
<link rel="icon" href="_/img/favicon.png">
This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
.
To learn more about using other file types like PNG check out this question.
For cache busting purposes:
Add a query string to the path for cache-busting purposes:
<link rel="icon" href="/favicon.ico?v=1.1">
Favicons are very heavily cached and this a great way to ensure a refresh.
Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link
for it.
Footnote about rel="icon"
:
As indicated by @Semanino's answer, using rel="shortcut icon"
is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon"
instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel
value of shortcut
isn't a valid option.
How to verify CuDNN installation?
Getting cuDNN Version [Linux]
Use following to find path for cuDNN:
cat $(whereis cudnn.h) | grep CUDNN_MAJOR -A 2
If above doesn't work try this:
cat $(whereis cuda)/include/cudnn.h | grep CUDNN_MAJOR -A 2
Getting cuDNN Version [Windows]
Use following to find path for cuDNN:
C:\>where cudnn*
C:\Program Files\cuDNN6\cuda\bin\cudnn64_6.dll
Then use this to dump version from header file,
type "%PROGRAMFILES%\cuDNN6\cuda\include\cudnn.h" | findstr "CUDNN_MAJOR CUDNN_MINOR CUDNN_PATCHLEVEL"
Getting CUDA Version
This works on Linux as well as Windows:
nvcc --version
Pointers in C: when to use the ampersand and the asterisk?
Put simply
&
means the address-of, you will see that in placeholders for functions to modify the parameter variable as in C, parameter variables are passed by value, using the ampersand means to pass by reference.
*
means the dereference of a pointer variable, meaning to get the value of that pointer variable.
int foo(int *x){
*x++;
}
int main(int argc, char **argv){
int y = 5;
foo(&y); // Now y is incremented and in scope here
printf("value of y = %d\n", y); // output is 6
/* ... */
}
The above example illustrates how to call a function foo
by using pass-by-reference, compare with this
int foo(int x){
x++;
}
int main(int argc, char **argv){
int y = 5;
foo(y); // Now y is still 5
printf("value of y = %d\n", y); // output is 5
/* ... */
}
Here's an illustration of using a dereference
int main(int argc, char **argv){
int y = 5;
int *p = NULL;
p = &y;
printf("value of *p = %d\n", *p); // output is 5
}
The above illustrates how we got the address-of y
and assigned it to the pointer variable p
. Then we dereference p
by attaching the *
to the front of it to obtain the value of p
, i.e. *p
.
Flask SQLAlchemy query, specify column names
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
Setting the value of checkbox to true or false with jQuery
You can do (jQuery 1.6 onwards):
$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);
to remove you can also use:
$('#idCheckbox').removeProp('checked');
with jQuery < 1.6 you must do
$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');
Center icon in a div - horizontally and vertically
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
JSFiddle
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
How can I return pivot table output in MySQL?
select t3.name, sum(t3.prod_A) as Prod_A, sum(t3.prod_B) as Prod_B, sum(t3.prod_C) as Prod_C, sum(t3.prod_D) as Prod_D, sum(t3.prod_E) as Prod_E
from
(select t2.name as name,
case when t2.prodid = 1 then t2.counts
else 0 end prod_A,
case when t2.prodid = 2 then t2.counts
else 0 end prod_B,
case when t2.prodid = 3 then t2.counts
else 0 end prod_C,
case when t2.prodid = 4 then t2.counts
else 0 end prod_D,
case when t2.prodid = "5" then t2.counts
else 0 end prod_E
from
(SELECT partners.name as name, sales.products_id as prodid, count(products.name) as counts
FROM test.sales left outer join test.partners on sales.partners_id = partners.id
left outer join test.products on sales.products_id = products.id
where sales.partners_id = partners.id and sales.products_id = products.id group by partners.name, prodid) t2) t3
group by t3.name ;
error: ‘NULL’ was not declared in this scope
To complete the other answers: If you are using C++11, use nullptr
, which is a keyword that means a void pointer pointing to null. (instead of NULL
, which is not a pointer type)
Android, Java: HTTP POST Request
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair
.
An alternative is to use (Http)URLConnection
. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection
javadoc.
How can I add a Google search box to my website?
Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form.
When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query.
Therefor, renaming your field from "g" to "q" solved the problem.
Populating spinner directly in the layout xml
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
how to align text vertically center in android
Try to put android:gravity="center_vertical|right"
inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true"
inside your scrollView
.
Opacity of div's background without affecting contained element in IE 8?
What about this approach:
_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
div.gradient {_x000D_
color: #000000;_x000D_
width: 800px;_x000D_
height: 200px;_x000D_
}_x000D_
div.gradient:after {_x000D_
background: url(SOME_BACKGROUND);_x000D_
background-size: cover;_x000D_
content:'';_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0;_x000D_
width:inherit;_x000D_
height:inherit;_x000D_
opacity:0.1;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="gradient">Text</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_
Loop over html table and get checked checkboxes (JQuery)
Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"]
means that this will match each <input />
with type attribute type
equals to checkbox
After that: :checked
will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});
How to load html string in a webview?
read from assets html file
ViewGroup webGroup;
String content = readContent("content/ganji.html");
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
webGroup.addView(webView);
Add horizontal scrollbar to html table
First, make a display: block
of your table
then, set overflow-x:
to auto
.
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
Nice and clean. No superfluous formatting.
Here are more involved examples with scrolling table captions from a page on my website.
If an issue is taken about cells not filling the entire table, append the following additional CSS code:
table tbody {
display: table;
width: 100%;
}
How to refresh table contents in div using jquery/ajax
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
Update Code (if you don't want it auto-refresh)
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
Excel Formula to SUMIF date falls in particular month
Try this instead:
=SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))
It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.
Here's how the formula works.
- MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
{1, 1, 1, 2, 2}
.
- Then the comparison
{1, 1, 1, 2, 2}= 1
produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}
, which comprises the condition for the IF statement.
- The IF statement then returns an array of values, with
{430, 96, 400..
for the values of the sum ranges where the month value equals 1 and ..0,0}
where the month value does not equal 1.
- That array
{430, 96, 400, 0, 0}
is then summed to get the answer you are looking for.
This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.
It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)
--also works.
Heads up: This does not work in Google Spreadsheets
In JavaScript can I make a "click" event fire programmatically for a file input element?
You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
Big-O summary for Java Collections Framework implementations?
The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).
List implementations:
get add contains next remove(0) iterator.remove
ArrayList O(1) O(1) O(n) O(1) O(n) O(n)
LinkedList O(n) O(1) O(n) O(1) O(1) O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n) O(1) O(n) O(n)
Set implementations:
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table capacity
LinkedHashSet O(1) O(1) O(1)
CopyOnWriteArraySet O(n) O(n) O(1)
EnumSet O(1) O(1) O(1)
TreeSet O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table capacity
LinkedHashMap O(1) O(1) O(1)
IdentityHashMap O(1) O(1) O(h/n) h is the table capacity
EnumMap O(1) O(1) O(1)
TreeMap O(log n) O(log n) O(log n)
ConcurrentHashMap O(1) O(1) O(h/n) h is the table capacity
ConcurrentSkipListMap O(log n) O(log n) O(1)
Queue implementations:
offer peek poll size
PriorityQueue O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1) O(1) O(1) O(n)
ArrayBlockingQueue O(1) O(1) O(1) O(1)
LinkedBlockingQueue O(1) O(1) O(1) O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue O(log n) O(1) O(log n) O(1)
LinkedList O(1) O(1) O(1) O(1)
ArrayDeque O(1) O(1) O(1) O(1)
LinkedBlockingDeque O(1) O(1) O(1) O(1)
The bottom of the javadoc for the java.util package contains some good links:
Reading serial data in realtime in Python
From the manual:
Possible values for the parameter timeout:
…
x set timeout to x seconds
and
readlines(sizehint=None, eol='\n') Read a list of lines,
until timeout. sizehint is ignored and only present for API
compatibility with built-in File objects.
Note that this function only returns on a timeout.
So your readlines
will return at most every 2 seconds. Use read()
as Tim suggested.
How are Anonymous inner classes used in Java?
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Python ValueError: too many values to unpack
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
Regular expression - starting and ending with a letter, accepting only letters, numbers and _
Here's a solution using a negative lookahead (not supported in all regex engines):
^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$
Test that it works as expected:
import re
tests = [
('a', True),
('_', False),
('zz', True),
('a0', True),
('A_', False),
('a0_b', True),
('a__b', False),
('a_1_c', True),
]
regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
is_match = re.match(regex, test[0]) is not None
if is_match != test[1]:
print "fail: " + test[0]
How to send image to PHP file using Ajax?
Jquery code which contains simple ajax :
$("#product").on("input", function(event) {
var data=$("#nameform").serialize();
$.post("./__partails/search-productbyCat.php",data,function(e){
$(".result").empty().append(e);
});
});
Html elements you can use any element:
<form id="nameform">
<input type="text" name="product" id="product">
</form>
php Code:
$pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
$Catagoryf=$_POST['product'];
$pricef=$_POST['price'];
$colorf=$_POST['color'];
$stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
$stmtcat->execute(array($Catagoryf));
while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
$iddb=$result['ID'];
$namedb=$result['Name'];
$pricedb=$result['Price'];
$colordb=$result['Color'];
echo "<tr>";
echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>';
echo "<td><pre>$pricedb</pre></td>";
echo "<td><pre> $colordb</pre>";
echo "</tr>";
The easy way
Multiple aggregate functions in HAVING clause
For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:
GROUP BY meetingID
HAVING COUNT(caseID) = 3
In your general case:
GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7
Or (possibly easier to read?),
GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6
Dependency Injection vs Factory Pattern
I believe DI is a type of abstraction layer on factories, but they also provide benefits beyond abstraction. A true factory knows how to instantiate a single type and configure it. A good DI layer provides the ability, through configuration, to instantiate and configure many types.
Obviously, for a project with a few simple types that requires relatively stable business logic in their construction, the factory pattern is simple to understand, implement, and works well.
OTOH, if you have a project containing numerous types whose implementations you expect to change often, DI gives you the flexibility through its configuration to do this at runtime without having to recompile your factories.
Create an array of integers property in Objective-C
C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:
Supported Types
You can declare a property for any
Objective-C class, Core Foundation
data type, or “plain old data” (POD)
type (see C++ Language Note: POD
Types). For constraints on using Core
Foundation types, however, see “Core
Foundation.”
POD does not include C arrays. See
http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html
If you need an array, you should use NSArray or NSData.
The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.
How to post data to specific URL using WebClient in C#
Here is the crisp answer:
public String sendSMS(String phone, String token) {
WebClient webClient = WebClient.create(smsServiceUrl);
SMSRequest smsRequest = new SMSRequest();
smsRequest.setMessage(token);
smsRequest.setPhoneNo(phone);
smsRequest.setTokenId(smsServiceTokenId);
Mono<String> response = webClient.post()
.uri(smsServiceEndpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(smsRequest), SMSRequest.class)
.retrieve().bodyToMono(String.class);
String deliveryResponse = response.block();
if (deliveryResponse.equalsIgnoreCase("success")) {
return deliveryResponse;
}
return null;
}
Get integer value from string in swift
A more general solution could be a extension
extension String {
var toFloat:Float {
return Float(self.bridgeToObjectiveC().floatValue)
}
var toDouble:Double {
....
}
....
}
this for example extends the swift native String object by toFloat
How to link an image and target a new window
If you use script to navigate to the page, use the open
method with the target _blank
to open a new window / tab:
<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />
However, if you want search engines to find the page, you should just wrap the image in a regular link instead.
Setting up FTP on Amazon Cloud Server
Don't forget to update your iptables firewall if you have one to allow the 20-21 and 1024-1048 ranges in.
Do this from /etc/sysconfig/iptables
Adding lines like this:
-A INPUT -m state --state NEW -m tcp -p tcp --dport 20:21 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 1024:1048 -j ACCEPT
And restart iptables with the command:
sudo service iptables restart
How do I login and authenticate to Postgresql after a fresh install?
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
Difference between .dll and .exe?
Dll v/s Exe
1)DLL file is a dynamic link library which can be used in exe files and
other dll files.
EXE file is a executable file which runs in a separate
process which is managed by OS.
2)DLLs are not directly executable . They are separate files containing functions that can be called by programs and other DLLs to perform computations and functions.
An EXE is a program that can be executed . Ex :Windows program
3)Reusability
DLL: They can be reused for some other application. As long as the coder knows the names and parameters of the functions and procedures in the DLL file .
EXE: Only for specific purpose .
4)A DLL would share the same process and memory space of the calling application while an
EXE creates its separate process and memory space.
5)Uses
DLL: You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
EXE: When we work with project templates like Windows Forms Applications, Console Applications, WPF Applications and Windows Services they generate an exe assembly when compiled.
6)Similarities :
Both DLL and EXE are binary files have a complex nested structure defined by the Portable Executable format, and they are not intended to be editable by users.
Maven home (M2_HOME) not being picked up by IntelliJ IDEA
In case you don't want to use the M2_HOME and want to direct the IntelliJ to the maven installation you can simply set it by:
- goto File => Setting => Maven => Maven home directory
- point to your maven build directory e.g. /usr/local/maven/apache-maven-3.0.4
A better way is to have a symlink e.g. 'latest' for the latest version and point your IntelliJ to use that for consistency, given latest points to the latest version of maven installed on your box.
MySQL: Set user variable from result of query
Use this way so that result will not be displayed while running stored procedure.
The query:
SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;
The requested resource does not support HTTP method 'GET'
Please use the attributes from the System.Web.Http namespace on your WebAPI actions:
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public string Auth(string username, string password)
{...}
The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc
. The classes in the System.Web.Http
namespace are for WebAPI.
Turn off constraints temporarily (MS SQL)
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
Spring MVC: How to return image in @ResponseBody?
if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping
annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc
).
@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
return IOUtils.toByteArray(in);
}
"CASE" statement within "WHERE" clause in SQL Server 2008
select
d.DISTNAME,e.BLKNAME,a.childid,a.studyingclass
from Tbl_AdmissionRegister a
inner join District_master b on a.Schooid=b.Schooid
where
case when len('3601')=4 then c.distcd
when len('3601')=6 then c.blkcd
when len('3601')=11 then c.schcd end = '3601'
Label word wrapping
Change your maximum size,
label1.MaximumSize = new Size(100, 0);
And set your autosize to true.
label1.AutoSize = true;
That's it!
How to check if an user is logged in Symfony2 inside a controller?
To add to answer given by Anil, In symfony3, you can use $this->getUser()
to determine if the user is logged in, a simple condition like if(!$this->getUser()) {}
will do.
If you look at the source code which is available in base controller, it does the exact same thing defined by Anil.
What should I set JAVA_HOME environment variable on macOS X 10.6?
It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:
$ echo $SHELL
/bin/bash
If your default terminal is /bin/bash (Bash), then you should use @hygull method
If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:
export JAVA_HOME="$(/usr/libexec/java_home)"
Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.
This method tested working in macOS Mojave Version 10.14.6.
How to create a stopwatch using JavaScript?
Solution by Mosh Hamedani
Creating a StopWatch function constructor.
Define 4 local variables
- startTime
- endTime
- isRunning
- duration set to 0
Next create 3 methods
- start
- stop
- reset
start method
- check if isRunning is true if so throw an error that start cannot be called twice.
- set isRunning to true
- assign the current Date object to startTime.
stop method
- check if isRunning is false if so throw an error that stop cannot be called twice.
- set isRunning to false
- assign the current Date object to endTime.
- calculate the seconds by endTime and startTime Date object
- increment duration with seconds
reset method:
- reset all the local variables.
Read-only property
if you want to access the duration local variable you need to define a property using Object.defineProperty.
It's useful when you want to create a read-only property.
Object.defineProperty takes 3 parameters
- the object which to define a property (in this case the current object (this))
- the name of the property
the value of the key property.
We want to create a Read-only property so we pass an object as a value.
The object contain a get method that return the duration local variable.
in this way we cannot change the property only get it.
The trick is to use Date() object to calculate the time.
Reference the code below
function StopWatch() {
let startTime,
endTime,
isRunning,
duration = 0;
this.start = function () {
if (isRunning) throw new Error("StopWatch has already been started.");
isRunning = true;
startTime = new Date();
};
this.stop = function () {
if (!isRunning) throw new Error("StopWatch has already been stop.");
isRunning = false;
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
};
this.reset = function () {
duration = 0;
startTime = null;
endTime = null;
isRunning = false;
};
Object.defineProperty(this, "duration", {
get: function () {
return duration;
},
});
}
const sw = new StopWatch();
How do I draw a grid onto a plot in Python?
Using rcParams you can show grid very easily as follows
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"
If grid is not showing even after changing these parameters then use
plt.grid(True)
before calling
plt.show()
What are .NET Assemblies?
See this:
In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security
How to get query string parameter from MVC Razor markup?
It was suggested to post this as an answer, because some other answers are giving errors like 'The name Context does not exist in the current context'.
Just using the following works:
Request.Query["queryparm1"]
Sample usage:
<a href="@Url.Action("Query",new {parm1=Request.Query["queryparm1"]})">GO</a>
How can I include null values in a MIN or MAX?
The effect you want is to treat the NULL as the largest possible date then replace it with NULL again upon completion:
SELECT RecordId, MIN(StartDate), NULLIF(MAX(COALESCE(EndDate,'9999-12-31')),'9999-12-31')
FROM tmp GROUP BY RecordId
Per your fiddle this will return the exact results you specify under all conditions.
Pylint, PyChecker or PyFlakes?
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).
Strong points of PyLint
:
- Very descriptive and accurate report.
- Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
- The fully corrected code run faster (no class, no reference binding...).
- Made by a French team. OK, it's not a plus for everybody, but I like it ;-)
Cons of Pylint:
- Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
- Very very talkative. Be ready to use your eyes.
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
Populating a razor dropdownlist from a List<object> in MVC
I'm going to approach this as if you have a Users model:
Users.cs
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual DbUserRoles DbUserRoles { get; set; }
}
and a DbUserRoles model that represented a table by that name in the database:
DbUserRoles.cs
public partial class DbUserRoles
{
[Key]
public int UserRoleId { get; set; }
[Required]
[StringLength(30)]
public string UserRole { get; set; }
}
Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:
var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;
and have these supporting functions:
private static SelectListItem[] _UserRolesList;
/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
if (_UserRolesList == null)
{
var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
{
Text = a.UserRole,
Value = a.UserRoleId.ToString()
}).ToList();
userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
_UserRolesList = userRoles.ToArray();
}
// Have to create new instances via projection
// to avoid ModelBinding updates to affect this
// globally
return _UserRolesList
.Select(d => new SelectListItem()
{
Value = d.Value,
Text = d.Text
})
.ToArray();
}
Repository.cs
My Repository function GetAllUserRoles()
for the function, above:
public class Repository
{
Model1 db = new Model1(); // Entity Framework context
// User Roles
public IList<DbUserRoles> GetAllUserRoles()
{
return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
}
}
AddNewUser.cshtml
Then do this in your View:
<table>
<tr>
<td>
@Html.EditorFor(model => model.UserName,
htmlAttributes: new { @class = "form-control" }
)
</td>
<td>
@Html.DropDownListFor(model => model.RoleId,
new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
htmlAttributes: new { @class = "form-control" }
)
</td>
</tr>
</table>
adb command not found
if youd dont have adb in folder android-sdk-macosx/platform-tools/
you should install platform tools first. Run android-sdk-macosx/tools/android
and Install platform tools from Android SDK manager.
How to use FormData in react-native?
Here is my simple code FormData with react-native to post request with string and image.
I have used react-native-image-picker to capture/select photo
react-native-image-picker
let photo = { uri: source.uri}
let formdata = new FormData();
formdata.append("product[name]", 'test')
formdata.append("product[price]", 10)
formdata.append("product[category_ids][]", 2)
formdata.append("product[description]", '12dsadadsa')
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
NOTE you can change image/jpeg
to other content type. You can get content type from image picker response.
fetch('http://192.168.1.101:3000/products',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
console.log("image uploaded")
}).catch(err => {
console.log(err)
})
});
How to export DataTable to Excel
You can use EasyXLS that is a library for exporting Excel files.
Check this code:
DataSet ds = new DataSet();
ds.Tables.Add(dataTable);
ExcelDocument xls = new ExcelDocument();
xls.easy_WriteXLSFile_FromDataSet("datatable.xls", ds,
new ExcelAutoFormat(Styles.AUTOFORMAT_EASYXLS1), "DataTable");
See also this sample about how to export datatable to excel in C#.
How do I release memory used by a pandas dataframe?
It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659
The monkey patch detailed on this issue has resolved the problem for me:
# monkeypatches.py
# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
libc.malloc_trim(0)
except (OSError, AttributeError):
libc = None
__old_del = getattr(pd.DataFrame, '__del__', None)
def __new_del(self):
if __old_del:
__old_del(self)
libc.malloc_trim(0)
if libc:
print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
pd.DataFrame.__del__ = __new_del
else:
print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)
Trying to read cell 1,1 in spreadsheet using Google Script API
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is
Spreadsheet --> Sheet --> Range --> Cell.
Github Push Error: RPC failed; result=22, HTTP code = 413
Do you use https links instead of ssh links? Because the https link is limited by the size of the upload of HttpServer (such as Apache, Ngnix), there is no such restriction when using ssh.
Use the following method to switch to the ssh link.
- Open terminal.
- Switch to your project's working directory.
- Get the name of the remote repository
$ git remote -v
origin https://github.com/[user_name]/[project_name].git (fetch)
origin https://github.com/[user_name]/[project_name].git (push)
- Modify the git address to ssh link.
git remote set-url origin [email protected]:[user_name]/[project_name].git
If you determine the remote repository name, proceed directly to step 4.
Now, you can do the push operation happily.
How to iterate over a TreeMap?
Just to point out the generic way to iterate over any map:
private <K, V> void iterateOverMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
}
TokenMismatchException in VerifyCsrfToken.php Line 67
Please follow a very simple step. You just have to comment the following line of in the app\http\kernel.php
and not app\kernel.php
file:
\App\Http\Middleware\VerifyCsrfToken::class,
I hope, it will solve your problem, and let me know if its not working.
MySQL timezone change?
This works fine
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
$con->query("SET time_zone = '+05:30'");
$con->query("SET @@session.time_zone = '+05:30'");
?>
What does java.lang.Thread.interrupt() do?
Thread.interrupt()
sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait()
may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException
)
Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.
Polling occurs via the Thread.interrupted()
method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.
EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.
Object.wait()
, Thread.sleep()
, and Thread.join()
- Most
java.util.concurrent
structures
- Java NIO (but not java.io) and it does NOT use
InterruptedException
, instead using ClosedByInterruptException
.
EDIT (from @thomas-pornin's answer to exactly same question for completeness)
Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop()
that is more like shooting the thread with an assault rifle.
How to change bower's default components folder?
Hi i am same problem and resolve this ways.
windows user and vs cant'create .bowerrc file.
in cmd go any folder
install any packages which is contains .bowerrc file forexample
bower install angular-local-storage
this plugin contains .bowerrc file. copy that and go to your project and paste this file.
and in visual studio - solution explorer - show all files and include project
seen .bowerrc file
i resolve this ways :)
rebase in progress. Cannot commit. How to proceed or stop (abort)?
You told your repository to rebase. It looks like you were on a commit (identified by SHA 9c168a5) and then did git rebase master
or git pull --rebase master
.
You are rebasing the branch master onto that commit. You can end the rebase via git rebase --abort
. This would put back at the state that you were at before you started rebasing.
how to query child objects in mongodb
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
CSS: auto height on containing div, 100% height on background div inside containing div
Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.
Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)
#container {
height:500px;
min-height:500px;
}
Table-level backup
Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.
EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg
How to line-break from css, without using <br />?
In case this helps someone...
You could do this:
<p>This is an <a class="on-new-line">inline link</a>?</p>
With this css:
a.on-new-line:before {
content: ' ';
font-size:0;
display:block;
line-height:0;
}
How do I run a program with a different working directory from current, from Linux shell?
Call the program like this:
(cd /c; /a/helloworld)
The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c
, then executes helloworld
from /a
. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.
Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled /c
, make the execution of helloworld
conditional:
(cd /c && /a/helloworld)
Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld
via exec:
(cd /c && exec /a/helloworld)
[Thanks to Josh and Juliano for giving tips on improving this answer!]
How do I check if file exists in Makefile so I can delete it?
The second top answer mentions ifeq
, however, it fails to mention that these must be on the same level as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:
download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
# THIS DOES NOT WORK!
download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
Using GitLab token to clone without authentication
Inside a GitLab CI pipeline the CI_JOB_TOKEN
environment variable works for me:
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/...
Source: Gitlab Docs
BTW, setting this variable in .gitlab-ci.yml
helps to debug errors.
variables:
CI_DEBUG_TRACE: "true"
In Python, is there an elegant way to print a list in a custom format without explicit looping?
from time import clock
from random import sample
n = 500
myList = sample(xrange(10000),n)
#print myList
A,B,C,D = [],[],[],[]
for i in xrange(100):
t0 = clock()
ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
A.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
B.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
C.append(clock()-t0)
t0 = clock()
ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
D.append(clock()-t0)
print '\n'.join(('t1 = '+str(min(A))+' '+'{:.1%}.'.format(min(A)/min(D)),
't2 = '+str(min(B))+' '+'{:.1%}.'.format(min(B)/min(D)),
't3 = '+str(min(C))+' '+'{:.1%}.'.format(min(C)/min(D)),
't4 = '+str(min(D))+' '+'{:.1%}.'.format(min(D)/min(D))))
For n=500:
150.8%.
142.7%.
110.8%.
100.0%.
For n=5000:
153.5%.
176.2%.
109.7%.
100.0%.
Oh, I see now: only the solution 3 with map() fits with the title of the question.
Make a UIButton programmatically in Swift
For Swift 3 Xcode 8.......
let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
button.addTarget(self, action: #selector(self.barItemTapped), for: .touchUpInside)
func barItemTapped(sender : UIButton) {
//Write button action here
}
Angular 2 Unit Tests: Cannot find name 'describe'
Solution to this problem is connected with what @Pace has written in his answer. However, it doesn't explain everything so, if you don't mind, I'll write it by myself.
SOLUTION:
Adding this line:
///<reference path="./../../../typings/globals/jasmine/index.d.ts"/>
at the beginning of hero.spec.ts
file fixes problem. Path leads to typings
folder (where all typings are stored).
To install typings you need to create typings.json
file in root of your project with following content:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160807145350"
}
}
And run typings install
(where typings
is NPM package).
How to encode text to base64 in python
It looks it's essential to call decode() function to make use of actual string data even after calling base64.b64decode over base64 encoded string. Because never forget it always return bytes literals.
import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes) # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str) # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str)) # b'your string'
print(base64.b64decode(encoded_str).decode()) # your string
Add/Delete table rows dynamically using JavaScript
If you put a delete button on each row, then:
<tr>
<td><input type="button" value="Delete row" onclick="deleteRow(this);">
<td><input type="text">
<td><input type="text">
And the deleteRow function can be:
function deleteRow(el) {
// while there are parents, keep going until reach TR
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
// If el has a parentNode it must be a TR, so delete it
// Don't delte if only 3 rows left in table
if (el.parentNode && el.parentNode.rows.length > 3) {
el.parentNode.removeChild(el);
}
}
If all your rows have the same content, it will be much faster to add a row by cloning an existing row:
function addRow(tableID) {
var table = document.getElementById(tableID);
if (!table) return;
var newRow = table.rows[1].cloneNode(true);
// Now get the inputs and modify their names
var inputs = newRow.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
// Update inputs[i]
}
// Add the new row to the tBody (required for IE)
var tBody = table.tBodies[0];
tBody.insertBefore(newRow, tBody.lastChild);
}
MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?
To remove all the documents in all the collections:
db.getCollectionNames().forEach( function(collection_name) {
if (collection_name.indexOf("system.") == -1) {
print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
db[collection_name].remove({});
}
});
How do I display a wordpress page content?
@Sydney Try putting wp_reset_query() before you call the loop.
This will display the content of your page.
<?php
wp_reset_query(); // necessary to reset query
while ( have_posts() ) : the_post();
the_content();
endwhile; // End of the loop.
?>
EDIT: Try this if you have some other loops that you previously ran.
Place wp_reset_query(); where you find it most suitable, but before you call this loop.
Send SMTP email using System.Net.Mail via Exchange Online (Office 365)
Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.
My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as [email protected].
Another thing to try is in the authentication, fill in the third field with the domain, like
Dim smtpAuth = New System.Net.NetworkCredential(
"TheDude", "hunter2password", "MicrosoftOffice365Domain.com")
If that doesn't work, double check that you can log into the account at: https://portal.microsoftonline.com
Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).
One last thing to note, the Send method is Asynchronous. If you call
Dispose
immediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.
Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="System.Net" />
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net" />
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose" />
<add name="System.Net.Sockets" value="Verbose" />
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.log"
/>
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
</configuration>
How to uninstall a package installed with pip install --user
I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:
pip uninstall opencv-python # -- the original step. failed.
ImportError: DLL load failed: The specified module could not be found.
I did this into my python3.6 environment and got this error.
python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.
Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.
finally, this fixed it:
pip uninstall opencv-python
(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.
>>>import cv2
>>>
working!
Overwriting txt file in java
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the
first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field
of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How to dump a table to console?
You have to code it yourself I'm afraid. I wrote this, and it may be of some use to you
function printtable(table, indent)
indent = indent or 0;
local keys = {};
for k in pairs(table) do
keys[#keys+1] = k;
table.sort(keys, function(a, b)
local ta, tb = type(a), type(b);
if (ta ~= tb) then
return ta < tb;
else
return a < b;
end
end);
end
print(string.rep(' ', indent)..'{');
indent = indent + 1;
for k, v in pairs(table) do
local key = k;
if (type(key) == 'string') then
if not (string.match(key, '^[A-Za-z_][0-9A-Za-z_]*$')) then
key = "['"..key.."']";
end
elseif (type(key) == 'number') then
key = "["..key.."]";
end
if (type(v) == 'table') then
if (next(v)) then
printf("%s%s =", string.rep(' ', indent), tostring(key));
printtable(v, indent);
else
printf("%s%s = {},", string.rep(' ', indent), tostring(key));
end
elseif (type(v) == 'string') then
printf("%s%s = %s,", string.rep(' ', indent), tostring(key), "'"..v.."'");
else
printf("%s%s = %s,", string.rep(' ', indent), tostring(key), tostring(v));
end
end
indent = indent - 1;
print(string.rep(' ', indent)..'}');
end
Check OS version in Swift?
Mattt Thompson shares a very handy way
switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
case .OrderedAscending:
println("iOS < 8.0")
}
How to search a string in a single column (A) in excel using VBA
Below are two methods that are superior to looping. Both handle a "no-find" case.
- The VBA equivalent of a normal function
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)
VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
JTable How to refresh table model after insert delete or update the data.
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
javascript get child by id
document.getElementById('child')
should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
How to do left join in Doctrine?
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
How to convert from Hex to ASCII in JavaScript?
_x000D_
_x000D_
console.log(_x000D_
_x000D_
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")_x000D_
_x000D_
)
_x000D_
_x000D_
_x000D_
macro - open all files in a folder
You can use Len(StrFile) > 0
in loop check statement !
Sub openMyfile()
Dim Source As String
Dim StrFile As String
'do not forget last backslash in source directory.
Source = "E:\Planning\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub
INNER JOIN same table
Perhaps this should be the select (if I understand the question correctly)
select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before
Package structure for a Java project?
There are a few existing resources you might check:
- Properly Package Your Java Classes
- Spring 2.5 Architecture
- Java Tutorial - Naming a Package
- SUN Naming Conventions
For what it's worth, my own personal guidelines that I tend to use are as follows:
- Start with reverse domain, e.g. "com.mycompany".
- Use product name, e.g. "myproduct". In some cases I tend to have common packages that do not belong to a particular product. These would end up categorized according to the functionality of these common classes, e.g. "io", "util", "ui", etc.
- After this it becomes more free-form. Usually I group according to project, area of functionality, deployment, etc. For example I might have "project1", "project2", "ui", "client", etc.
A couple of other points:
- It's quite common in projects I've worked on for package names to flow from the design documentation. Usually products are separated into areas of functionality or purpose already.
- Don't stress too much about pushing common functionality into higher packages right away. Wait for there to be a need across projects, products, etc., and then refactor.
- Watch inter-package dependencies. They're not all bad, but it can signify tight coupling between what might be separate units. There are tools that can help you keep track of this.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Validating a Textbox field for only numeric input.
if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
{
lblMessage.Text = string.Empty;
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Maroon;
lblMessage.Text = "You have not entered a number";
return;
}
How do I get to IIS Manager?
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit:
You should have something like this:
git rebase merge conflict
If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".
First, checkout temp branch and start standard merge
git checkout -b temp
git merge origin/master
You will have to resolve conflicts, but only once and only real ones.
Then stage all files and finish merge.
git commit -m "Merge branch 'origin/master' into 'temp'"
Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.
git checkout alpha
git rebase origin/master -X theirs
Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.
git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
And delete temporary branch
git branch -D temp
That's all. We did a rebase via hidden merge.
Also I wrote a script, so that can be done in a dialog manner, you can find it here.
Is there a way to do repetitive tasks at intervals?
If you want to stop it in any moment ticker
ticker := time.NewTicker(500 * time.Millisecond)
go func() {
for range ticker.C {
fmt.Println("Tick")
}
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
If you do not want to stop it tick:
tick := time.Tick(500 * time.Millisecond)
for range tick {
fmt.Println("Tick")
}
Pass in an enum as a method parameter
First change the method parameter Enum supportedPermissions
to SupportedPermissions supportedPermissions
.
Then create your file like this
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
And the call to your method should be
CreateFile(id, name, description, SupportedPermissions.basic);
PHP split alternative?
preg_split
if you need to split by regular expressions.
str_split
if you need to split by characters.
explode
if you need to split by something simple.
Also for the future, if you ever want to know what PHP wants you to use if something is deprecated you can always check out the function in the manual and it will tell you alternatives.
golang why don't we have a set datastructure
Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...
The other reason is, that it's not clear at all what the "right" implementation of a set is:
There is a functional approach:
func IsInEvenNumbers(n int) bool {
if n % 2 == 0 {
return true
}
return false
}
This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.
- Or you do a has-like approach like Dali showed.
A map does not have that problem, since you store something associated with the value.
Groovy write to file (newline)
As @Steven points out, a better way would be:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
As this handles the line separator for you, and handles closing the writer as well
(and doesn't open and close the file each time you write a line, which could be slow in your original version)
React js onClick can't pass value to method
There are nice answers here, and i agree with @Austin Greco (the second option with separate components)
There is another way i like, currying.
What you can do is create a function that accept a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). then you are free to do with it what ever you want.
ES5:
handleChange(param) { // param is the argument you passed to the function
return function (e) { // e is the event object that returned
};
}
ES6:
handleChange = param => e => {
// param is the argument you passed to the function
// e is the event object that returned
};
And you will use it this way:
<input
type="text"
onChange={this.handleChange(someParam)}
/>
Here is a full example of such usage:
_x000D_
_x000D_
const someArr = ["A", "B", "C", "D"];_x000D_
_x000D_
class App extends React.Component {_x000D_
state = {_x000D_
valueA: "",_x000D_
valueB: "some initial value",_x000D_
valueC: "",_x000D_
valueD: "blah blah"_x000D_
};_x000D_
_x000D_
handleChange = param => e => {_x000D_
const nextValue = e.target.value;_x000D_
this.setState({ ["value" + param]: nextValue });_x000D_
};_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
{someArr.map(obj => {_x000D_
return (_x000D_
<div>_x000D_
<label>_x000D_
{`input ${obj} `}_x000D_
</label>_x000D_
<input_x000D_
type="text"_x000D_
value={this.state["value" + obj]}_x000D_
onChange={this.handleChange(obj)}_x000D_
/>_x000D_
<br />_x000D_
<br />_x000D_
</div>_x000D_
);_x000D_
})}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_
Note that this approach doesn't solve the creation of a new instance on each render.
I like this approach over the other inline handlers as this one is more concise and readable in my opinion.
Edit:
As suggested in the comments below, you can cache / memoize the result of the function.
Here is a naive implementation:
_x000D_
_x000D_
let memo = {};_x000D_
_x000D_
const someArr = ["A", "B", "C", "D"];_x000D_
_x000D_
class App extends React.Component {_x000D_
state = {_x000D_
valueA: "",_x000D_
valueB: "some initial value",_x000D_
valueC: "",_x000D_
valueD: "blah blah"_x000D_
};_x000D_
_x000D_
handleChange = param => {_x000D_
const handler = e => {_x000D_
const nextValue = e.target.value;_x000D_
this.setState({ ["value" + param]: nextValue });_x000D_
}_x000D_
if (!memo[param]) {_x000D_
memo[param] = e => handler(e)_x000D_
}_x000D_
return memo[param]_x000D_
};_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
{someArr.map(obj => {_x000D_
return (_x000D_
<div key={obj}>_x000D_
<label>_x000D_
{`input ${obj} `}_x000D_
</label>_x000D_
<input_x000D_
type="text"_x000D_
value={this.state["value" + obj]}_x000D_
onChange={this.handleChange(obj)}_x000D_
/>_x000D_
<br />_x000D_
<br />_x000D_
</div>_x000D_
);_x000D_
})}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root" />
_x000D_
_x000D_
_x000D_
git - remote add origin vs remote set-url origin
if you have existing project and you would like to add remote repository url then you need to do following command
git init
if you would like to add readme.md file then you can create it and add it using below command.
git add README.md
make your first commit using below command
git commit -m "first commit"
Now you completed all local repository process, now how you add remote repository url ? check below command this is for ssh url, you can change it for https.
git remote add origin [email protected]:user-name/repository-name.git
How you push your first commit see below command :
git push -u origin master
Why use getters and setters/accessors?
It can be useful for lazy-loading. Say the object in question is stored in a database, and you don't want to go get it unless you need it. If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.
I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages. Web services, for all of the benefits, pioneer new definitions of "slow", so you don't want to make a web service call if you don't have to.
I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service. So with a little wrapping, a lot of web service calls were prevented.
So the getter saves me from trying to figure out, on each child page, what I will need. If I need it, I call the getter, and it goes to find it for me if I don't already have it.
protected YourType _yourName = null;
public YourType YourName{
get
{
if (_yourName == null)
{
_yourName = new YourType();
return _yourName;
}
}
}
JQuery get all elements by class name
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
Callback when DOM is loaded in react.js
I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.
eg:
componentDidUpdate: function() {
$(".tbl-tr").height($(".tbl-tr ").height());
}
Tell Ruby Program to Wait some amount of time
I find until
very useful with sleep. example:
> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully
Error: stray '\240' in program
Your Program has invalid/invisible characters in it. You most likely would have picked up these invisible characters when you copy and past code from another website or sometimes a document. Copying the code from the site into another text document and then copying and pasting into your code editor may work, but depending on how long your code is you should just go with typing it out word for word.
Getting GET "?" variable in laravel
In laravel 5.3 $start = Input::get('start');
returns NULL
To solve this
use Illuminate\Support\Facades\Input;
//then inside you controller function use
$input = Input::all(); // $input will have all your variables,
$start = $input['start'];
$limit = $input['limit'];
Abstract methods in Java
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
Get File Path (ends with folder)
Use the Application.FileDialog
object
Sub SelectFolder()
Dim diaFolder As FileDialog
Dim selected As Boolean
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
selected = diaFolder.Show
If selected Then
MsgBox diaFolder.SelectedItems(1)
End If
Set diaFolder = Nothing
End Sub
Postgres FOR LOOP
Below is example you can use:
create temp table test2 (
id1 numeric,
id2 numeric,
id3 numeric,
id4 numeric,
id5 numeric,
id6 numeric,
id7 numeric,
id8 numeric,
id9 numeric,
id10 numeric)
with (oids = false);
do
$do$
declare
i int;
begin
for i in 1..100000
loop
insert into test2 values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;
How to change the default docker registry from docker.io to my private registry?
Earlier this could be achieved using DOCKER_OPTS
in the /etc/default/docker
config file which worked on Ubuntu 14:04 and had some issues on Ubuntu 15:04. Not sure if this has been fixed.
The below line needs to go into the file /etc/default/docker
on the host which runs the docker daemon. The change points to the private registry is installed in your local network. Note: you would require to restart the docker service followed with this change.
DOCKER_OPTS="--insecure-registry <priv registry hostname/ip>:<port>"
Get first line of a shell command's output
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
Subset dataframe by multiple logical conditions of rows to remove
This answer is more meant to explain why, not how. The '=='
operator in R is vectorized in a same way as the '+'
operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:
> 1:3 == 1:3
[1] TRUE TRUE TRUE
Here the first test is 1==1
which is TRUE, the second 2==2
and the third 3==3
. Notice that this returns a FALSE in the first and second element because the order is wrong:
> 3:1 == 1:3
[1] FALSE TRUE FALSE
Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:
> 1:2 == 1:3
[1] TRUE TRUE FALSE
Warning message:
In 1:2 == 1:3 :
longer object length is not a multiple of shorter object length
Here the first match is 1==1
, then 2==2
, and finally 1==3
(FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:
> 1:3 == 1
[1] TRUE FALSE FALSE
The correct operator to test if an element is in a vector is indeed '%in%'
which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).
Alternatively, you can use '&'
to combine two logical statements. '&'
takes two elements and checks elementwise if both are TRUE:
> 1:3 == 1 & 1:3 != 2
[1] TRUE FALSE FALSE
What is the difference between dynamic and static polymorphism in Java?
Binding refers to the link between method call and method definition.
This picture clearly shows what is binding.
In this picture, “a1.methodOne()” call is binding to corresponding methodOne() definition and “a1.methodTwo()” call is binding to corresponding methodTwo() definition.
For every method call there should be proper method definition. This is a rule in java. If compiler does not see the proper method definition for every method call, it throws error.
Now, come to static binding and dynamic binding in java.
Static Binding In Java :
Static binding is a binding which happens during compilation. It is
also called early binding because binding happens before a program
actually runs
.
Static binding can be demonstrated like in the below picture.
In this picture, ‘a1’ is a reference variable of type Class A pointing to object of class A. ‘a2’ is also reference variable of type class A but pointing to object of Class B.
During compilation, while binding, compiler does not check the type of object to which a particular reference variable is pointing. It just checks the type of reference variable through which a method is called and checks whether there exist a method definition for it in that type.
For example, for “a1.method()” method call in the above picture, compiler checks whether there exist method definition for method() in Class A. Because ‘a1' is Class A type. Similarly, for “a2.method()” method call, it checks whether there exist method definition for method() in Class A. Because ‘a2' is also Class A type. It does not check to which object, ‘a1’ and ‘a2’ are pointing. This type of binding is called static binding.
Dynamic Binding In Java :
Dynamic binding is a binding which happens during run time. It is also
called late binding because binding happens when program actually is
running.
During run time actual objects are used for binding. For example, for “a1.method()” call in the above picture, method() of actual object to which ‘a1’ is pointing will be called. For “a2.method()” call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is called dynamic binding.
The dynamic binding of above example can be demonstrated like below.
Reference static-binding-and-dynamic-binding-in-java
Gradle build without tests
the different way to disable test tasks in the project is:
tasks.withType(Test) {enabled = false}
this behavior needed sometimes if you want to disable tests in one of a project(or the group of projects).
This way working for the all kind of test task, not just a java 'tests'. Also, this way is safe. Here's what I mean
let's say: you have a set of projects in different languages:
if we try to add this kind of record in main build.gradle
:
subprojects{
.......
tests.enabled=false
.......
}
we will fail in a project when if we have no task called tests
MYSQL query between two timestamps
Try the following:
SELECT * FROM eventList WHERE
date BETWEEN
STR_TO_DATE('2013/03/26', '%Y/%m/%d')
AND
STR_TO_DATE('2013/03/27', '%y/%m/%d')
Styling a input type=number
A little different to the other answers, using a similar concept but divs instead of pseudoclasses:
_x000D_
_x000D_
input {_x000D_
position: absolute;_x000D_
left: 10px;_x000D_
top: 10px;_x000D_
width: 50px;_x000D_
height: 20px;_x000D_
padding: 0px;_x000D_
font-size: 14pt;_x000D_
border: solid 0.5px #000;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.spinner-button {_x000D_
position: absolute;_x000D_
cursor: default;_x000D_
z-index: 2;_x000D_
background-color: #ccc;_x000D_
width: 14.5px;_x000D_
text-align: center;_x000D_
margin: 0px;_x000D_
pointer-events: none;_x000D_
height: 10px;_x000D_
line-height: 10px;_x000D_
}_x000D_
_x000D_
#inc-button {_x000D_
left: 46px;_x000D_
top: 10.5px;_x000D_
}_x000D_
_x000D_
#dec-button {_x000D_
left: 46px;_x000D_
top: 20.5px;_x000D_
}
_x000D_
<input type="number" value="0" min="0" max="100"/>_x000D_
<div id="inc-button" class="spinner-button">+</div>_x000D_
<div id="dec-button" class="spinner-button">-</div>
_x000D_
_x000D_
_x000D_
Regular expression for extracting tag attributes
Extract the element:
var buttonMatcherRegExp=/<a[\s\S]*?>[\s\S]*?<\/a>/;
htmlStr=string.match( buttonMatcherRegExp )[0]
Then use jQuery to parse and extract the bit you want:
$(htmlStr).attr('style')
Windows- Pyinstaller Error "failed to execute script " When App Clicked
Well I guess I have found the solution for my own question, here is how I did it:
Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.
So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.
The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!
Check if all elements in a list are identical
If you're interested in something a little more readable (but of course not as efficient,) you could try:
def compare_lists(list1, list2):
if len(list1) != len(list2): # Weed out unequal length lists.
return False
for item in list1:
if item not in list2:
return False
return True
a_list_1 = ['apple', 'orange', 'grape', 'pear']
a_list_2 = ['pear', 'orange', 'grape', 'apple']
b_list_1 = ['apple', 'orange', 'grape', 'pear']
b_list_2 = ['apple', 'orange', 'banana', 'pear']
c_list_1 = ['apple', 'orange', 'grape']
c_list_2 = ['grape', 'orange']
print compare_lists(a_list_1, a_list_2) # Returns True
print compare_lists(b_list_1, b_list_2) # Returns False
print compare_lists(c_list_1, c_list_2) # Returns False
IIS error, Unable to start debugging on the webserver
Just had the same issue after VS crashed and Rahul's comment regarding the application pool pointed me in the right direction. In my case recycling the app pool did the trick (IIS Manager => App Pools => right click on ap in question and recycle).
How to get the mouse position without events (without moving the mouse)?
You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.
For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...
How to set default values for Angular 2 component properties?
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
How do I do a multi-line string in node.js?
node v4 and current versions of node
As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'
.
Note that the newline at the end of the first line is included in the resulting string.
Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format
or other templaters, as in:
let num=10;
console.log(`the result of ${num} plus ${num} is ${num + num}.`);
which will print "the result of 10 plus 10 is 20." to the console.
Older versions of node
Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:
'this is a \
single string'
which evaluates to: 'this is a single string'
.
Note that the newline at the end of the first line is not included in the resulting string.
Reshape an array in NumPy
There are two possible result rearrangements (following example by @eumiro). Einops
package provides a powerful notation to describe such operations non-ambigously
>> a = np.arange(18).reshape(9,2)
# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)
array([[[ 0, 6, 12],
[ 2, 8, 14],
[ 4, 10, 16]],
[[ 1, 7, 13],
[ 3, 9, 15],
[ 5, 11, 17]]])
# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)
array([[[ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16]],
[[ 1, 3, 5],
[ 7, 9, 11],
[13, 15, 17]]])
c++ Read from .csv file
That because your csv file is in invalid format,
maybe the line break in your text file is not the \n or \r
and,
using c/c++ to parse text is not a good idea.
try awk:
$awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
ID=0 Name=Filipe Age=19 Gender=M
ID=1 Name=Maria Age=20 Gender=F
ID=2 Name=Walter Age=60 Gender=M
Dynamically generating a QR code with PHP
I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.
I did a little comand-line research and found out that linux has a command line tool qrencode
for generating qr-codes.
I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.
$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));
$imgData = "data:image/png;base64,".base64_encode($img);
Then in the html I load the image:
<img class="emrQRCode" src="<?=$imgData ?>" />
You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.