What is "stdafx.h" used for in Visual Studio?
It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.
If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.
Declaring functions in JSP?
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Most efficient way to check if a file is empty in Java on Windows
Try FileReader
, this reader is meant to read stream of character, while FileInputStream
is meant to read raw data.
From the Javadoc:
FileReader is meant for reading streams of characters. For reading
streams of raw bytes, consider using a FileInputStream.
Since you wanna read a log file, FileReader
is the class to use IMO.
Reading from stdin
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
Changing git commit message after push (given that no one pulled from remote)
This works for me pretty fine,
git checkout origin/branchname
if you're already in branch then it's better to do pull or rebase
git pull
or
git -c core.quotepath=false fetch origin --progress --prune
Later you can simply use
git commit --amend -m "Your message here"
or if you like to open text-editor then use
git commit --amend
I will prefer using text-editor if you have many comments. You can set your preferred text-editor with command
git config --global core.editor your_preffered_editor_here
Anyway, when your are done changing the commit message, save it and exit
and then run
git push --force
And you're done
How to build splash screen in windows forms application?
The other answers here cover this well, but it is worth knowing that there is built in functionality for splash screens in Visual Studio: If you open the project properties for the windows form app and look at the Application tab, there is a "Splash screen:" option at the bottom. You simply pick which form in your app you want to display as the splash screen and it will take care of showing it when the app starts and hiding it once your main form is displayed.
You still need to set up your form as described above (with the correct borders, positioning, sizing etc.)
How to access your website through LAN in ASP.NET
I'm not sure how stuck you are:
You must have a web server (Windows comes with one called IIS, but it may not be installed)
- Make sure you actually have IIS
installed! Try typing
http://localhost/
in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
- Set up IIS How to set up your first IIS Web site
- You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)
Installing your application
Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\
. Read Installing ASP.NET Applications (IIS 6.0) for more information
Accessing the web site from another machine
In theory, once you have a web server running, and the application installed, you only need the IP address
of your web server to access the application.
To find your IP address try:
Start
-> Run
-> type cmd
(hit ENTER
) -> type ipconfig
(hit ENTER
)
Once
- you have the IP address AND
- IIS running AND
- the application is installed
you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.
If you put your application in a directory called NewApp
, you will need to type something like http://your_ip_address/NewApp/default.aspx
Turn off your firewall
If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.
how to get a list of dates between two dates in java
Like as @folone, but correct
private static List<Date> getDatesBetween(final Date date1, final Date date2) {
List<Date> dates = new ArrayList<>();
Calendar c1 = new GregorianCalendar();
c1.setTime(date1);
Calendar c2 = new GregorianCalendar();
c2.setTime(date2);
int a = c1.get(Calendar.DATE);
int b = c2.get(Calendar.DATE);
while ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) || (c1.get(Calendar.DATE) != c2.get(Calendar.DATE))) {
c1.add(Calendar.DATE, 1);
dates.add(new Date(c1.getTimeInMillis()));
}
return dates;
}
jQuery get input value after keypress
I was looking for a ES6 example (so it could pass my linter)
So for other people who are looking for the same:
$('#dSuggest').keyup((e) => {
console.log(e.currentTarget.value);
});
I would also use keyup because you get the current value that is filled in.
webpack command not working
Actually, I have got this error a while ago. There are two ways to make this to work, as per my knowledge.
- Server wont update the changes made in the index.js because of some webpack bugs. So, restart your server.
- Updating your node.js will be helpful to avoid such problems.
Angularjs $http.get().then and binding to a list
Try using the success()
call back
$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
$scope.Documents = result;
});
But now since Documents
is an array and not a promise, remove the ()
<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
<input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
</span>
<span>{{document.Name}}</span>
</li>
Java ArrayList Index
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
base64 encode in MySQL
For those interested, these are the only alternatives so far:
1) Using these Functions:
http://wi-fizzle.com/downloads/base64.sql
2) If you already have the sys_eval UDF, (Linux) you can do this:
sys_eval(CONCAT("echo '",myField,"' | base64"));
The first method is known to be slow. The problem with the second one, is that the encoding is actually happening "outside" MySQL, which can have encoding problems (besides the security risks that you are adding with sys_* functions).
Unfortunately there is no UDF compiled version (which should be faster) nor a native support in MySQL (Posgresql supports it!).
It seems that the MySQL development team are not interested in implement it as this function already exists in other languages, which seems pretty silly to me.
How do I install PIL/Pillow for Python 3.6?
Pillow is released with installation wheels on Windows:
We provide Pillow binaries for Windows
compiled for the matrix of supported Pythons
in both 32 and 64-bit versions in wheel, egg,
and executable installers. These binaries have
all of the optional libraries included
https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation
Update: Python 3.6 is now supported by Pillow. Install with pip install pillow
and check https://pillow.readthedocs.io/en/latest/installation.html for more information.
However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).
https://travis-ci.org/python-pillow/Pillow/jobs/155605577
If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:
https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source
And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):
https://github.com/python-pillow/Pillow/tree/master/winbuild
Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.
Warning: Found conflicts between different versions of the same dependent assembly
This warning means that two projects reference the same assembly (e.g. System.Windows.Forms
) but the two projects require different versions. You have a few options:
Recompile all projects to use the same versions (e.g. move all to .Net 3.5). This is the preferred option because all code is running with the versions of dependencies they were compiled with.
Add a binding redirect. This will suppress the warning. However, your .Net 2.0 projects will (at runtime) be bound to the .Net 3.5 versions of dependent assemblies such as System.Windows.Forms
. You can quickly add a binding redirect by double-clicking on error in Visual Studio.
Use CopyLocal=true
. I'm not sure if this will suppress the warning. It will, like option 2 above, mean that all projects will use the .Net 3.5 version of System.Windows.Forms.
Here are a couple of ways to identify the offending reference(s):
- You can use a utility such as the one found at
https://gist.github.com/1553265
- Another simple method is to set Build
output verbosity (Tools, Options, Projects and Solutions, Build and
Run, MSBuild project build output verbosity, Detailed) and after
building, search the output window for the warning, and look at the
text just above it. (Hat tip to pauloya who suggested this in the
comments on this answer).
How do I show the changes which have been staged?
If you'd be interested in a visual side-by-side view, the diffuse visual diff tool can do that. It will even show three panes if some but not all changes are staged. In the case of conflicts, there will even be four panes.
Invoke it with
diffuse -m
in your Git working copy.
If you ask me, the best visual differ I've seen for a decade. Also, it is not specific to Git: It interoperates with a plethora of other VCS, including SVN, Mercurial, Bazaar, ...
See also: Show both staged & working tree in git diff?
Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop
the Perl language). I hope this (perl5-porters) is the right list. I
am cc'ing the Python string-sig because it is the origin of most of
the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am
planning to release a next "major" version, Python 1.5, by the end of
this year. I hope that Python and Perl can co-exist in years to come;
cross-pollination can be good for both languages. (I believe Larry
had a good look at Python when he added objects to Perl 5; O'Reilly
publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that
more closely matches Perl's syntax. We've tried to be as close to the
Perl syntax as possible within Python's syntax. However, the regex
syntax has some Python-specific extensions, which all begin with (?P .
Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed,
via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named
"foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.
I hope that this Python-specific extension won't conflict with any
future Perl extensions to the Perl regex syntax. If you have plans to
use (?P, please let us know as soon as possible so we can resolve the
conflict. Otherwise, it would be nice if the (?P syntax could be
permanently reserved for Python-specific syntax extensions. (Is
there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from
outside perl5-porters, so it's a pretty low-bandwidth activity.
(Sorry it was even lower last week--I was off in New York at Internet
World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my
blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
Return a string method in C#
These answers are all way too complicated!
The way he wrote the method is fine. The problem is where he invoked the method. He did not include parentheses after the method name, so the compiler thought he was trying to get a value from a variable instead of a method.
In Visual Basic and Delphi, those parentheses are optional, but in C#, they are required. So, to correct the last line of the original post:
Console.WriteLine("{0}", x.fullNameMethod());
How to insert current_timestamp into Postgres via python
Date and time input is accepted in almost any reasonable format,
including ISO 8601, SQL-compatible, traditional POSTGRES, and others.
For some formats, ordering of month, day, and year in date input is
ambiguous and there is support for specifying the expected ordering of
these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
How to store command results in a shell variable?
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
How can I check that JButton is pressed? If the isEnable() is not work?
JButton#isEnabled
changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.
When a JButton
is pressed, it fires a actionPerformed
event.
You are receiving Add button is pressed
when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.
Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener
it would always be false, as the button will only be in the pressed state while the add button's ActionListener
s are being called.
Based on all this information, I would suggest you might want to consider using a JCheckBox
which you can then use JCheckBox#isSelected
to determine if it has being checked or not.
Take a closer look at How to Use Buttons for more details
Remove Unnamed columns in pandas dataframe
df = df.loc[:, ~df.columns.str.contains('^Unnamed')]
In [162]: df
Out[162]:
colA ColB colC colD colE colF colG
0 44 45 26 26 40 26 46
1 47 16 38 47 48 22 37
2 19 28 36 18 40 18 46
3 50 14 12 33 12 44 23
4 39 47 16 42 33 48 38
if the first column in the CSV file has index values, then you can do this instead:
df = pd.read_csv('data.csv', index_col=0)
How to show text in combobox when no item selected?
I realize this is an old thread, but just wanted to let others who might search for an answer to this question know, in the current version of Visual Studio (2015), there is a property called "Placeholder Text" that does what jotbek originally asked about. Use the Properties box, under "Common" properties.
What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?
Let's un-complicate Bootstrap!
Notice how the col-sm occupies the 100% width (in other terms breaks into new line) below 576px
but col doesn't. You can notice the current width at the top center in gif.
Here comes the code:
<div class="container">
<div class="row">
<div class="col">col</div>
<div class="col">col</div>
<div class="col">col</div>
</div>
<div class="row">
<div class="col-sm">col-sm</div>
<div class="col-sm">col-sm</div>
<div class="col-sm">col-sm</div>
</div>
</div>
Bootstrap by default aligns all the columns(col) in a single row with equal width. In this case three col
will occupy 100%/3 width each, whatever the screen size. You can notice that in gif.
Now what if we want to render only one column per line i.e give 100% width to each column but for smaller screens only? Now comes the col-xx
classes!
I used col-sm
because I wanted to break the columns into separate lines below 576px. These 4 col-xx
classes are provided by Bootstrap for different display devices like mobiles, tablets, laptops, large monitors etc.
So,col-sm
would break below 576px, col-md
would break below 768px, col-lg
would break below 992px and col-xl
would break below 1200px
Note that there's no col-xs
class in bootstrap 4.
This pretty much sums-up. You can go back to work.
But there's bit more to it. Now comes the col-*
and col-xx-*
for customizing width.
Remember in the above example I mentioned that col
or col-xx
takes the equal width in a row. So if we want to give more width to a specific col
we can do this.
Bootstrap row is divided into 12 parts, so in above example there were 3 col
so each one takes 12/3 = 4 part. You can consider these parts as a way to measure width.
We could also write that in format col-*
i.e. col-4
like this :
<div class="row">
<div class="col-4">col</div>
<div class="col-4">col</div>
<div class="col-4">col</div>
</div>
And it would've made no difference because by default bootstrap gives equal width to col
(4 + 4 + 4 = 12).
But, what if we want to give 7 parts to 1st col
, 3 parts to 2nd col
and rest 2 parts (12-7-3 = 2) to 3rd col
(7+3+2 so total is 12), we can simply do this:
<div class="row">
<div class="col-7">col-7</div>
<div class="col-3">col-3</div>
<div class="col-2">col-2</div>
</div>
and you can customize the width of col-xx-*
classes also.
<div class="row">
<div class="col-sm-7">col-sm-7</div>
<div class="col-sm-3">col-sm-3</div>
<div class="col-sm-2">col-sm-2</div>
</div>
How does it look in the action?
What if sum of col
is more than 12? Then the col
will shift/adjust to below line. Yes, there can be any number of columns for a row!
<div class="row">
<div class="col-12">col-12</div>
<div class="col-9">col-9</div>
<div class="col-6">col-6</div>
<div class="col-6">col-6</div>
</div>
What if we want 3 columns in a row for large screens but split these columns into 2 rows for small screens?
<div class="row">
<div class="col-12 col-sm">col-12 col-sm TOP</div>
<div class="col col-sm">col col-sm</div>
<div class="col col-sm">col col-sm</div>
</div>
You can play around here: https://jsfiddle.net/JerryGoyal/6vqno0Lm/
Parse strings to double with comma and point
You DO NOT NEED to replace the comma and dot..
I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.
Here I made a complete example to make the difference clear.
string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}
double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}
The results is the following:
Play around with the culture and you will get the result you need.
SQL Case Expression Syntax?
Considering you tagged multiple products, I'd say the full correct syntax would be the one found in the ISO/ANSI SQL-92 standard:
<case expression> ::=
<case abbreviation>
| <case specification>
<case abbreviation> ::=
NULLIF <left paren> <value expression> <comma>
<value expression> <right paren>
| COALESCE <left paren> <value expression>
{ <comma> <value expression> }... <right paren>
<case specification> ::=
<simple case>
| <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[ <else clause> ]
END
<searched case> ::=
CASE
<searched when clause>...
[ <else clause> ]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
Syntax Rules
1) NULLIF (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1=V2 THEN NULL ELSE V1 END
2) COALESCE (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END
3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
END
4) If a <case specification> specifies a <simple case>, then let CO
be the <case operand>:
a) The data type of each <when operand> WO shall be comparable
with the data type of the <case operand>.
b) The <case specification> is equivalent to a <searched case>
in which each <searched when clause> specifies a <search
condition> of the form "CO=WO".
5) At least one <result> in a <case specification> shall specify a
<result expression>.
6) If an <else clause> is not specified, then ELSE NULL is im-
plicit.
7) The data type of a <case specification> is determined by ap-
plying Subclause 9.3, "Set operation result data types", to the
data types of all <result expression>s in the <case specifica-
tion>.
Access Rules
None.
General Rules
1) Case:
a) If a <result> specifies NULL, then its value is the null
value.
b) If a <result> specifies a <value expression>, then its value
is the value of that <value expression>.
2) Case:
a) If the <search condition> of some <searched when clause> in
a <case specification> is true, then the value of the <case
specification> is the value of the <result> of the first
(leftmost) <searched when clause> whose <search condition> is
true, cast as the data type of the <case specification>.
b) If no <search condition> in a <case specification> is true,
then the value of the <case expression> is the value of the
<result> of the explicit or implicit <else clause>, cast as
the data type of the <case specification>.
how do I create an array in jquery?
Not completely clear what you mean. Perhaps:
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var params = {};
params['pageNo'] = $(this).text();
params['sortBy'] = $("#sortBy").val();
$("#results").load( "jquery-routing.php", params );
return false;
});
});
</script>
Java says FileNotFoundException but file exists
Apart from all the other answers mentioned here, you can do one thing which worked for me.
If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.
It worked for me, hope it helps someone :)
How to do a Jquery Callback after form submit?
I do not believe there is a callback-function like the one you describe.
What is normal here is to do the alterations using some server-side language, like PHP.
In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.
PHP:
$someHiddenVar = $_POST["hidden_field"];
if (!empty($someHiddenVar)) {
// do something
}
One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.
$.post("test.php", $("#testform").serialize(), function(data) {
$('.result').html(data);
});
http://api.jquery.com/jQuery.post/
Get user input from textarea
Remove the spaces around your =
:
<div>
<input type="text" [(ngModel)]="str" name="str">
</div>
But you need to have the variable named str
on back-end, than its should work fine.
How do I run a batch file from my Java Application?
The executable used to run batch scripts is cmd.exe
which uses the /c
flag to specify the name of the batch file to run:
Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});
Theoretically you should also be able to run Scons in this manner, though I haven't tested this:
Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});
EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.
Reset git proxy to default configuration
If you have used Powershell commands to set the Proxy on windows machine doing the below helped me.
To unset the proxy use:
1. Open powershell
2. Enter the following:
[Environment]::SetEnvironmentVariable(“HTTP_PROXY”, $null, [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable(“HTTPS_PROXY”, $null, [EnvironmentVariableTarget]::Machine)
To set the proxy again use:
1. Open powershell
2. Enter the following:
[Environment]::SetEnvironmentVariable(“HTTP_PROXY”, “http://yourproxy.com:yourportnumber”, [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable(“HTTPS_PROXY”, “http://yourproxy.com:yourportnumber”, [EnvironmentVariableTarget]::Machine)
When should we use Observer and Observable?
Definition
Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically and corresponding changes are done to all dependent objects.
Examples
Let's say, your permanent address is changed then you need to notify passport authority and pan card authority. So here passport authority and pan card authority are observers and You are a subject.
On Facebook also, If you subscribe to someone then whenever new updates happen then you will be notified.
When to use it:
When one object changes its state, then all other dependents object must automatically change their state to maintain consistency
When the subject doesn't know about the number of observers it has.
When an object should be able to notify other objects without knowing who objects are.
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers
= new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
Step 2
Create Observer class.
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Binary String: "
+ Integer.toBinaryString( subject.getState() ) );
}
}
OctalObserver.java
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Octal String: "
+ Integer.toOctalString( subject.getState() ) );
}
}
HexaObserver.java
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Hex String: "
+ Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
Step 5
Verify the output.
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010
How to determine the Schemas inside an Oracle Data Pump Export file
Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the SQLFILE parameter to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.
SQL Update Multiple Fields FROM via a SELECT Statement
You can use:
UPDATE s SET
s.Field1 = q.Field1,
s.Field2 = q.Field2,
(list of fields...)
FROM (
SELECT Field1, Field2, (list of fields...)
FROM ProfilerTest.dbo.BookingDetails
WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2
Python pip install module is not found. How to link python to pip location?
how did you install easy_install/pip? make sure that you installed it for the upgraded version of python. what could have happened here is that the old (default) python install might be linked to your pip install. you might wanna try running the default version and importing the newly installed modules.
Select Pandas rows based on list index
you can also use iloc:
df.iloc[[1,3],:]
This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:
df.index.isin([1,3])
... as suggested in other responses.
What's the C++ version of Java's ArrayList
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
Split string with JavaScript
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
jQuery AJAX file upload PHP
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
Ways to insert javascript into URL?
JavaScript injection is not at attack on your web application. JavaScript injection simply adds JavaScript code for the browser to execute. The only way JavaScript could harm your web application is if you have a blog posting or some other area in which user input is stored. This could be a problem because an attacker could inject their code and leave it there for other users to execute. This attack is known as Cross-Site Scripting. The worst scenario would be Cross-Site Forgery, which allows attackers to inject a statement that will steal a user's cookie and therefore give the attacker their session ID.
Check whether an array is empty
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject)
function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true
Are there best practices for (Java) package organization?
I'm not aware of standard practices for package organization. I generally create packages that cover some reasonably broad spectrum, but I can differentiate within a project. For example, a personal project I'm currently working on has a package devoted to my customized UI controls (full of classes subclassing swing classes). I've got a package devoted to my database management stuff, I've got a package for a set of listeners/events that I've created, and so on.
On the other hand I've had a coworker create a new package for almost everything he did. Each different MVC he wanted got its own package, and it seemed a MVC set was the only grouping of classes allowed to be in the same package. I recall at one point he had 5 different packages that each had a single class in them. I think his method is a little bit on the extreme (and the team forced him to reduce his package count when we simply couldn't handle it), but for a nontrivial application, so would putting everything in the same package. It's a balance point you and your teammates have to find for yourself.
One thing you can do is try to step back and think: if you were a new member introduced to the project, or your project was released as open source or an API, how easy/difficult would it be to find what you want? Because for me, that's what I really want out of packages: organization. Similar to how I store files in folder on my computer, I expect to be able to find them again without having to search my entire drive. I expect to be able to find the class I want without having to search the list of all classes in the package.
DTO and DAO concepts and MVC
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.
DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.
DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
More than one file was found with OS independent path 'META-INF/LICENSE'
I faced this issue, first with some native libraries (.so files) and then with java/kotlin files. Turned out I was including a library from source as well as referencing artifactory through a transitive dependency. Check your dependency tree to see if there are any redundant entries. Use ./gradlew :app:dependencies
to get the dependency tree. Replace "app" with your module name if the main module name is different.
Initializing default values in a struct
Yes. bar.a
and bar.b
are set to true, but bar.c
is undefined. However, certain compilers will set it to false.
See a live example here: struct demo
According to C++ standard Section 8.5.12:
if no initialization is performed, an
object with automatic or dynamic storage duration has indeterminate value
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
If you don't really want undefined bar.c
to start with, you should also initialize it like you did for bar.a
and bar.b
.
scp from Linux to Windows
Open bash window. Preferably git bash.
write
scp username@remote_ip:/directory_of_file/filename 'windows_location_you_want_to_store_the_file'
Example:
Suppose your username is jewel
your IP is 176.35.96.32
your remote file location is /usr/local/forme
your filename is logs.zip
and you want to store in your windows PC's D drive forme folder
then the command will be
scp [email protected]:/usr/local/forme/logs.zip 'D:/forme'
**Keep the local file directory inside single quote.
How to populate a sub-document in mongoose after creating it?
@user1417684 and @chris-foster are right!
excerpt from working code (without error handling):
var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel = mongoose.model('items', ItemSchema);
var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {
var new_item = new ItemModel(new_item);
new_item.subitem = new_sub_item._id;
new_item.save(function (error, new_item) {
// so this is a valid way to populate via the Model
// as documented in comments above (here @stack overflow):
ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
callback(new_item.toObject());
});
// or populate directly on the result object
new_item.populate('subitem', function(error, new_item) {
callback(new_item.toObject());
});
});
});
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
Spring lets you define multiple contexts in a parent-child hierarchy.
The applicationContext.xml
defines the beans for the "root webapp context", i.e. the context associated with the webapp.
The spring-servlet.xml
(or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml
for servlet spring1
, spring2-servlet.xml
for servlet spring2
).
Beans in spring-servlet.xml
can reference beans in applicationContext.xml
, but not vice versa.
All Spring MVC controllers must go in the spring-servlet.xml
context.
In most simple cases, the applicationContext.xml
context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.
Getting or changing CSS class property with Javascript using DOM style
As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.
This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...
function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
Extract code country from phone number [libphonenumber]
I have got kept a handy helper method to take care of this based on one answer posted above:
Imports:
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
Function:
fun parseCountryCode( phoneNumberStr: String?): String {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
// phone must begin with '+'
val numberProto = phoneUtil.parse(phoneNumberStr, "")
numberProto.countryCode.toString()
} catch (e: NumberParseException) {
""
}
}
How do you close/hide the Android soft keyboard using Java?
Try This one
public void disableSoftKeyboard(final EditText v) {
if (Build.VERSION.SDK_INT >= 11) {
v.setRawInputType(InputType.TYPE_CLASS_TEXT);
v.setTextIsSelectable(true);
} else {
v.setRawInputType(InputType.TYPE_NULL);
v.setFocusable(true);
}
}
Converting String to Int using try/except in Python
It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
What's the UIScrollView contentInset property for?
It sets the distance of the inset between the content view and the enclosing scroll view.
Obj-C
aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);
Swift 5.0
aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)
Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:
_|?_cW_?_|_?_
| |
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
_|_______|___
?
(cH = contentSize.height; cW = contentSize.width)
The scroll view encloses the content view plus whatever padding is provided by the specified content insets.
Difference between using bean id and name in Spring configuration file
Is there difference in defining Id & name in ApplicationContext xml ? No
As of 3.1(spring), id is also defined as an xsd:string type.
It means whatever characters allowed in defining name are also allowed in Id.
This was not possible prior to Spring 3.1.
Why to use name when it is same as Id ?
It is useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.
For example, the configuration metadata for subsystem A may refer to a DataSource via the name subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource via the name subsystemB-dataSource. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name myApp-dataSource. To have all three names refer to the same object you add to the MyApp configuration metadata the following
<bean id="myApp-dataSource" name="subsystemA-dataSource,subsystemB-dataSource" ..../>
Alternatively, You can have separate xml configuration files for each sub-system and then you can make use of
alias to define your own names.
<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
<alias name="subsystemA-dataSource" alias="myApp-dataSource" />
How can I one hot encode in Python?
One-hot encoding requires bit more than converting the values to indicator variables. Typically ML process requires you to apply this coding several times to validation or test data sets and applying the model you construct to real-time observed data. You should store the mapping (transform) that was used to construct the model. A good solution would use the DictVectorizer
or LabelEncoder
(followed by get_dummies
. Here is a function that you can use:
def oneHotEncode2(df, le_dict = {}):
if not le_dict:
columnsToEncode = list(df.select_dtypes(include=['category','object']))
train = True;
else:
columnsToEncode = le_dict.keys()
train = False;
for feature in columnsToEncode:
if train:
le_dict[feature] = LabelEncoder()
try:
if train:
df[feature] = le_dict[feature].fit_transform(df[feature])
else:
df[feature] = le_dict[feature].transform(df[feature])
df = pd.concat([df,
pd.get_dummies(df[feature]).rename(columns=lambda x: feature + '_' + str(x))], axis=1)
df = df.drop(feature, axis=1)
except:
print('Error encoding '+feature)
#df[feature] = df[feature].convert_objects(convert_numeric='force')
df[feature] = df[feature].apply(pd.to_numeric, errors='coerce')
return (df, le_dict)
This works on a pandas dataframe and for each column of the dataframe it creates and returns a mapping back. So you would call it like this:
train_data, le_dict = oneHotEncode2(train_data)
Then on the test data, the call is made by passing the dictionary returned back from training:
test_data, _ = oneHotEncode2(test_data, le_dict)
An equivalent method is to use DictVectorizer
. A related post on the same is on my blog. I mention it here since it provides some reasoning behind this approach over simply using get_dummies post (disclosure: this is my own blog).
Python loop for inside lambda
Since a for
loop is a statement (as is print
, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write
method on sys.stdout
along with the join
method.
x = lambda x: sys.stdout.write("\n".join(x) + "\n")
Which Radio button in the group is checked?
For developers using VB.NET
Private Function GetCheckedRadio(container) As RadioButton
For Each control In container.Children
Dim radio As RadioButton = TryCast(control, RadioButton)
If radio IsNot Nothing AndAlso radio.IsChecked Then
Return radio
End If
Next
Return Nothing
End Function
iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons
Absolutely Asset Catalog is you answer, it removes the need to follow naming conventions when you are adding or updating your app icons.
Below are the steps to Migrating an App Icon Set or Launch Image Set From Apple:
1- In the project navigator, select your target.
2- Select the General pane, and scroll to the App Icons section.
3- Specify an image in the App Icon table by clicking the folder icon on the right side of the image row and selecting the image file in the dialog that appears.
4-Migrate the images in the App Icon table to an asset catalog by clicking the Use Asset Catalog button, selecting an asset catalog from the popup menu, and clicking the Migrate button.
Alternatively, you can create an empty app icon set by choosing Editor > New App Icon, and add images to the set by dragging them from the Finder or by choosing Editor > Import.
What is the (function() { } )() construct in JavaScript?
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
How does the enhanced for statement work for arrays, and how to get an iterator for an array?
I like the answer from 30thh using Iterators
from Guava. However, from some frameworks I get null instead of an empty array, and Iterators.forArray(array)
does not handle that well. So I came up with this helper method, which you can call with Iterator<String> it = emptyIfNull(array);
public static <F> UnmodifiableIterator<F> emptyIfNull(F[] array) {
if (array != null) {
return Iterators.forArray(array);
}
return new UnmodifiableIterator<F>() {
public boolean hasNext() {
return false;
}
public F next() {
return null;
}
};
}
What is the best way to implement nested dictionaries?
For easy iterating over your nested dictionary, why not just write a simple generator?
def each_job(my_dict):
for state, a in my_dict.items():
for county, b in a.items():
for job, value in b.items():
yield {
'state' : state,
'county' : county,
'job' : job,
'value' : value
}
So then, if you have your compilicated nested dictionary, iterating over it becomes simple:
for r in each_job(my_dict):
print "There are %d %s in %s, %s" % (r['value'], r['job'], r['county'], r['state'])
Obviously your generator can yield whatever format of data is useful to you.
Why are you using try catch blocks to read the tree? It's easy enough (and probably safer) to query whether a key exists in a dict before trying to retrieve it. A function using guard clauses might look like this:
if not my_dict.has_key('new jersey'):
return False
nj_dict = my_dict['new jersey']
...
Or, a perhaps somewhat verbose method, is to use the get method:
value = my_dict.get('new jersey', {}).get('middlesex county', {}).get('salesmen', 0)
But for a somewhat more succinct way, you might want to look at using a collections.defaultdict, which is part of the standard library since python 2.5.
import collections
def state_struct(): return collections.defaultdict(county_struct)
def county_struct(): return collections.defaultdict(job_struct)
def job_struct(): return 0
my_dict = collections.defaultdict(state_struct)
print my_dict['new jersey']['middlesex county']['salesmen']
I'm making assumptions about the meaning of your data structure here, but it should be easy to adjust for what you actually want to do.
Server returned HTTP response code: 401 for URL: https
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
Tomcat request timeout
If you are trying to prevent a request from running too long, then setting a timeout in Tomcat will not help you. As Chris says, you can set the global timeout value for Tomcat. But, from The Apache Tomcat Connector - Generic HowTo
Timeouts, see the Reply Timeout section:
JK can also use a timeout on request replies. This timeout does not
measure the full processing time of the response. Instead it controls,
how much time between consecutive response packets is allowed.
In most cases, this is what one actually wants. Consider for example
long running downloads. You would not be able to set an effective
global reply timeout, because downloads could last for many minutes.
Most applications though have limited processing time before starting
to return the response. For those applications you could set an
explicit reply timeout. Applications that do not harmonise with reply
timeouts are batch type applications, data warehouse and reporting
applications which are expected to observe long processing times.
If JK aborts waiting for a response, because a reply timeout fired,
there is no way to stop processing on the backend. Although you free
processing resources in your web server, the request will continue to
run on the backend - without any way to send back a result once the
reply timeout fired.
So Tomcat will detect that the servlet has not responded within the timeout and will send back a response to the user, but will not stop the thread running. I don't think you can achieve what you want to do.
Sorting objects by property values
Example.
This runs on cscript.exe, on windows.
// define the Car class
(function() {
// makeClass - By John Resig (MIT Licensed)
// Allows either new User() or User() to be employed for construction.
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, (args && args.callee) ? args : arguments );
} else
return new arguments.callee( arguments );
};
}
Car = makeClass();
Car.prototype.init = function(make, model, price, topSpeed, weight) {
this.make = make;
this.model = model;
this.price = price;
this.weight = weight;
this.topSpeed = topSpeed;
};
})();
// create a list of cars
var autos = [
new Car("Chevy", "Corvair", 1800, 88, 2900),
new Car("Buick", "LeSabre", 31000, 138, 3700),
new Car("Toyota", "Prius", 24000, 103, 3200),
new Car("Porsche", "911", 92000, 155, 3100),
new Car("Mercedes", "E500", 67000, 145, 3800),
new Car("VW", "Passat", 31000, 135, 3700)
];
// a list of sorting functions
var sorters = {
byWeight : function(a,b) {
return (a.weight - b.weight);
},
bySpeed : function(a,b) {
return (a.topSpeed - b.topSpeed);
},
byPrice : function(a,b) {
return (a.price - b.price);
},
byModelName : function(a,b) {
return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
},
byMake : function(a,b) {
return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
}
};
function say(s) {WScript.Echo(s);}
function show(title)
{
say ("sorted by: "+title);
for (var i=0; i < autos.length; i++) {
say(" " + autos[i].model);
}
say(" ");
}
autos.sort(sorters.byWeight);
show("Weight");
autos.sort(sorters.byModelName);
show("Name");
autos.sort(sorters.byPrice);
show("Price");
You can also make a general sorter.
var byProperty = function(prop) {
return function(a,b) {
if (typeof a[prop] == "number") {
return (a[prop] - b[prop]);
} else {
return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
}
};
};
autos.sort(byProperty("topSpeed"));
show("Top Speed");
How can I pipe stderr, and not stdout?
It's much easier to visualize things if you think about what's really going on with "redirects" and "pipes." Redirects and pipes in bash do one thing: modify where the process file descriptors 0, 1, and 2 point to (see /proc/[pid]/fd/*).
When a pipe or "|" operator is present on the command line, the first thing to happen is that bash creates a fifo and points the left side command's FD 1 to this fifo, and points the right side command's FD 0 to the same fifo.
Next, the redirect operators for each side are evaluated from left to right, and the current settings are used whenever duplication of the descriptor occurs. This is important because since the pipe was set up first, the FD1 (left side) and FD0 (right side) are already changed from what they might normally have been, and any duplication of these will reflect that fact.
Therefore, when you type something like the following:
command 2>&1 >/dev/null | grep 'something'
Here is what happens, in order:
- a pipe (fifo) is created. "command FD1" is pointed to this pipe. "grep FD0" also is pointed to this pipe
- "command FD2" is pointed to where "command FD1" currently points (the pipe)
- "command FD1" is pointed to /dev/null
So, all output that "command" writes to its FD 2 (stderr) makes its way to the pipe and is read by "grep" on the other side. All output that "command" writes to its FD 1 (stdout) makes its way to /dev/null.
If instead, you run the following:
command >/dev/null 2>&1 | grep 'something'
Here's what happens:
- a pipe is created and "command FD 1" and "grep FD 0" are pointed to it
- "command FD 1" is pointed to /dev/null
- "command FD 2" is pointed to where FD 1 currently points (/dev/null)
So, all stdout and stderr from "command" go to /dev/null. Nothing goes to the pipe, and thus "grep" will close out without displaying anything on the screen.
Also note that redirects (file descriptors) can be read-only (<), write-only (>), or read-write (<>).
A final note. Whether a program writes something to FD1 or FD2, is entirely up to the programmer. Good programming practice dictates that error messages should go to FD 2 and normal output to FD 1, but you will often find sloppy programming that mixes the two or otherwise ignores the convention.
How can I create a simple message box in Python?
Also you can position the other window before withdrawing it so that you position your message
from tkinter import *
import tkinter.messagebox
window = Tk()
window.wm_withdraw()
# message at x:200,y:200
window.geometry("1x1+200+200") # remember its.geometry("WidthxHeight(+or-)X(+or-)Y")
tkinter.messagebox.showerror(title="error", message="Error Message", parent=window)
# center screen message
window.geometry(f"1x1+{round(window.winfo_screenwidth() / 2)}+{round(window.winfo_screenheight() / 2)}")
tkinter.messagebox.showinfo(title="Greetings", message="Hello World!")
Please Note: This is Lewis Cowles' answer just Python 3ified, since tkinter has changed since python 2. If you want your code to be backwords compadible do something like this:
try:
import tkinter
import tkinter.messagebox
except ModuleNotFoundError:
import Tkinter as tkinter
import tkMessageBox as tkinter.messagebox
How can I write maven build to add resources to classpath?
If you place anything in src/main/resources
directory, then by default it will end up in your final *.jar
. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:
*.jar
is not correctly loaded (maybe typo in the path?)
- you are not addressing the resource correctly, for instance:
/src/main/resources/conf/settings.properties
is seen on classpath as classpath:conf/settings.properties
Get int value from enum in C#
public enum Suit : int
{
Spades = 0,
Hearts = 1,
Clubs = 2,
Diamonds = 3
}
Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));
// From int
Console.WriteLine((Suit)1);
// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));
if (typeof(Suit).IsEnumDefined("Spades"))
{
var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
Console.Out.WriteLine("{0}", res);
}
Time stamp in the C programming language
This will give you the time in seconds + microseconds
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
tv.tv_sec // seconds
tv.tv_usec // microseconds
Docker error : no space left on device
I went to the docker settings and changed the image space available. It reached the limit while creating the new image with docker build
. So I just increased the amount available.
How do I use extern to share variables between source files?
Using extern
is only of relevance when the program you're building
consists of multiple source files linked together, where some of the
variables defined, for example, in source file file1.c
need to be
referenced in other source files, such as file2.c
.
It is important to understand the difference between defining a
variable and declaring a
variable:
A variable is declared when the compiler is informed that a
variable exists (and this is its type); it does not allocate the
storage for the variable at that point.
A variable is defined when the compiler allocates the storage for
the variable.
You may declare a variable multiple times (though once is sufficient);
you may only define it once within a given scope.
A variable definition is also a declaration, but not all variable
declarations are definitions.
Best way to declare and define global variables
The clean, reliable way to declare and define global variables is to use
a header file to contain an extern
declaration of the variable.
The header is included by the one source file that defines the variable
and by all the source files that reference the variable.
For each program, one source file (and only one source file) defines the
variable.
Similarly, one header file (and only one header file) should declare the
variable.
The header file is crucial; it enables cross-checking between
independent TUs (translation units — think source files) and ensures
consistency.
Although there are other ways of doing it, this method is simple and
reliable.
It is demonstrated by file3.h
, file1.c
and file2.c
:
file3.h
extern int global_variable; /* Declaration of the variable */
file1.c
#include "file3.h" /* Declaration made available here */
#include "prog1.h" /* Function declarations */
/* Variable defined here */
int global_variable = 37; /* Definition checked against declaration */
int increment(void) { return global_variable++; }
file2.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
void use_it(void)
{
printf("Global variable: %d\n", global_variable++);
}
That's the best way to declare and define global variables.
The next two files complete the source for prog1
:
The complete programs shown use functions, so function declarations have
crept in.
Both C99 and C11 require functions to be declared or defined before they
are used (whereas C90 did not, for good reasons).
I use the keyword extern
in front of function declarations in headers
for consistency — to match the extern
in front of variable
declarations in headers.
Many people prefer not to use extern
in front of function
declarations; the compiler doesn't care — and ultimately, neither do I
as long as you're consistent, at least within a source file.
prog1.h
extern void use_it(void);
extern int increment(void);
prog1.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
int main(void)
{
use_it();
global_variable += 19;
use_it();
printf("Increment: %d\n", increment());
return 0;
}
prog1
uses prog1.c
, file1.c
, file2.c
, file3.h
and prog1.h
.
The file prog1.mk
is a makefile for prog1
only.
It will work with most versions of make
produced since about the turn
of the millennium.
It is not tied specifically to GNU Make.
prog1.mk
# Minimal makefile for prog1
PROGRAM = prog1
FILES.c = prog1.c file1.c file2.c
FILES.h = prog1.h file3.h
FILES.o = ${FILES.c:.c=.o}
CC = gcc
SFLAGS = -std=c11
GFLAGS = -g
OFLAGS = -O3
WFLAG1 = -Wall
WFLAG2 = -Wextra
WFLAG3 = -Werror
WFLAG4 = -Wstrict-prototypes
WFLAG5 = -Wmissing-prototypes
WFLAGS = ${WFLAG1} ${WFLAG2} ${WFLAG3} ${WFLAG4} ${WFLAG5}
UFLAGS = # Set on command line only
CFLAGS = ${SFLAGS} ${GFLAGS} ${OFLAGS} ${WFLAGS} ${UFLAGS}
LDFLAGS =
LDLIBS =
all: ${PROGRAM}
${PROGRAM}: ${FILES.o}
${CC} -o $@ ${CFLAGS} ${FILES.o} ${LDFLAGS} ${LDLIBS}
prog1.o: ${FILES.h}
file1.o: ${FILES.h}
file2.o: ${FILES.h}
# If it exists, prog1.dSYM is a directory on macOS
DEBRIS = a.out core *~ *.dSYM
RM_FR = rm -fr
clean:
${RM_FR} ${FILES.o} ${PROGRAM} ${DEBRIS}
Guidelines
Rules to be broken by experts only, and only with good reason:
A header file only contains extern
declarations of variables — never
static
or unqualified variable definitions.
For any given variable, only one header file declares it (SPOT —
Single Point of Truth).
A source file never contains extern
declarations of variables —
source files always include the (sole) header that declares them.
For any given variable, exactly one source file defines the variable,
preferably initializing it too. (Although there is no need to
initialize explicitly to zero, it does no harm and can do some good,
because there can be only one initialized definition of a particular
global variable in a program).
The source file that defines the variable also includes the header to
ensure that the definition and the declaration are consistent.
A function should never need to declare a variable using extern
.
Avoid global variables whenever possible — use functions instead.
The source code and text of this answer are available in my
SOQ (Stack Overflow Questions)
repository on GitHub in the
src/so-0143-3204
sub-directory.
If you're not an experienced C programmer, you could (and perhaps
should) stop reading here.
Not so good way to define global variables
With some (indeed, many) C compilers, you can get away with what's
called a 'common' definition of a variable too.
'Common', here, refers to a technique used in Fortran for sharing
variables between source files, using a (possibly named) COMMON block.
What happens here is that each of a number of files provides a tentative
definition of the variable.
As long as no more than one file provides an initialized definition,
then the various files end up sharing a common single definition of the
variable:
file10.c
#include "prog2.h"
long l; /* Do not do this in portable code */
void inc(void) { l++; }
file11.c
#include "prog2.h"
long l; /* Do not do this in portable code */
void dec(void) { l--; }
file12.c
#include "prog2.h"
#include <stdio.h>
long l = 9; /* Do not do this in portable code */
void put(void) { printf("l = %ld\n", l); }
This technique does not conform to the letter of the C standard and the
'one definition rule' — it is officially undefined behaviour:
J.2 Undefined behavior
An identifier with external linkage is used, but in the program there
does not exist exactly one external definition for the identifier, or
the identifier is not used and there exist multiple external
definitions for the identifier (6.9).
§6.9 External definitions ¶5
An external definition is an external declaration that is also a
definition of a function (other than an inline definition) or an
object.
If an identifier declared with external linkage is used in an
expression (other than as part of the operand of a sizeof
or
_Alignof
operator whose result is an integer constant), somewhere in
the entire program there shall be exactly one external definition for
the identifier; otherwise, there shall be no more than
one.161)
161) Thus, if an identifier declared with external linkage
is not used in an expression, there need be no external definition for
it.
However, the C standard also lists it in informative Annex J as one of
the Common extensions.
J.5.11 Multiple external definitions
There may be more than one external definition for the identifier of
an object, with or without the explicit use of the keyword extern; if
the definitions disagree, or more than one is initialized, the
behavior is undefined (6.9.2).
Because this technique is not always supported, it is best to avoid
using it, especially if your code needs to be portable.
Using this technique, you can also end up with unintentional type
punning.
If one of the files above declared l
as a double
instead of as a
long
, C's type-unsafe linkers probably would not spot the mismatch.
If you're on a machine with 64-bit long
and double
, you'd not even
get a warning; on a machine with 32-bit long
and 64-bit double
,
you'd probably get a warning about the different sizes — the linker
would use the largest size, exactly as a Fortran program would take the
largest size of any common blocks.
Note that GCC 10.1.0, which was released on 2020-05-07, changes the
default compilation options to use
-fno-common
, which means
that by default, the code above no longer links unless you override the
default with -fcommon
(or use attributes, etc — see the link).
The next two files complete the source for prog2
:
prog2.h
extern void dec(void);
extern void put(void);
extern void inc(void);
prog2.c
#include "prog2.h"
#include <stdio.h>
int main(void)
{
inc();
put();
dec();
put();
dec();
put();
}
prog2
uses prog2.c
, file10.c
, file11.c
, file12.c
, prog2.h
.
Warning
As noted in comments here, and as stated in my answer to a similar
question, using multiple
definitions for a global variable leads to undefined behaviour (J.2;
§6.9), which is the standard's way of saying "anything could happen".
One of the things that can happen is that the program behaves as you
expect; and J.5.11 says, approximately, "you might be lucky more often
than you deserve".
But a program that relies on multiple definitions of an extern variable
— with or without the explicit 'extern' keyword — is not a strictly
conforming program and not guaranteed to work everywhere.
Equivalently: it contains a bug which may or may not show itself.
Violating the guidelines
There are, of course, many ways in which these guidelines can be broken.
Occasionally, there may be a good reason to break the guidelines, but
such occasions are extremely unusual.
faulty_header.h
int some_var; /* Do not do this in a header!!! */
Note 1: if the header defines the variable without the extern
keyword,
then each file that includes the header creates a tentative definition
of the variable.
As noted previously, this will often work, but the C standard does not
guarantee that it will work.
broken_header.h
int some_var = 13; /* Only one source file in a program can use this */
Note 2: if the header defines and initializes the variable, then only
one source file in a given program can use the header.
Since headers are primarily for sharing information, it is a bit silly
to create one that can only be used once.
seldom_correct.h
static int hidden_global = 3; /* Each source file gets its own copy */
Note 3: if the header defines a static variable (with or without
initialization), then each source file ends up with its own private
version of the 'global' variable.
If the variable is actually a complex array, for example, this can lead
to extreme duplication of code. It can, very occasionally, be a
sensible way to achieve some effect, but that is very unusual.
Summary
Use the header technique I showed first.
It works reliably and everywhere.
Note, in particular, that the header declaring the global_variable
is
included in every file that uses it — including the one that defines it.
This ensures that everything is self-consistent.
Similar concerns arise with declaring and defining functions —
analogous rules apply.
But the question was about variables specifically, so I've kept the
answer to variables only.
End of Original Answer
If you're not an experienced C programmer, you probably should stop reading here.
Late Major Addition
Avoiding Code Duplication
One concern that is sometimes (and legitimately) raised about the
'declarations in headers, definitions in source' mechanism described
here is that there are two files to be kept synchronized — the header
and the source. This is usually followed up with an observation that a
macro can be used so that the header serves double duty — normally
declaring the variables, but when a specific macro is set before the
header is included, it defines the variables instead.
Another concern can be that the variables need to be defined in each of
a number of 'main programs'. This is normally a spurious concern; you
can simply introduce a C source file to define the variables and link
the object file produced with each of the programs.
A typical scheme works like this, using the original global variable
illustrated in file3.h
:
file3a.h
#ifdef DEFINE_VARIABLES
#define EXTERN /* nothing */
#else
#define EXTERN extern
#endif /* DEFINE_VARIABLES */
EXTERN int global_variable;
file1a.c
#define DEFINE_VARIABLES
#include "file3a.h" /* Variable defined - but not initialized */
#include "prog3.h"
int increment(void) { return global_variable++; }
file2a.c
#include "file3a.h"
#include "prog3.h"
#include <stdio.h>
void use_it(void)
{
printf("Global variable: %d\n", global_variable++);
}
The next two files complete the source for prog3
:
prog3.h
extern void use_it(void);
extern int increment(void);
prog3.c
#include "file3a.h"
#include "prog3.h"
#include <stdio.h>
int main(void)
{
use_it();
global_variable += 19;
use_it();
printf("Increment: %d\n", increment());
return 0;
}
prog3
uses prog3.c
, file1a.c
, file2a.c
, file3a.h
, prog3.h
.
Variable initialization
The problem with this scheme as shown is that it does not provide for
initialization of the global variable. With C99 or C11 and variable argument
lists for macros, you could define a macro to support initialization too.
(With C89 and no support for variable argument lists in macros, there is no
easy way to handle arbitrarily long initializers.)
file3b.h
#ifdef DEFINE_VARIABLES
#define EXTERN /* nothing */
#define INITIALIZER(...) = __VA_ARGS__
#else
#define EXTERN extern
#define INITIALIZER(...) /* nothing */
#endif /* DEFINE_VARIABLES */
EXTERN int global_variable INITIALIZER(37);
EXTERN struct { int a; int b; } oddball_struct INITIALIZER({ 41, 43 });
Reverse contents of #if
and #else
blocks, fixing bug identified by
Denis Kniazhev
file1b.c
#define DEFINE_VARIABLES
#include "file3b.h" /* Variables now defined and initialized */
#include "prog4.h"
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
file2b.c
#include "file3b.h"
#include "prog4.h"
#include <stdio.h>
void use_them(void)
{
printf("Global variable: %d\n", global_variable++);
oddball_struct.a += global_variable;
oddball_struct.b -= global_variable / 2;
}
Clearly, the code for the oddball structure is not what you'd normally
write, but it illustrates the point. The first argument to the second
invocation of INITIALIZER
is { 41
and the remaining argument
(singular in this example) is 43 }
. Without C99 or similar support
for variable argument lists for macros, initializers that need to
contain commas are very problematic.
Correct header file3b.h
included (instead of fileba.h
) per
Denis Kniazhev
The next two files complete the source for prog4
:
prog4.h
extern int increment(void);
extern int oddball_value(void);
extern void use_them(void);
prog4.c
#include "file3b.h"
#include "prog4.h"
#include <stdio.h>
int main(void)
{
use_them();
global_variable += 19;
use_them();
printf("Increment: %d\n", increment());
printf("Oddball: %d\n", oddball_value());
return 0;
}
prog4
uses prog4.c
, file1b.c
, file2b.c
, prog4.h
, file3b.h
.
Header Guards
Any header should be protected against reinclusion, so that type
definitions (enum, struct or union types, or typedefs generally) do not
cause problems. The standard technique is to wrap the body of the
header in a header guard such as:
#ifndef FILE3B_H_INCLUDED
#define FILE3B_H_INCLUDED
...contents of header...
#endif /* FILE3B_H_INCLUDED */
The header might be included twice indirectly. For example, if
file4b.h
includes file3b.h
for a type definition that isn't shown,
and file1b.c
needs to use both header file4b.h
and file3b.h
, then
you have some more tricky issues to resolve. Clearly, you might revise
the header list to include just file4b.h
. However, you might not be
aware of the internal dependencies — and the code should, ideally,
continue to work.
Further, it starts to get tricky because you might include file4b.h
before including file3b.h
to generate the definitions, but the normal
header guards on file3b.h
would prevent the header being reincluded.
So, you need to include the body of file3b.h
at most once for
declarations, and at most once for definitions, but you might need both
in a single translation unit (TU — a combination of a source file and
the headers it uses).
Multiple inclusion with variable definitions
However, it can be done subject to a not too unreasonable constraint.
Let's introduce a new set of file names:
external.h
for the EXTERN macro definitions, etc.
file1c.h
to define types (notably, struct oddball
, the type of oddball_struct
).
file2c.h
to define or declare the global variables.
file3c.c
which defines the global variables.
file4c.c
which simply uses the global variables.
file5c.c
which shows that you can declare and then define the global variables.
file6c.c
which shows that you can define and then (attempt to) declare the global variables.
In these examples, file5c.c
and file6c.c
directly include the header
file2c.h
several times, but that is the simplest way to show that the
mechanism works. It means that if the header was indirectly included
twice, it would also be safe.
The restrictions for this to work are:
The header defining or declaring the global variables may not itself
define any types.
Immediately before you include a header that should define variables,
you define the macro DEFINE_VARIABLES.
The header defining or declaring the variables has stylized contents.
external.h
/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is invoked, it redefines the macros EXTERN, INITIALIZE
** based on whether macro DEFINE_VARIABLES is currently defined.
*/
#undef EXTERN
#undef INITIALIZE
#ifdef DEFINE_VARIABLES
#define EXTERN /* nothing */
#define INITIALIZE(...) = __VA_ARGS__
#else
#define EXTERN extern
#define INITIALIZE(...) /* nothing */
#endif /* DEFINE_VARIABLES */
file1c.h
#ifndef FILE1C_H_INCLUDED
#define FILE1C_H_INCLUDED
struct oddball
{
int a;
int b;
};
extern void use_them(void);
extern int increment(void);
extern int oddball_value(void);
#endif /* FILE1C_H_INCLUDED */
file2c.h
/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2C_H_DEFINITIONS)
#undef FILE2C_H_INCLUDED
#endif
#ifndef FILE2C_H_INCLUDED
#define FILE2C_H_INCLUDED
#include "external.h" /* Support macros EXTERN, INITIALIZE */
#include "file1c.h" /* Type definition for struct oddball */
#if !defined(DEFINE_VARIABLES) || !defined(FILE2C_H_DEFINITIONS)
/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });
#endif /* !DEFINE_VARIABLES || !FILE2C_H_DEFINITIONS */
/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */
#endif /* FILE2C_H_INCLUDED */
file3c.c
#define DEFINE_VARIABLES
#include "file2c.h" /* Variables now defined and initialized */
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
file4c.c
#include "file2c.h"
#include <stdio.h>
void use_them(void)
{
printf("Global variable: %d\n", global_variable++);
oddball_struct.a += global_variable;
oddball_struct.b -= global_variable / 2;
}
file5c.c
#include "file2c.h" /* Declare variables */
#define DEFINE_VARIABLES
#include "file2c.h" /* Variables now defined and initialized */
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
file6c.c
#define DEFINE_VARIABLES
#include "file2c.h" /* Variables now defined and initialized */
#include "file2c.h" /* Declare variables */
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
The next source file completes the source (provides a main program) for prog5
, prog6
and prog7
:
prog5.c
#include "file2c.h"
#include <stdio.h>
int main(void)
{
use_them();
global_variable += 19;
use_them();
printf("Increment: %d\n", increment());
printf("Oddball: %d\n", oddball_value());
return 0;
}
prog5
uses prog5.c
, file3c.c
, file4c.c
, file1c.h
, file2c.h
, external.h
.
prog6
uses prog5.c
, file5c.c
, file4c.c
, file1c.h
, file2c.h
, external.h
.
prog7
uses prog5.c
, file6c.c
, file4c.c
, file1c.h
, file2c.h
, external.h
.
This scheme avoids most problems. You only run into a problem if a
header that defines variables (such as file2c.h
) is included by
another header (say file7c.h
) that defines variables. There isn't an
easy way around that other than "don't do it".
You can partially work around the problem by revising file2c.h
into
file2d.h
:
file2d.h
/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2D_H_DEFINITIONS)
#undef FILE2D_H_INCLUDED
#endif
#ifndef FILE2D_H_INCLUDED
#define FILE2D_H_INCLUDED
#include "external.h" /* Support macros EXTERN, INITIALIZE */
#include "file1c.h" /* Type definition for struct oddball */
#if !defined(DEFINE_VARIABLES) || !defined(FILE2D_H_DEFINITIONS)
/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });
#endif /* !DEFINE_VARIABLES || !FILE2D_H_DEFINITIONS */
/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2D_H_DEFINITIONS
#undef DEFINE_VARIABLES
#endif /* DEFINE_VARIABLES */
#endif /* FILE2D_H_INCLUDED */
The issue becomes 'should the header include #undef DEFINE_VARIABLES
?'
If you omit that from the header and wrap any defining invocation with
#define
and #undef
:
#define DEFINE_VARIABLES
#include "file2c.h"
#undef DEFINE_VARIABLES
in the source code (so the headers never alter the value of
DEFINE_VARIABLES
), then you should be clean. It is just a nuisance to
have to remember to write the the extra line. An alternative might be:
#define HEADER_DEFINING_VARIABLES "file2c.h"
#include "externdef.h"
externdef.h
/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is included, the macro HEADER_DEFINING_VARIABLES should
** be defined with the name (in quotes - or possibly angle brackets) of
** the header to be included that defines variables when the macro
** DEFINE_VARIABLES is defined. See also: external.h (which uses
** DEFINE_VARIABLES and defines macros EXTERN and INITIALIZE
** appropriately).
**
** #define HEADER_DEFINING_VARIABLES "file2c.h"
** #include "externdef.h"
*/
#if defined(HEADER_DEFINING_VARIABLES)
#define DEFINE_VARIABLES
#include HEADER_DEFINING_VARIABLES
#undef DEFINE_VARIABLES
#undef HEADER_DEFINING_VARIABLES
#endif /* HEADER_DEFINING_VARIABLES */
This is getting a tad convoluted, but seems to be secure (using the
file2d.h
, with no #undef DEFINE_VARIABLES
in the file2d.h
).
file7c.c
/* Declare variables */
#include "file2d.h"
/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"
/* Declare variables - again */
#include "file2d.h"
/* Define variables - again */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
file8c.h
/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE8C_H_DEFINITIONS)
#undef FILE8C_H_INCLUDED
#endif
#ifndef FILE8C_H_INCLUDED
#define FILE8C_H_INCLUDED
#include "external.h" /* Support macros EXTERN, INITIALIZE */
#include "file2d.h" /* struct oddball */
#if !defined(DEFINE_VARIABLES) || !defined(FILE8C_H_DEFINITIONS)
/* Global variable declarations / definitions */
EXTERN struct oddball another INITIALIZE({ 14, 34 });
#endif /* !DEFINE_VARIABLES || !FILE8C_H_DEFINITIONS */
/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE8C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */
#endif /* FILE8C_H_INCLUDED */
file8c.c
/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"
/* Define variables */
#define HEADER_DEFINING_VARIABLES "file8c.h"
#include "externdef.h"
int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }
The next two files complete the source for prog8
and prog9
:
prog8.c
#include "file2d.h"
#include <stdio.h>
int main(void)
{
use_them();
global_variable += 19;
use_them();
printf("Increment: %d\n", increment());
printf("Oddball: %d\n", oddball_value());
return 0;
}
file9c.c
#include "file2d.h"
#include <stdio.h>
void use_them(void)
{
printf("Global variable: %d\n", global_variable++);
oddball_struct.a += global_variable;
oddball_struct.b -= global_variable / 2;
}
prog8
uses prog8.c
, file7c.c
, file9c.c
.
prog9
uses prog8.c
, file8c.c
, file9c.c
.
However, the problems are relatively unlikely to occur in practice,
especially if you take the standard advice to
A
What are the best PHP input sanitizing functions?
function sanitize($string,$dbmin,$dbmax){
$string = preg_replace('#[^a-z0-9]#i', '', $string); //useful for strict cleanse, alphanumeric here
$string = mysqli_real_escape_string($con, $string); //get ready for db
if(strlen($string) > $dbmax || strlen($string) < $dbmin){
echo "reject_this"; exit();
}
return $string;
}
How to remove .html from URL?
I use this .htacess for removing .html extantion from my url site, please verify this is correct code:
RewriteEngine on
RewriteBase /
RewriteCond %{http://www.proofers.co.uk/new} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) /$1.html [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]+)\.html\ HTTP
RewriteRule ^([^.]+)\.html$ http://www.proofers.co.uk/new/$1 [R=301,L]
Change default text in input type="file"?
Here is how its done with bootstrap, only u should put the original input somewhere...idk
in head and delete the < br > if you have it, because its only hidden and its taking space anyway :)
_x000D_
_x000D_
<head> _x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<label for="file" button type="file" name="image" class="btn btn-secondary">Secondary</button> </label>_x000D_
_x000D_
<input type="file" id="file" name="image" value="Prebrskaj" style="visibility:hidden;">_x000D_
_x000D_
_x000D_
<footer>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
</footer>
_x000D_
_x000D_
_x000D_
MySQL 'Order By' - sorting alphanumeric correctly
Instead of trying to write some function and slow down the SELECT
query, I thought of another way of doing this...
Create an extra field in your database that holds the result from the following Class and when you insert a new row, run the field value that will be naturally sorted through this class and save its result in the extra field. Then instead of sorting by your original field, sort by the extra field.
String nsFieldVal = new NaturalSortString(getFieldValue(), 4).toString()
The above means:
- Create a NaturalSortString for the String returned from getFieldValue()
- Allow up to 4 bytes to store each character or number (4 bytes = ffff = 65535)
| field(32) | nsfield(161) |
a1 300610001
String sortString = new NaturalSortString(getString(), 4).toString()
import StringUtils;
/**
* Creates a string that allows natural sorting in a SQL database
* eg, 0 1 1a 2 3 3a 10 100 a a1 a1a1 b
*/
public class NaturalSortString {
private String inStr;
private int byteSize;
private StringBuilder out = new StringBuilder();
/**
* A byte stores the hex value (0 to f) of a letter or number.
* Since a letter is two bytes, the minimum byteSize is 2.
*
* 2 bytes = 00 - ff (max number is 255)
* 3 bytes = 000 - fff (max number is 4095)
* 4 bytes = 0000 - ffff (max number is 65535)
*
* For example:
* dog123 = 64,6F,67,7B and thus byteSize >= 2.
* dog280 = 64,6F,67,118 and thus byteSize >= 3.
*
* For example:
* The String, "There are 1000000 spots on a dalmatian" would require a byteSize that can
* store the number '1000000' which in hex is 'f4240' and thus the byteSize must be at least 5
*
* The dbColumn size to store the NaturalSortString is calculated as:
* > originalStringColumnSize x byteSize + 1
* The extra '1' is a marker for String type - Letter, Number, Symbol
* Thus, if the originalStringColumn is varchar(32) and the byteSize is 5:
* > NaturalSortStringColumnSize = 32 x 5 + 1 = varchar(161)
*
* The byteSize must be the same for all NaturalSortStrings created in the same table.
* If you need to change the byteSize (for instance, to accommodate larger numbers), you will
* need to recalculate the NaturalSortString for each existing row using the new byteSize.
*
* @param str String to create a natural sort string from
* @param byteSize Per character storage byte size (minimum 2)
* @throws Exception See the error description thrown
*/
public NaturalSortString(String str, int byteSize) throws Exception {
if (str == null || str.isEmpty()) return;
this.inStr = str;
this.byteSize = Math.max(2, byteSize); // minimum of 2 bytes to hold a character
setStringType();
iterateString();
}
private void setStringType() {
char firstchar = inStr.toLowerCase().subSequence(0, 1).charAt(0);
if (Character.isLetter(firstchar)) // letters third
out.append(3);
else if (Character.isDigit(firstchar)) // numbers second
out.append(2);
else // non-alphanumeric first
out.append(1);
}
private void iterateString() throws Exception {
StringBuilder n = new StringBuilder();
for (char c : inStr.toLowerCase().toCharArray()) { // lowercase for CASE INSENSITIVE sorting
if (Character.isDigit(c)) {
// group numbers
n.append(c);
continue;
}
if (n.length() > 0) {
addInteger(n.toString());
n = new StringBuilder();
}
addCharacter(c);
}
if (n.length() > 0) {
addInteger(n.toString());
}
}
private void addInteger(String s) throws Exception {
int i = Integer.parseInt(s);
if (i >= (Math.pow(16, byteSize)))
throw new Exception("naturalsort_bytesize_exceeded");
out.append(StringUtils.padLeft(Integer.toHexString(i), byteSize));
}
private void addCharacter(char c) {
//TODO: Add rest of accented characters
if (c >= 224 && c <= 229) // set accented a to a
c = 'a';
else if (c >= 232 && c <= 235) // set accented e to e
c = 'e';
else if (c >= 236 && c <= 239) // set accented i to i
c = 'i';
else if (c >= 242 && c <= 246) // set accented o to o
c = 'o';
else if (c >= 249 && c <= 252) // set accented u to u
c = 'u';
else if (c >= 253 && c <= 255) // set accented y to y
c = 'y';
out.append(StringUtils.padLeft(Integer.toHexString(c), byteSize));
}
@Override
public String toString() {
return out.toString();
}
}
For completeness, below is the StringUtils.padLeft
method:
public static String padLeft(String s, int n) {
if (n - s.length() == 0) return s;
return String.format("%0" + (n - s.length()) + "d%s", 0, s);
}
The result should come out like the following
-1
-a
0
1
1.0
1.01
1.1.1
1a
1b
9
10
10a
10ab
11
12
12abcd
100
a
a1a1
a1a2
a-1
a-2
áviacion
b
c1
c2
c12
c100
d
d1.1.1
e
Using PUT method in HTML form
According to the HTML standard, you can not. The only valid values for the method attribute are get
and post
, corresponding to the GET and POST HTTP methods. <form method="put">
is invalid HTML and will be treated like <form>
, i.e. send a GET request.
Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:
<form method="post" ...>
<input type="hidden" name="_method" value="put" />
...
Of course, this requires server-side unwrapping.
What's the difference between compiled and interpreted language?
Here is the Basic Difference between Compiler vs Interpreter Language.
Compiler Language
- Takes entire program as single input and converts it into object code which is stored in the file.
- Intermediate Object code is generated
- e.g: C,C++
- Compiled programs run faster because compilation is done before execution.
- Memory requirement is more due to the creation of object code.
- Error are displayed after the entire program is compiled
- Source code ---Compiler ---Machine Code ---Output
Interpreter Language:
- Takes single instruction as single input and executes instructions.
- Intermediate Object code is NOT generated
- e.g: Perl, Python, Matlab
- Interpreted programs run slower because compilation and execution take place simultaneously.
- Memory requirement is less.
- Error are displayed for every single instruction.
- Source Code ---Interpreter ---Output
How to save a list to a file and read it as a list type?
What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:
mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
f.write("\n".join(mylist))
and then to open it and get your list again:
with open(myfile, 'r') as f:
mystring = f.read()
my_list = mystring.split("\n")
pandas create new column based on values from other columns / apply a function of multiple columns, row-wise
OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:
def label_race (row):
if row['eri_hispanic'] == 1 :
return 'Hispanic'
if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
return 'Two Or More'
if row['eri_nat_amer'] == 1 :
return 'A/I AK Native'
if row['eri_asian'] == 1:
return 'Asian'
if row['eri_afr_amer'] == 1:
return 'Black/AA'
if row['eri_hawaiian'] == 1:
return 'Haw/Pac Isl.'
if row['eri_white'] == 1:
return 'White'
return 'Other'
You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".
Next, use the apply function in pandas to apply the function - e.g.
df.apply (lambda row: label_race(row), axis=1)
Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:
0 White
1 Hispanic
2 White
3 White
4 Other
5 White
6 Two Or More
7 White
8 Haw/Pac Isl.
9 White
If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.
df['race_label'] = df.apply (lambda row: label_race(row), axis=1)
The resultant dataframe looks like this (scroll to the right to see the new column):
lname fname rno_cd eri_afr_amer eri_asian eri_hawaiian eri_hispanic eri_nat_amer eri_white rno_defined race_label
0 MOST JEFF E 0 0 0 0 0 1 White White
1 CRUISE TOM E 0 0 0 1 0 0 White Hispanic
2 DEPP JOHNNY NaN 0 0 0 0 0 1 Unknown White
3 DICAP LEO NaN 0 0 0 0 0 1 Unknown White
4 BRANDO MARLON E 0 0 0 0 0 0 White Other
5 HANKS TOM NaN 0 0 0 0 0 1 Unknown White
6 DENIRO ROBERT E 0 1 0 0 0 1 White Two Or More
7 PACINO AL E 0 0 0 0 0 1 White White
8 WILLIAMS ROBIN E 0 0 1 0 0 0 White Haw/Pac Isl.
9 EASTWOOD CLINT E 0 0 0 0 0 1 White White
trace a particular IP and port
Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.
You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).
Attempt to set a non-property-list object as an NSUserDefaults
I had this problem trying save a dictionary to NSUserDefaults
. It turns out it wouldn't save because it contained NSNull
values. So I just copied the dictionary into a mutable dictionary removed the nulls then saved to NSUserDefaults
NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary_trying_to_save];
[dictionary removeObjectForKey:@"NullKey"];
[[NSUserDefaults standardUserDefaults] setObject:dictionary forKey:@"key"];
In this case I knew which keys might be NSNull
values.
casting int to char using C++ style casting
You should use static_cast<char>(i)
to cast the integer i
to char
.
reinterpret_cast
should almost never be used, unless you want to cast one type into a fundamentally different type.
Also reinterpret_cast
is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.
For more information about C++ casting see:
how to create a login page when username and password is equal in html
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
- The password needs to be hashed
- The hashed password is used as part of a new url
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
Set focus on TextBox in WPF from view model
Nobody seems to have included the final step to make it easy to update attributes via binded variables. Here's what I came up with. Let me know if there is a better way of doing this.
XAML
<TextBox x:Name="txtLabel"
Text="{Binding Label}"
local:FocusExtension.IsFocused="{Binding txtLabel_IsFocused, Mode=TwoWay}"
/>
<Button x:Name="butEdit" Content="Edit"
Height="40"
IsEnabled="{Binding butEdit_IsEnabled}"
Command="{Binding cmdCapsuleEdit.Command}"
/>
ViewModel
public class LoginModel : ViewModelBase
{
public string txtLabel_IsFocused { get; set; }
public string butEdit_IsEnabled { get; set; }
public void SetProperty(string PropertyName, string value)
{
System.Reflection.PropertyInfo propertyInfo = this.GetType().GetProperty(PropertyName);
propertyInfo.SetValue(this, Convert.ChangeType(value, propertyInfo.PropertyType), null);
OnPropertyChanged(PropertyName);
}
private void Example_function(){
SetProperty("butEdit_IsEnabled", "False");
SetProperty("txtLabel_IsFocused", "True");
}
}
How to drop a table if it exists?
I use:
if exists (select *
from sys.tables
where name = 'tableName'
and schema_id = schema_id('dbo'))
begin
drop table dbo.tableName
end
Get program execution time in the shell
If you intend to use the times later to compute with, learn how to use the -f
option of /usr/bin/time
to output code that saves times. Here's some code I used recently to get and sort the execution times of a whole classful of students' programs:
fmt="run { date = '$(date)', user = '$who', test = '$test', host = '$(hostname)', times = { user = %U, system = %S, elapsed = %e } }"
/usr/bin/time -f "$fmt" -o $timefile command args...
I later concatenated all the $timefile
files and pipe the output into a Lua interpreter. You can do the same with Python or bash or whatever your favorite syntax is. I love this technique.
How can I represent a range in Java?
For a range of Comparable
I use the following :
public class Range<T extends Comparable<T>> {
/**
* Include start, end in {@link Range}
*/
public enum Inclusive {START,END,BOTH,NONE }
/**
* {@link Range} start and end values
*/
private T start, end;
private Inclusive inclusive;
/**
* Create a range with {@link Inclusive#START}
* @param start
*<br/> Not null safe
* @param end
*<br/> Not null safe
*/
public Range(T start, T end) { this(start, end, null); }
/**
* @param start
*<br/> Not null safe
* @param end
*<br/> Not null safe
*@param inclusive
*<br/>If null {@link Inclusive#START} used
*/
public Range(T start, T end, Inclusive inclusive) {
if((start == null) || (end == null)) {
throw new NullPointerException("Invalid null start / end value");
}
setInclusive(inclusive);
if( isBigger(start, end) ) {
this.start = end; this.end = start;
}else {
this.start = start; this.end = end;
}
}
/**
* Convenience method
*/
public boolean isBigger(T t1, T t2) { return t1.compareTo(t2) > 0; }
/**
* Convenience method
*/
public boolean isSmaller(T t1, T t2) { return t1.compareTo(t2) < 0; }
/**
* Check if this {@link Range} contains t
*@param t
*<br/>Not null safe
*@return
*false for any value of t, if this.start equals this.end
*/
public boolean contains(T t) { return contains(t, inclusive); }
/**
* Check if this {@link Range} contains t
*@param t
*<br/>Not null safe
*@param inclusive
*<br/>If null {@link Range#inclusive} used
*@return
*false for any value of t, if this.start equals this.end
*/
public boolean contains(T t, Inclusive inclusive) {
if(t == null) {
throw new NullPointerException("Invalid null value");
}
inclusive = (inclusive == null) ? this.inclusive : inclusive;
switch (inclusive) {
case NONE:
return ( isBigger(t, start) && isSmaller(t, end) );
case BOTH:
return ( ! isBigger(start, t) && ! isBigger(t, end) ) ;
case START: default:
return ( ! isBigger(start, t) && isBigger(end, t) ) ;
case END:
return ( isBigger(t, start) && ! isBigger(t, end) ) ;
}
}
/**
* Check if this {@link Range} contains other range
* @return
* false for any value of range, if this.start equals this.end
*/
public boolean contains(Range<T> range) {
return contains(range.start) && contains(range.end);
}
/**
* Check if this {@link Range} intersects with other range
* @return
* false for any value of range, if this.start equals this.end
*/
public boolean intersects(Range<T> range) {
return contains(range.start) || contains(range.end);
}
/**
* Get {@link #start}
*/
public T getStart() { return start; }
/**
* Set {@link #start}
* <br/>Not null safe
* <br/>If start > end they are switched
*/
public Range<T> setStart(T start) {
if(start.compareTo(end)>0) {
this.start = end;
this.end = start;
}else {
this.start = start;
}
return this;
}
/**
* Get {@link #end}
*/
public T getEnd() { return end; }
/**
* Set {@link #end}
* <br/>Not null safe
* <br/>If start > end they are switched
*/
public Range<T> setEnd(T end) {
if(start.compareTo(end)>0) {
this.end = start;
this.start = end;
}else {
this.end = end;
}
return this;
}
/**
* Get {@link #inclusive}
*/
public Inclusive getInclusive() { return inclusive; }
/**
* Set {@link #inclusive}
* @param inclusive
*<br/>If null {@link Inclusive#START} used
*/
public Range<T> setInclusive(Inclusive inclusive) {
this.inclusive = (inclusive == null) ? Inclusive.START : inclusive;
return this;
}
}
(This is a somewhat shorted version. The full code is available here )
Call japplet from jframe
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
How to sort an array of objects in Java?
With Java 8, you can use a reference method.
You could add compare
method to your Book
class
class Book {
public static int compare(Book a, Book b)
{
return a.name.compareTo(b.name);
}
}
And then you could do this :
Arrays.sort(books , Book::compare);
Here is the full example:
class Book {
String name;
String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public static int compareBooks(Book a , Book b)
{
return a.name.compareTo(b.name);
}
@Override
public String toString() {
return "name : " + name + "\t" + "author : " + author;
}
public static void main(String[] args) {
Book[] books = {
new Book("Book 3" , "Author 1"),
new Book("Book 2" , "Author 2"),
new Book("Book 1" , "Author 3"),
new Book("Book 4" , "Author 4")
};
Arrays.sort(books , Book::compareBooks);
Arrays.asList(books).forEach(System.out::println);
}
}
How to find the remainder of a division in C?
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
How do I print my Java object without getting "SomeType@2f92e0f4"?
Every class in Java has the toString()
method in it by default, which is called if you pass some object of that class to System.out.println()
. By default, this call returns the className@hashcode of that object.
{
SomeClass sc = new SomeClass();
// Class @ followed by hashcode of object in Hexadecimal
System.out.println(sc);
}
You can override the toString method of a class to get different output. See this example
class A {
String s = "I am just a object";
@Override
public String toString()
{
return s;
}
}
class B {
public static void main(String args[])
{
A obj = new A();
System.out.println(obj);
}
}
Get the current cell in Excel VB
I realize this doesn't directly apply from the title of the question, However some ways to deal with a variable range could be to select the range each time the code runs -- especially if you are interested in a user-selected range. If you are interested in that option, you can use the Application.InputBox (official documentation page here). One of the optional variables is 'type'. If the type is set equal to 8, the InputBox also has an excel-style range selection option. An example of how to use it in code would be:
Dim rng as Range
Set rng = Application.InputBox(Prompt:= "Please select a range", Type:=8)
Note:
If you assign the InputBox value to a none-range variable (without the Set
keyword), instead of the ranges, the values from the ranges will be assigned, as in the code below (although selecting multiple ranges in this situation may require the values to be assigned to a variant):
Dim str as String
str = Application.InputBox(Prompt:= "Please select a range", Type:=8)
matrix multiplication algorithm time complexity
The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).
There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.
See this wikipedia article on Matrix Multiplication for more information.
Getting multiple keys of specified value of a generic Dictionary?
Okay, here's the multiple bidirectional version:
using System;
using System.Collections.Generic;
using System.Text;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();
IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();
private static IList<TFirst> EmptyFirstList = new TFirst[0];
private static IList<TSecond> EmptySecondList = new TSecond[0];
public void Add(TFirst first, TSecond second)
{
IList<TFirst> firsts;
IList<TSecond> seconds;
if (!firstToSecond.TryGetValue(first, out seconds))
{
seconds = new List<TSecond>();
firstToSecond[first] = seconds;
}
if (!secondToFirst.TryGetValue(second, out firsts))
{
firsts = new List<TFirst>();
secondToFirst[second] = firsts;
}
seconds.Add(second);
firsts.Add(first);
}
// Note potential ambiguity using indexers (e.g. mapping from int to int)
// Hence the methods as well...
public IList<TSecond> this[TFirst first]
{
get { return GetByFirst(first); }
}
public IList<TFirst> this[TSecond second]
{
get { return GetBySecond(second); }
}
public IList<TSecond> GetByFirst(TFirst first)
{
IList<TSecond> list;
if (!firstToSecond.TryGetValue(first, out list))
{
return EmptySecondList;
}
return new List<TSecond>(list); // Create a copy for sanity
}
public IList<TFirst> GetBySecond(TSecond second)
{
IList<TFirst> list;
if (!secondToFirst.TryGetValue(second, out list))
{
return EmptyFirstList;
}
return new List<TFirst>(list); // Create a copy for sanity
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
greek.Add(5, "Beta");
ShowEntries(greek, "Alpha");
ShowEntries(greek, "Beta");
ShowEntries(greek, "Gamma");
}
static void ShowEntries(BiDictionary<int, string> dict, string key)
{
IList<int> values = dict[key];
StringBuilder builder = new StringBuilder();
foreach (int value in values)
{
if (builder.Length != 0)
{
builder.Append(", ");
}
builder.Append(value);
}
Console.WriteLine("{0}: [{1}]", key, builder);
}
}
How Do I Take a Screen Shot of a UIView?
I have created usable extension for UIView to take screenshot in Swift:
extension UIView{
var screenshot: UIImage{
UIGraphicsBeginImageContext(self.bounds.size);
let context = UIGraphicsGetCurrentContext();
self.layer.renderInContext(context)
let screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenShot
}
}
To use it just type:
let screenshot = view.screenshot
Can I set a breakpoint on 'memory access' in GDB?
I just tried the following:
$ cat gdbtest.c
int abc = 43;
int main()
{
abc = 10;
}
$ gcc -g -o gdbtest gdbtest.c
$ gdb gdbtest
...
(gdb) watch abc
Hardware watchpoint 1: abc
(gdb) r
Starting program: /home/mweerden/gdbtest
...
Old value = 43
New value = 10
main () at gdbtest.c:6
6 }
(gdb) quit
So it seems possible, but you do appear to need some hardware support.
Background thread with QThread in PyQt
According to the Qt developers, subclassing QThread is incorrect (see http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/). But that article is really hard to understand (plus the title is a bit condescending). I found a better blog post that gives a more detailed explanation about why you should use one style of threading over another: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
In my opinion, you should probably never subclass thread with the intent to overload the run method. While that does work, you're basically circumventing how Qt wants you to work. Plus you'll miss out on things like events and proper thread safe signals and slots. Plus as you'll likely see in the above blog post, the "correct" way of threading forces you to write more testable code.
Here's a couple of examples of how to take advantage of QThreads in PyQt (I posted a separate answer below that properly uses QRunnable and incorporates signals/slots, that answer is better if you have a lot of async tasks that you need to load balance).
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
finished = QtCore.pyqtSignal()
dataReady = QtCore.pyqtSignal(list, dict)
@QtCore.pyqtSlot()
def processA(self):
print "Worker.processA()"
self.finished.emit()
@QtCore.pyqtSlot(str, list, list)
def processB(self, foo, bar=None, baz=None):
print "Worker.processB()"
for thing in bar:
# lots of processing...
self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
self.finished.emit()
class Thread(QtCore.QThread):
"""Need for PyQt4 <= 4.6 only"""
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
# this class is solely needed for these two methods, there
# appears to be a bug in PyQt 4.6 that requires you to
# explicitly call run and start from the subclass in order
# to get the thread to actually start an event loop
def start(self):
QtCore.QThread.start(self)
def run(self):
QtCore.QThread.run(self)
app = QtGui.QApplication(sys.argv)
thread = Thread() # no parent!
obj = Worker() # no parent!
obj.moveToThread(thread)
# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)
# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread. As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.start()
# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
QtCore.Q_ARG(str, "Hello World!"),
QtCore.Q_ARG(list, ["args", 0, 1]),
QtCore.Q_ARG(list, []))
# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls. Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking
app.exec_()
# Without this you may get weird QThread messages in the shell on exit
app.deleteLater()
_tkinter.TclError: no display name and no $DISPLAY environment variable
I want to add an answer here that noone has explicitly stated with implementation.
This is a great resource to refer to for this failure:
https://matplotlib.org/faq/usage_faq.html
In my case, using matplotlib.use
did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:
export MPLBACKEND=Agg
This takes care of the issue.
My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest
, however would fail when using parallelism
along with circleci tests split
feature. However, declaring this env variable resolved the issue.
How do I find the size of a struct?
This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment.
Delete entire row if cell contains the string X
This was alluded to in another comment, but you could try something like this.
Sub FilterAndDelete()
Application.DisplayAlerts = False
With Sheet1 'Change this to your sheet name
.AutoFilterMode = False
.Range("A3:K3").AutoFilter
.Range("A3:K3").AutoFilter Field:=5, Criteria1:="none"
.UsedRange.Offset(1, 0).Resize(ActiveSheet.UsedRange.Rows.Count - 1).Rows.Delete
End With
Application.DisplayAlerts = True
End Sub
I haven't tested this and it is from memory, so it may require some tweaking but it should get the job done without looping through thousands of rows. You'll need to remove the 11-Jul so that UsedRange
is correct or change the offset to 2 rows instead of 1 in the .Offset(1,0)
.
Generally, before I do .Delete
I will run the macro with .Select
instead of the Delete that way I can be sure the correct range will be deleted, that may be worth doing to check to ensure the appropriate range is being deleted.
Read file line by line in PowerShell
I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
Handling onchange event in HTML.DropDownList Razor MVC
Description
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
Sample
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
More Information
OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted
Same error
Installing collected packages: six, pyparsing, packaging, appdirs, setuptools
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
**kwargs
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
isolated=self.isolated,
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
clobber(source, lib_dir, True)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber
shutil.copyfile(srcfile, destfile)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/six.py'
and here I use --user
without sudo
to solve this issue
$ pip install --user scikit-image h5py keras pygame
Collecting scikit-image
Downloading http://mirrors.aliyun.com/pypi/packages/65/69/27a1d55ce8f77c8ac757938707105b1070ff4f2ae47d2dc99461bfae4491/scikit_image-0.13.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (28.1MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 28.1MB 380kB/s
Collecting h5py
Downloading http://mirrors.aliyun.com/pypi/packages/b7/cc/1c29b0815b12de2c92b5323cad60f724ac8f0e39d0166d0b9dfacbcb70dd/h5py-2.7.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 4.5MB 503kB/s
Requirement already satisfied: keras in /Library/Python/2.7/site-packages
Requirement already satisfied: pygame in /Library/Python/2.7/site-packages
Requirement already satisfied: matplotlib>=1.3.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scikit-image)
Requirement already satisfied: six>=1.7.3 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: pillow>=2.1.0 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: networkx>=1.8 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: PyWavelets>=0.4.0 in /Library/Python/2.7/site-packages (from scikit-image)
Collecting scipy>=0.17.0 (from scikit-image)
Downloading http://mirrors.aliyun.com/pypi/packages/72/eb/d398b9f63ee936575edc62520477d6c2353ed013bacd656bd0c8bc1d0fa7/scipy-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (16.2MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 16.2MB 990kB/s
Requirement already satisfied: numpy>=1.7 in /Library/Python/2.7/site-packages (from h5py)
Requirement already satisfied: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: tornado in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: pyparsing>=1.5.6 in /Users/qiuwei/Library/Python/2.7/lib/python/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: nose in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: olefile in /Library/Python/2.7/site-packages (from pillow>=2.1.0->scikit-image)
Requirement already satisfied: decorator>=3.4.0 in /Library/Python/2.7/site-packages (from networkx>=1.8->scikit-image)
Requirement already satisfied: singledispatch in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: certifi in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: backports_abc>=0.4 in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Installing collected packages: scipy, scikit-image, h5py
Successfully installed h5py-2.7.0 scikit-image-0.13.0 scipy-0.19.0
Hope it will help someone who encounter similar issue!
Bytes of a string in Java
The pedantic answer (though not necessarily the most useful one, depending on what you want to do with the result) is:
string.length() * 2
Java strings are physically stored in UTF-16BE
encoding, which uses 2 bytes per code unit, and String.length()
measures the length in UTF-16 code units, so this is equivalent to:
final byte[] utf16Bytes= string.getBytes("UTF-16BE");
System.out.println(utf16Bytes.length);
And this will tell you the size of the internal char
array, in bytes.
Note: "UTF-16"
will give a different result from "UTF-16BE"
as the former encoding will insert a BOM, adding 2 bytes to the length of the array.
ViewDidAppear is not called when opening app from background
As per Apple's documentation:
(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;
Description:
Tells a child controller its appearance is about to change.
If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:
, viewWillDisappear:
, viewDidAppear:
, or viewDidDisappear:
directly.
(void)endAppearanceTransition;
Description:
Tells a child controller its appearance has changed.
If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.
Sample code:
(void)applicationDidEnterBackground:(UIApplication *)application
{
[self.window.rootViewController beginAppearanceTransition: NO animated: NO]; // I commented this line
[self.window.rootViewController endAppearanceTransition]; // I commented this line
}
Question: How I fixed?
Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.
Specify the from user when sending email using the mail command
I faced the same issue. But i solved the problem just be setting geko field in /ect/passwd field. Postfix by default send the mail from user login. Lets suppose you want to change from field to Alert. You just need to edit /ect/passwd file in any editor you like.
- vim /ect/passwd
root:x:0:0:Alerts:/root:/bin/bash
- Restart postfix.
Now check the result.
- echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected]
Now in recipient. From will be shown as Alerts as you have specified in geko field.
Hope this solution works for you.
textarea character limit
This works on keyup and paste, it colors the text red when you are almost up to the limit, truncates it when you go over and alerts you to edit your text, which you can do.
var t2= /* textarea reference*/
t2.onkeyup= t2.onpaste= function(e){
e= e || window.event;
var who= e.target || e.srcElement;
if(who){
var val= who.value, L= val.length;
if(L> 175){
who.style.color= 'red';
}
else who.style.color= ''
if(L> 180){
who.value= who.value.substring(0, 175);
alert('Your message is too long, please shorten it to 180 characters or less');
who.style.color= '';
}
}
}
std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?
As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.
There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.
Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:
- std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
- std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)
I can't understand why this JAXB IllegalAnnotationException is thrown
I can't understand why this JAXB IllegalAnnotationException is thrown
I also was getting the ### counts of IllegalAnnotationExceptions
exception and it seemed to be due to an improper dependency hierarchy in my Spring wiring.
I figured it out by putting a breakpoint in the JAXB code when it does the throw. For me this was at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check()
. Then I dumped the list
variable which gives something like:
[org.mortbay.jetty.Handler is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at org.mortbay.jetty.Handler
at public org.mortbay.jetty.Handler[] org.mortbay.jetty.handler.HandlerCollection.getHandlers()
at org.mortbay.jetty.handler.HandlerCollection
at org.mortbay.jetty.handler.ContextHandlerCollection
at com.mprew.ec2.commons.server.LocalContextHandlerCollection
at private com.mprew.ec2.commons.server.LocalContextHandlerCollection com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection.arg0
at com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection,
org.mortbay.jetty.Handler does not have a no-arg default constructor.]
....
The does not have a no-arg default constructor
seemed to me to be misleading. Maybe I wasn't understanding what the exception was saying. But it did indicate that there was a problem with my LocalContextHandlerCollection
. I removed a dependency loop and the error cleared.
Hopefully this will be helpful to others.
How do I measure separate CPU core usage for a process?
You can use:
mpstat -P ALL 1
It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):
10:54:41 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
10:54:42 PM all 8.20 0.12 0.75 0.00 0.00 0.00 0.00 0.00 90.93
10:54:42 PM 0 24.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 74.00
10:54:42 PM 1 22.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 76.00
10:54:42 PM 2 2.02 1.01 0.00 0.00 0.00 0.00 0.00 0.00 96.97
10:54:42 PM 3 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00
10:54:42 PM 4 14.15 0.00 1.89 0.00 0.00 0.00 0.00 0.00 83.96
10:54:42 PM 5 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.00
10:54:42 PM 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
10:54:42 PM 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.
Fragment Inside Fragment
Curently in nested fragment, the nested one(s) are only supported if they are generated programmatically! So at this time no nested fragment layout are supported in xml layout scheme!
Mapping list in Yaml to list of objects in Spring Boot
The reason must be somewhere else. Using only Spring Boot 1.2.2 out of the box with no configuration, it Just Works. Have a look at this repo - can you get it to break?
https://github.com/konrad-garus/so-yaml
Are you sure the YAML file looks exactly the way you pasted? No extra whitespace, characters, special characters, mis-indentation or something of that sort? Is it possible you have another file elsewhere in the search path that is used instead of the one you're expecting?
How can I determine if an image has loaded, using Javascript/jQuery?
As per one of the recent comments to your original question
$(function() {
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size() {
if (!$("#photo").get(0).complete) {
$("#photo").load(function() {
adjust_photo_size();
});
} else {
...
}
});
Warning This answer could cause a serious loop in ie8 and lower, because img.complete is not always properly set by the browser. If you must support ie8, use a flag to remember the image is loaded.
Where is android_sdk_root? and how do I set it.?
This is how to change it :
Step 1 :
Open a Terminal / CMD As Administrator (Right-click on cmd and click "Run as Administrator")
Step 2:
type in " set ANDROID_SDK_ROOT=E:\Android\sdk\ " (type it without the quotes and replace "E:\Android\sdk" with your actual sdk file path location - Mine was : C:\Users\YOUR_ACCOUNT\AppData\Local\Android\Sdk
step 3:
Press "Enter" and i noticed nothing happened
Step 4:
Build your app again and it should reflect your file path.
For me it doisplayed as :
Preparing Firebase on Android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=C:\Users\Kurt\AppData\Local\Android\Sdk (recommended setting)
ANDROID_HOME=C:\Users\Kurt\AppData\Local\Android\Sdk (DEPRECATED)
Subproject Path: CordovaLib
Subproject Path: app
I got that info from this site :
https://developer.android.com/studio/command-line/variables#android_sdk_root
Check it out for more information
Have Fun!!
Vue is not defined
Sometimes the problem may be if you import
that like this:
const Vue = window.vue;
this may overwrite the original Vue
reference.
sys.stdin.readline() reads without prompt, returning 'nothing in between'
stdin.read(1)
reads one character from stdin
. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read()
or readline()
.
As an example, given rd.py
:
from sys import stdin
x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)
... if I run this script as follows (I've typed in the 234
):
C:\>python rd.py
234
x= 2
userinput= 34
betAmount= 34
... so the 2
is being picked up first, leaving the 34
and the trailing newline character to be picked up by the readline()
.
I'd suggest fixing the problem by using readline()
rather than read()
under most circumstances.
How do I check form validity with angularjs?
form
- directive in module ng
Directive that instantiates FormController.
If the name attribute is specified, the form controller is published onto the current scope under this name.
Alias: ngForm
In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.
CSS classes
ng-valid is set if the form is valid.
ng-invalid is set if the form is invalid.
ng-pristine is set if the form is pristine.
ng-dirty is set if the form is dirty.
ng-submitted is set if the form was submitted.
Keep in mind that ngAnimate can detect each of these classes when added and removed.
Submitting a form and preventing the default action
Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.
For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.
This is because of the following form submission rules in the HTML specification:
If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
if a form has 2+ input fields and no buttons or input[type=submit]
then hitting enter doesn't trigger submit
if a form has one or more input fields and one or more buttons or input[type=submit]
then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit]
(ngClick) and a submit handler on the enclosing form (ngSubmit).
Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.
Use ngSubmit to have access to the updated model.
app.js:
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
Form:
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span>
userType = {{userType}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
myForm.$error.required = {{!!myForm.$error.required}}
</form>
Source: AngularJS: API: form
Java Project: Failed to load ApplicationContext
Looks like you are using maven (src/main/java)
. In this case put the applicationContext.xml
file in the src/main/resources
directory. It will be copied in the classpath directory and you should be able to access it with
@ContextConfiguration("/applicationContext.xml")
From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".
So it's important that you add the slash when referencing the file in the root directory of the classpath.
If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).
How to change the color of a SwitchCompat from AppCompat library
<android.support.v7.widget.SwitchCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/adamSwitch"
android:textColor="@color/top_color"
android:textAppearance="@color/top_color"
android:gravity="center"
app:showText="true"
app:theme="@style/Custom.Widget.SwitchCompat"
app:switchPadding="5dp"
/>
in style.xml
<style name="Custom.Widget.SwitchCompat" parent="Widget.AppCompat.CompoundButton.Switch" >
<item name="android:textColorPrimary">@color/blue</item> <!--textColor on activated state -->
</style>
draw diagonal lines in div background with CSS
All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:
_x000D_
_x000D_
.crossed {_x000D_
position: relative;_x000D_
width: 300px;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 1px;_x000D_
bottom: 1px;_x000D_
border-width: 149px;_x000D_
border-style: solid;_x000D_
border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 1px;_x000D_
right: 1px;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
border-width: 149px;_x000D_
border-style: solid;_x000D_
border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_
Explanation, as requested:
Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:
_x000D_
_x000D_
.borders {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background-color: black;_x000D_
border-width: 40px;_x000D_
border-style: solid;_x000D_
border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_
To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:
_x000D_
_x000D_
.r1 { width: 10px;_x000D_
height: 0;_x000D_
border-width: 40px;_x000D_
border-style: solid;_x000D_
border-color: red blue;_x000D_
margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
height: 10px;_x000D_
border-width: 40px;_x000D_
border-style: solid;_x000D_
border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_
Finally, use the :before
and :after
pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.
Linq : select value in a datatable column
If the return value is string and you need to search by Id you can use:
string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();
or using generic variable:
var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));
Unable to connect PostgreSQL to remote database using pgAdmin
Connecting to PostgreSQL via SSH Tunneling
In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:
- Open PuTTY. If you already have a session set up to connect to the
EC2 instance, load that, but don't connect to it just yet. If you
don't have such a session, see this post.
- Go to Connection > SSH > Tunnels
- Enter 5433 in the Source Port field.
- Enter 127.0.0.1:5432 in the Destination field.
- Click the "Add" button.
- Go back to Session, and save your session, then click "Open" to
connect.
- This opens a terminal window. Once you're connected, you can leave
that alone.
- Open pgAdmin and add a connection.
- Enter localhost in the Host field and 5433 in the Port field.
Specify a Name for the connection, and the username and password.
Click OK when you're done.
What is the JavaScript version of sleep()?
This will do you the trick.
var reloadAfter = 10; //seconds
var intervalId = setTimeout(function() {
//code you want to execute after the time waiting
}, reloadAfter * 1000); // 60000 = 60 sec = 1 min
How to do fade-in and fade-out with JavaScript and CSS
Here is a more efficient way of fading out an element:
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
you can do the reverse for fade in
setInterval or setTimeout should not get a string as argument
google the evils of eval to know why
And here is a more efficient way of fading in an element.
function unfade(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
Python equivalent of a given wget command
easy as py:
class Downloder():
def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
#threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
return True
else:
return False
def _wget_dl(self,url, destination, try_number, time_out):
import subprocess
command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
try:
download_state=subprocess.call(command)
except Exception as e:
print(e)
#if download_state==0 => successfull download
return download_state
How to style UITextview to like Rounded Rect text field?
this code worked well for me:
[yourTextView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
[yourTextView.layer setBorderColor: [[UIColor grayColor] CGColor]];
[yourTextView.layer setBorderWidth: 1.0];
[yourTextView.layer setCornerRadius:8.0f];
[yourTextView.layer setMasksToBounds:YES];
How to calculate distance between two locations using their longitude and latitude value
public float getMesureLatLang(double lat,double lang) {
Location loc1 = new Location("");
loc1.setLatitude(getLatitute());// current latitude
loc1.setLongitude(getLangitute());//current Longitude
Location loc2 = new Location("");
loc2.setLatitude(lat);
loc2.setLongitude(lang);
return loc1.distanceTo(loc2);
// return distance(getLatitute(),getLangitute(),lat,lang);
}
How to convert CSV file to multiline JSON?
import csv
import json
file = 'csv_file_name.csv'
json_file = 'output_file_name.json'
#Read CSV File
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
convert_write_json(csv_rows, json_file)
#Convert csv data into json
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #for pretty
f.write(json.dumps(data))
read_CSV(file,json_file)
Documentation of json.dumps()
SSIS how to set connection string dynamically from a config file
First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName
In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:
"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName] + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"
This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.
php search array key and get value
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>