Why number 9 in kill -9 command in unix?
I think a better answer here is simply this:
mike@sleepycat:~? kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):
Each signal is defined as a unique (small) integer, starting
sequentially from 1. These integers are defined in with
symbolic names of the form SIGxxxx . Since the actual numbers used for
each signal vary across implementations, it is these symbolic names
that are always used in programs.
multiprocessing.Pool: When to use apply, apply_async or map?
Regarding apply
vs map
:
pool.apply(f, args)
: f
is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args)
.
pool.map(f, iterable)
: This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.
Items in JSON object are out of order using "json.dumps"?
As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: http://code.activestate.com/recipes/576693/ ).
I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm not sure (and I don't have easy access to test).
Old pythons simplejson implementations dont handle the OrderedDict objects nicely .. and convert them to regular dicts before outputting them.. but you can overcome this by doing the following:
class OrderedJsonEncoder( simplejson.JSONEncoder ):
def encode(self,o):
if isinstance(o,OrderedDict.OrderedDict):
return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
else:
return simplejson.JSONEncoder.encode(self, o)
now using this we get:
>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}
Which is pretty much as desired.
Another alternative would be to specialise the encoder to directly use your row class, and then you'd not need any intermediate dict or UnorderedDict.
ASP.NET MVC: What is the purpose of @section?
A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.
How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?
You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.
what exactly is device pixel ratio?
Device Pixel Ratio == CSS Pixel Ratio
In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.
A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:
For example:
Apple iPhone 6s
- Actual Resolution: 750 x 1334
- CSS Pixel Ratio: 2
- Logical Resolution:
When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.
Some other examples:
Samsung Galaxy S4
- Actual Resolution: 1080 x 1920
- CSS Pixel Ratio: 3
- Logical Resolution:
iPhone 5s
- Actual Resolution: 640 x 1136
- CSS Pixel Ratio: 2
- Logical Resolution:
Why does the Device Pixel Ratio exist?
The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.
A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.
So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.
Here is a tool that also tells you your current device's pixel density:
http://bjango.com/articles/min-device-pixel-ratio/
"Port 4200 is already in use" when running the ng serve command
Port 4200 is already in use. Use '--port' to specify a different port
This means that you already have another service running on port 4200. If this is the case
you can either . shut down the other service. use the --port
flag when running ng
serve like this:
ng serve --port 9001
Another thing to notice is that, on some machines, the domain localhost may not work.
You may see a set of numbers such as 127.0.0.1. When you run ng serve it should show
you what URL the server is running on, so be sure to read the messages on your machine
to find your exact development URL.
How to check if a folder exists
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
Oracle TNS names not showing when adding new connection to SQL Developer
The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether.
Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?
Eclipse Bug: Unhandled event loop exception No more handles
I have the same problem. It is caused by a screen capture software hypersnap7. So I think the hotkey conflict is the reason. Reboot computer, don't start other software, start Android Development Tools and watch which software triger the bug.
Formula to determine brightness of RGB color
The "Accepted" Answer is Incorrect and Incomplete
The only answers that are accurate are the @jive-dadson and @EddingtonsMonkey answers, and in support @nils-pipenbrinck. The other answers (including the accepted) are linking to or citing sources that are either wrong, irrelevant, obsolete, or broken.
Briefly:
- sRGB must be LINEARIZED before applying the coefficients.
- Luminance (L or Y) is linear as is light.
- Perceived lightness (L*) is nonlinear as is human perception.
- HSV and HSL are not even remotely accurate in terms of perception.
- The IEC standard for sRGB specifies a threshold of 0.04045 it is NOT 0.03928 (that was from an obsolete early draft).
- The be useful (i.e. relative to perception), Euclidian distances require a perceptually uniform Cartesian vector space such as CIELAB. sRGB is not one.
What follows is a correct and complete answer:
Because this thread appears highly in search engines, I am adding this answer to clarify the various misconceptions on the subject.
Luminance is a linear measure of light, spectrally weighted for normal vision but not adjusted for the non-linear perception of lightness. It can be a relative measure, Y as in CIEXYZ, or as L, an absolute measure in cd/m2 (not to be confused with L*
).
Perceived lightness is used by some vision models such as CIELAB, here L*
(Lstar) is a value of perceptual lightness, and is non-linear to approximate the human vision non-linear response curve.
Brightness is a perceptual attribute, it does not have a "physical" measure. However some color appearance models do have a value, usualy denoted as "Q" for perceived brightness, which is different than perceived lightness.
Luma (Y´ prime) is a gamma encoded, weighted signal used in some video encodings (Y´I´Q´). It is not to be confused with linear luminance.
Gamma or transfer curve (TRC) is a curve that is often similar to the perceptual curve, and is commonly applied to image data for storage or broadcast to reduce perceived noise and/or improve data utilization (and related reasons).
To determine perceived lightness, first convert gamma encoded R´G´B´ image values to linear luminance (L
or Y
) and then to non-linear perceived lightness (L*
)
TO FIND LUMINANCE:
...Because apparently it was lost somewhere...
Step One:
Convert all sRGB 8 bit integer values to decimal 0.0-1.0
vR = sR / 255;
vG = sG / 255;
vB = sB / 255;
Step Two:
Convert a gamma encoded RGB to a linear value. sRGB (computer standard) for instance requires a power curve of approximately V^2.2, though the "accurate" transform is:
Where V´ is the gamma-encoded R, G, or B channel of sRGB.
Pseudocode:
function sRGBtoLin(colorChannel) {
// Send this function a decimal sRGB gamma encoded color value
// between 0.0 and 1.0, and it returns a linearized value.
if ( colorChannel <= 0.04045 ) {
return colorChannel / 12.92;
} else {
return pow((( colorChannel + 0.055)/1.055),2.4));
}
}
Step Three:
To find Luminance (Y) apply the standard coefficients for sRGB:
Pseudocode using above functions:
Y = (0.2126 * sRGBtoLin(vR) + 0.7152 * sRGBtoLin(vG) + 0.0722 * sRGBtoLin(vB))
TO FIND PERCEIVED LIGHTNESS:
Step Four:
Take luminance Y from above, and transform to L*
Pseudocode:
function YtoLstar(Y) {
// Send this function a luminance value between 0.0 and 1.0,
// and it returns L* which is "perceptual lightness"
if ( Y <= (216/24389) { // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
return Y * (24389/27); // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
} else {
return pow(Y,(1/3)) * 116 - 16;
}
}
L* is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey". L* = 50 is the equivalent of Y = 18.4, or in other words an 18% grey card, representing the middle of a photographic exposure (Ansel Adams zone V).
References:
IEC 61966-2-1:1999 Standard
Wikipedia sRGB
Wikipedia CIELAB
Wikipedia CIEXYZ
Charles Poynton's Gamma FAQ
Django: save() vs update() to update the database?
Using update directly is more efficient and could also prevent integrity problems.
From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update
If you’re just updating a record and don’t need to do anything with
the model object, the most efficient approach is to call update(),
rather than loading the model object into memory. For example, instead
of doing this:
e = Entry.objects.get(id=10)
e.comments_on = False
e.save()
…do this:
Entry.objects.filter(id=10).update(comments_on=False)
Using update() also prevents a race condition wherein something might
change in your database in the short period of time between loading
the object and calling save().
CREATE DATABASE permission denied in database 'master' (EF code-first)
I encountered what appeared to be this error. I was running on windows and found my administrator windows user did not have administrator privileges to database.
- Shut down SQL Server from ‘Services’
- Open cmd window (as administrator) and run single-user mode as local admin with this command (the version of MSSQL may differ):
"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -m -s SQLEXPRESS
- Open another cmd window (as administrator)
- Open sqlcmd on that terminal with:
sqlcmd -S .\SQLEXPRESS
- Now add the sysadmin role to your user:
sp_addsrvrolemember 'domain\user', 'sysadmin'
GO
- Re-enable SQL Server from ‘Services’
Credit to:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/
Formatting code in Notepad++
No. Notepad++ can't format by itself. Formatting can easily be accomplished in many IDEs like Eclipse, NetBeans, Visual Studio [Code].
String variable interpolation Java
Note that there is no variable interpolation in Java.
Variable interpolation is variable substitution with its value inside a string.
An example in Ruby:
#!/usr/bin/ruby
age = 34
name = "William"
puts "#{name} is #{age} years old"
The Ruby interpreter automatically replaces variables with its values inside a string.
The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby,
it is #{}. In Perl, it could be $, % or @. Java would only print such characters,
it would not expand them.
Variable interpolation is not supported in Java. Instead of this, we
have string formatting.
package com.zetcode;
public class StringFormatting
{
public static void main(String[] args)
{
int age = 34;
String name = "William";
String output = String.format("%s is %d years old.", name, age);
System.out.println(output);
}
}
In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.
See http://en.wikipedia.org/wiki/Variable_interpolation
Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
However, still no string interpolation:
Non-Goals: …
Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method String::formatted
aids in situations where interpolation might be desired.
How to handle calendar TimeZones using Java?
java.time
The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes bundled with the earliest versions of Java.
The java.sql.Timestamp
class is one of those legacy classes. No longer needed. Instead use Instant
or other java.time classes directly with your database using JDBC 4.2 and later.
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If you must interoperate with an existing Timestamp
, convert immediately into java.time via the new conversion methods added to the old classes.
Instant instant = myTimestamp.toInstant() ;
To adjust into another time zone, specify the time zone as a ZoneId
object. Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter pseudo-zones such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Apply to the Instant
to produce a ZonedDateTime
object.
ZonedDateTime zdt = instant.atZone( z ) ;
To generate a string for display to the user, search Stack Overflow for DateTimeFormatter
to find many discussions and examples.
Your Question is really about going the other direction, from user data-entry to the date-time objects. Generally best to break your data-entry into two parts, a date and a time-of-day.
LocalDate ld = LocalDate.parse( dateInput , DateTimeFormatter.ofPattern( "M/d/uuuu" , Locale.US ) ) ;
LocalTime lt = LocalTime.parse( timeInput , DateTimeFormatter.ofPattern( "H:m a" , Locale.US ) ) ;
Your Question is not clear. Do you want to interpret the date and the time entered by the user to be in UTC? Or in another time zone?
If you meant UTC, create a OffsetDateTime
with an offset using the constant for UTC, ZoneOffset.UTC
.
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
If you meant another time zone, combine along with a time zone object, a ZoneId
. But which time zone? You might detect a default time zone. Or, if critical, you must confirm with the user to be certain of their intention.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
To get a simpler object that is always in UTC by definition, extract an Instant
.
Instant instant = odt.toInstant() ;
…or…
Instant instant = zdt.toInstant() ;
Send to your database.
myPreparedStatement.setObject( … , instant ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Google maps Marker Label with multiple characters
A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.
for (i = 0; i < locations.length; i++)
{
k = i + 1;
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});
--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.
How To have Dynamic SQL in MySQL Stored Procedure
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
How to search a specific value in all tables (PostgreSQL)?
How about dumping the contents of the database, then using grep
?
$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');
The same utility, pg_dump, can include column names in the output. Just change --inserts
to --column-inserts
. That way you can search for specific column names, too. But if I were looking for column names, I'd probably dump the schema instead of the data.
$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');
Convert/cast an stdClass object to another class
I have a very similar problem. Simplified reflection solution worked just fine for me:
public static function cast($destination, \stdClass $source)
{
$sourceReflection = new \ReflectionObject($source);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$name = $sourceProperty->getName();
$destination->{$name} = $source->$name;
}
return $destination;
}
Bootstrap full-width text-input within inline-form
As stated in a similar question, try removing instances of the input-group
class and see if that helps.
refering to bootstrap:
Individual form controls automatically receive some global styling.
All textual , , and elements with
.form-control are set to width: 100%; by default. Wrap labels and
controls in .form-group for optimum spacing.
How to read a .properties file which contains keys that have a period character using Shell script
I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.
What is RSS and VSZ in Linux memory management
I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up.
As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.
How can I restore the MySQL root user’s full privileges?
- "sudo cat /etc/mysql/debian.cnf" to use debian-sys-maint user
- login by this user throgh "mysql -u
saved-username
-p;", then enter the saved password.
- mysql> UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
- mysql> FLUSH PRIVILEGES;
- mysql> exit
- reboot
Thanks
How to determine if a string is a number with C++?
I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with
-?[0-9]+([\.][0-9]+)?
would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.
Other variations:
[0-9]+([\.][0-9]+)?
(only positive)
-?[0-9]+
(only integer)
[0-9]+
(only positive integer)
Read remote file with node.js (http.get)
I'd use request for this:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:
var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
var csv = body;
// Continue with your processing here.
}
});
etc.
for loop in Python
The answer is good, but for the people that want this with range()
, the form to do is:
range(end)
:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start,end)
:
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(start,end, step)
:
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
rawQuery(query, selectionArgs)
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
Component is not part of any NgModule or the module has not been imported into your module
In my case, Angular 6, I renamed folder and file names of my modules from google.map.module.ts to google-map.module.ts.
In order to compile without overlay with old module and component names, ng compiler compiled with no error.
In app.routes.ts:
{
path: 'calendar',
loadChildren: './views/app-calendar/app-calendar.module#AppCalendarModule',
data: { title: 'Calendar', breadcrumb: 'CALENDAR'}
},
In google-map.routing.ts
import { GoogleMapComponent } from './google-map.component';
const routes: Routes = [
{
path: '', component: GoogleMapComponent, data: { title: 'Coupon Map' }
}
];
@NgModule({
exports: [RouterModule],
imports: [RouterModule.forChild(routes)]
})
export class GoogleMapRoutingModule { }
In google-map.module.ts:
import { GoogleMapRoutingModule } from './google-map.routing';
@NgModule({
imports: [
CommonModule,
FormsModule,
CommonModule,
GoogleMapRoutingModule,
],
exports: [GoogleMapComponent],
declarations: [GoogleMapComponent]
})
export class GoogleMapModule { }
How do I calculate the normal vector of a line segment?
This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y')
is perpendicular to the line connecting (x1,y1)
and (x2,y2)
. This line has direction (x2-x1,y2-y1)
, or (dx,dy)
.
So,
(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0
The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx)
or (-dy,dx)
Determine the type of an object?
type()
is a better solution than isinstance()
, particularly for booleans
:
True
and False
are just keywords that mean 1
and 0
in python. Thus,
isinstance(True, int)
and
isinstance(False, int)
both return True
. Both booleans are an instance of an integer. type()
, however, is more clever:
type(True) == int
returns False
.
How to execute a file within the python interpreter?
I am not an expert but this is what I noticed:
if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter.
Phonegap Cordova installation Windows
I faced this same error too.
And i even tried downloading the PhoneGap master from GitHub,but i found out that what i got was Phonegap 2.9.
I eventually had to download the Cordova 3 Source
Follow this steps to get it.
- Download and unzip the Cordova 3 Source
- Run the template.bat in the cordova-wp8 folder
- Copy the generated Zip files to your Visual studio template folder
Insert a background image in CSS (Twitter Bootstrap)
Adding background image on html, body or a wrapper element to achieve background image will cause problems with padding. Check this ticket https://github.com/twitter/bootstrap/issues/3169 on github. ShaunR's comment and also one of the creators response to this. The given solution in created ticket doesn't solve the problem, but it at least gets things going if you aren't using responsive features.
Assuming that you are using container without responsive features, and have a width of 960px, and want to achieve 10px padding, you set:
.container {
min-width: 940px;
padding: 10px;
}
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3
I received the same error (SCRIPT7002: XMLHttpRequest: Network Error 0x80004004, Operation aborted
), in our case it was because of JavaScript's same origin policy.
Our web app was making a JQuery AJAX call to our server on Port 8080. The call was getting intercepted and re-routed over SSL (due to server rules mandating that incoming traffic use SSL).
Once we made our web app load through the SSL port the issue was fixed.
How to show validation message below each textbox using jquery?
This is the simple solution may work for you.
Check this solution
$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
$(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
$(this).prev(".validationText").hide();
});});
using javascript to detect whether the url exists before display in iframe
I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file
// if-url-exist.js v1
function ifUrlExist(url, callback) {
let request = new XMLHttpRequest;
request.open('GET', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Accept', '*/*');
request.onprogress = function(event) {
let status = event.target.status;
let statusFirstNumber = (status).toString()[0];
switch (statusFirstNumber) {
case '2':
request.abort();
return callback(true);
default:
request.abort();
return callback(false);
};
};
request.send('');
};
Example of use:
ifUrlExist(url, function(exists) {
console.log(exists);
});
Scala: write string to file in one statement
Through the magic of the semicolon, you can make anything you like a one-liner.
import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
, StandardCharsets.UTF_8
, StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()
Sharepoint: How do I filter a document library view to show the contents of a subfolder?
Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.
Check if TextBox is empty and return MessageBox?
For multiple text boxes - add them into a list and show all errors into 1 messagebox.
// Append errors into 1 Message Box
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(textBox1.Text))
{
errors.Add("User");
}
if (string.IsNullOrEmpty(textBox2.Text))
{
errors.Add("Document Ref Code");
}
if (errors.Count > 0)
{
errors.Insert(0, "The following fields are empty:");
string message = string.Join(Environment.NewLine, errors);
MessageBox.Show(message, "errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Where to put a textfile I want to use in eclipse?
One path to take is to
- Add the file you're working with to the classpath
Use the resource loader to locate the file:
URL url = Test.class.getClassLoader().getResource("myfile.txt");
System.out.println(url.getPath());
...
- Open it
How to open a web server port on EC2 instance
Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".
Go to the "Network & Security" -> Security Group settings in the left hand navigation
Find the Security Group that your instance is apart of
Click on Inbound Rules
Use the drop down and add HTTP (port 80)
Click Apply and enjoy
How to expand a list to function arguments in Python
You should use the * operator, like foo(*values)
Read the Python doc unpackaging argument lists.
Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z):
return "%d, %d, %d" % (x,y,z)
values = [1,2,3]
# the solution.
foo(*values)
Error creating bean with name 'entityManagerFactory
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere.
In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
What is an attribute in Java?
A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.
so you can have a class like Array
with a public attribute length
and a public method sort()
.
What are the true benefits of ExpandoObject?
The real benefit for me is the totally effortless data binding from XAML:
public dynamic SomeData { get; set; }
...
SomeData.WhatEver = "Yo Man!";
...
<TextBlock Text="{Binding SomeData.WhatEver}" />
Internal Error 500 Apache, but nothing in the logs?
Why are the 500 Internal Server Errors not being logged into your apache error logs?
The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it's a security hazard to log errors to screen where attackers can observe them.
These instructions to enable Internal Server Error Logging are for Ubuntu 12.10
with PHP 5.3.10
and Apache/2.2.22
.
Make sure PHP logging is turned on:
Locate your php.ini file:
el@apollo:~$ locate php.ini
/etc/php5/apache2/php.ini
Edit that file as root:
sudo vi /etc/php5/apache2/php.ini
Find this line in php.ini:
display_errors = Off
Change the above line to this:
display_errors = On
Lower down in the file you'll see this:
;display_startup_errors
; Default Value: Off
; Development Value: On
; Production Value: Off
;error_reporting
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
The semicolons are comments, that means the lines don't take effect. Change those lines so they look like this:
display_startup_errors = On
; Default Value: Off
; Development Value: On
; Production Value: Off
error_reporting = E_ALL
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don't want this enabled on production because logging takes work and work takes time, time costs money.
Restarting PHP and Apache should apply the change.
Do what you did to cause the 500 Internal Server error again, and check the log:
tail -f /var/log/apache2/error.log
You should see the 500 error at the end, something like this:
[Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:
Call to undefined function Foobar\\byob\\penguin\\alert() in /yourproject/
your_src/symfony/Controller/MessedUpController.php on line 249, referer:
https://nuclearreactor.com/abouttoblowup
How to pass parameters in $ajax POST?
$.ajax(
{
type: 'post',
url: 'superman',
data: {
"field1": "hello",
"field2": "hello1"
},
success: function (response) {
alert("Success !!");
},
error: function () {
alert("Error !!");
}
}
);
type: 'POST'
, will append **parameters to the body of the request** which is not seen in the URL while type: 'GET'
, appends parameters to the URL which is visible.
Most of the popular web browsers contain network panels which displays the complete request.
In network panel select XHR to see requests.
This can also be done via this.
$.post('superman',
{
'field1': 'hello',
'field2': 'hello1'
},
function (response) {
alert("Success !");
}
);
Inner join with count() on three tables
i tried putting distinct on both,
count(distinct ord.ord_id) as num_order,
count(distinct items.item_id) as num items
its working :)
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(distinct items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
Thanks for the Thread it helps :)
Javascript - How to show escape characters in a string?
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
Javascript Array.sort implementation?
try this with quick sort:
function sort(arr, compareFn = (a, b) => a <= b) {
if (!arr instanceof Array || arr.length === 0) {
return arr;
}
if (typeof compareFn !== 'function') {
throw new Error('compareFn is not a function!');
}
const partition = (arr, low, high) => {
const pivot = arr[low];
while (low < high) {
while (low < high && compareFn(pivot, arr[high])) {
--high;
}
arr[low] = arr[high];
while (low < high && compareFn(arr[low], pivot)) {
++low;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
};
const quickSort = (arr, low, high) => {
if (low < high) {
let pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
return arr;
};
return quickSort(arr, 0, arr.length - 1);
}
Launch Bootstrap Modal on page load
I recently needed to launch a Bootstrap 5 modal without jQuery and not with a button click (eg, on page load) using Django messages. This is how I did it:
Template/HTML
<div class="modal" id="notification">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Notification!</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
{% for m in messages %}
{{ m }}
{% endfor %}
</div>
<div class="modal-footer justify-content-between">
<a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
type="button">
Link/Button A
</a>
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">
Link/Button B
</button>
</div>
</div>
</div>
</div>
JS in a file or in the template
{% block javascript %}
{{ block.super }}
<script>
var test_modal = new bootstrap.Modal(
document.getElementById('notification')
)
test_modal.show()
</script>
{% endblock javascript %}
This method will work without the Django template; just use the HTML and put the JS in a file or script
elements that loads after the Bootstrap JS before the end of the body
element.
Setting a log file name to include current date in Log4j
DailyRollingFileAppender is what you exactly searching for.
<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="application.log" />
<param name="DatePattern" value=".yyyy-MM-dd" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n"/>
</layout>
</appender>
Git vs Team Foundation Server
For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...
How to find the remainder of a division in C?
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
Match whitespace but not newlines
m/ /g
just give space in / /
, and it will work. Or use \S
— it will replace all the special characters like tab, newlines, spaces, and so on.
Vue.JS: How to call function after page loaded?
// vue js provides us `mounted()`. this means `onload` in javascript.
mounted () {
// we can implement any method here like
sampleFun () {
// this is the sample method you can implement whatever you want
}
}
How do I correctly clean up a Python object?
I don't think that it's possible for instance members to be removed before __del__
is called. My guess would be that the reason for your particular AttributeError is somewhere else (maybe you mistakenly remove self.file elsewhere).
However, as the others pointed out, you should avoid using __del__
. The main reason for this is that instances with __del__
will not be garbage collected (they will only be freed when their refcount reaches 0). Therefore, if your instances are involved in circular references, they will live in memory for as long as the application run. (I may be mistaken about all this though, I'd have to read the gc docs again, but I'm rather sure it works like this).
Vue 2 - Mutating props vue-warn
You need to add computed method like this
component.vue
props: ['list'],
computed: {
listJson: function(){
return JSON.parse(this.list);
}
}
Why I get 'list' object has no attribute 'items'?
You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.
If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:
result_list = [[int(v) for k,v in d.items()] for d in qs]
Which is the same as:
result_list = []
for d in qs:
result_list.append([int(v) for k,v in d.items()])
The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:
result_list = [int(v) for d in qs for k,v in d.items()]
"Items collection must be empty before using ItemsSource."
I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.
<ItemsControl
Foreground="Black" Background="White" Grid.IsSharedSizingScope="True"
x:Name="MyGrid" ItemsSource="{Binding}">
>
<ItemsControl.ItemsPanel>
<!-- All is fine here -->
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<!-- All is fine here -->
</ItemsControl.ItemTemplate>
<!-- Have you caught the error yet? -->
</ItemsControl>
The bug? The extra > after the initial opening <ItemsControl>
tag! The <
got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.
Most efficient way to concatenate strings in JavaScript?
Seems based on benchmarks at JSPerf that using +=
is the fastest method, though not necessarily in every browser.
For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.
(Thanks @zAlbee for correction)
Printing leading 0's in C
printf("%05d", zipCode);
The 0
indicates what you are padding with and the 5
shows the width of the integer number.
Example 1: If you use "%02d"
(useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06
instead of 6
.
Example 2: "%03d"
would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007
and number 17 padded to 017
.
Dynamically add item to jQuery Select2 control that uses AJAX
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
// append option
$("#select_with_data").append('<option value="5">Twitter</option>');
$("#select_with_data").val('5');
$("#select_with_data").trigger('change');
Ping all addresses in network, windows
@ECHO OFF
IF "%SUBNET%"=="" SET SUBNET=10
:ARGUMENTS
ECHO SUBNET=%SUBNET%
ECHO ARGUMENT %1
IF "%1"=="SUM" GOTO SUM
IF "%1"=="SLOW" GOTO SLOW
IF "%1"=="ARP" GOTO ARP
IF "%1"=="FAST" GOTO FAST
REM PRINT ARP TABLE BY DEFAULT
:DEFAULT
ARP -a
GOTO END
REM METHOD 1 ADDRESS AT A TIME
:SLOW
ECHO START SCAN
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO ping -a -n 2 192.168.%SUBNET%.%%i | FIND /i "TTL=" >> ipaddresses.txt
GOTO END
REM METHOD 2 MULTITASKING ALL ADDRESS AT SAME TIME
:FAST
ECHO START FAST SCANNING 192.168.%SUBNET%.X
set /a n=0
:FASTLOOP
set /a n+=1
ECHO 192.168.%SUBNET%.%n%
START CMD.exe /c call ipaddress.bat 192.168.%SUBNET%.%n%
IF %n% lss 254 GOTO FASTLOOP
GOTO END
:SUM
ECHO START SUM
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO TYPE ip192.168.%SUBNET%.%%i.txt | FIND /i "TTL=" >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO DEL ip192.168.%SUBNET%.%%i.txt
type ipaddresses.txt
GOTO END
:ARP
ARP -a >> ipaddresses.txt
type ipaddresses.txt
GOTO END
:END
ECHO DONE WITH IP SCANNING
ECHO OPTION "%0 SLOW" FOR SCANNING 1 AT A TIME
ECHO OPTION "%0 SUM" FOR COMBINE ALL TO FILE
ECHO OPTION "%0 ARP" FOR ADD ARP - IP LIST
ECHO PARAMETER "SET SUBNET=X" FOR SUBNET
ECHO.
Locking pattern for proper use of .NET MemoryCache
To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).
Using it looks like this:
SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();
const string CacheKey = "CacheKey";
static string GetCachedData()
{
string expensiveString =null;
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
// double checked lock
using (var lifetime = keyLocks.Acquire(url))
{
lock (lifetime.Value)
{
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
cacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
};
expensiveString = SomeHeavyAndExpensiveCalculation();
MemoryCache.Default.Set(CacheKey, expensiveString, cip);
return expensiveString;
}
}
}
Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching
Install-Package BitFaster.Caching
There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).
Clean out Eclipse workspace metadata
In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-
I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system:
1. Go to Eclipse --> Project --> Clean
2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"
After that boom - things gets start working :)
If you want to load variables from other files too then ado this :-
Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"
Then it will show element , variables and other functions also.
How to force NSLocalizedString to use a specific language
I usually do this in this way, but you MUST have all localization files in your project.
@implementation Language
static NSBundle *bundle = nil;
+(void)initialize
{
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString *current = [[languages objectAtIndex:0] retain];
[self setLanguage:current];
}
/*
example calls:
[Language setLanguage:@"it"];
[Language setLanguage:@"de"];
*/
+(void)setLanguage:(NSString *)l
{
NSLog(@"preferredLang: %@", l);
NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
bundle = [[NSBundle bundleWithPath:path] retain];
}
+(NSString *)get:(NSString *)key alter:(NSString *)alternate
{
return [bundle localizedStringForKey:key value:alternate table:nil];
}
@end
Hidden TextArea
An <input type=hidden>
element is not a hidden input box. It is simply a form field that has a value set via markup or via scripting, not via user input. You can use it for multi-line data too, e.g.
<input type=hidden name=stuff value=
"Hello
world, how
are you?">
If the value contains the Ascii quotation mark ("), then, as for any HTML attribute, you need to use Ascii apostrophes (') as attribute value delimites or escape the quote as "
, e.g.
<input type=hidden name=stuff value="A "funny" example">
How to obtain the last index of a list?
all above answers is correct but however
a = [];
len(list1) - 1 # where 0 - 1 = -1
to be more precisely
a = [];
index = len(a) - 1 if a else None;
if index == None : raise Exception("Empty Array")
since arrays is starting with 0
Android app unable to start activity componentinfo
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
Difference between static class and singleton pattern?
From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.
What is the opposite of :hover (on mouse leave)?
Just add a transition and the name of the animation on the class inicial, in your case, ul li a, just add a "transition" property and that is all you need
_x000D_
_x000D_
ul li {_x000D_
display: inline;_x000D_
margin-left: 20px;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #999;_x000D_
transition: 1s;_x000D_
-webkit-animation: item-hover-off 1s;_x000D_
-moz-animation: item-hover-off 1s;_x000D_
animation: item-hover-off 1s;_x000D_
}_x000D_
_x000D_
ul li a:hover {_x000D_
color: black;_x000D_
cursor: pointer;_x000D_
-webkit-animation: item-hover 1s;_x000D_
-moz-animation: item-hover 1s;_x000D_
animation: item-hover 1s;_x000D_
}_x000D_
_x000D_
@keyframes item-hover {_x000D_
from {_x000D_
color: #999;_x000D_
}_x000D_
to {_x000D_
color: black;_x000D_
}_x000D_
}_x000D_
_x000D_
@-moz-keyframes item-hover {_x000D_
from {_x000D_
color: #999;_x000D_
}_x000D_
to {_x000D_
color: black;_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes item-hover {_x000D_
from {_x000D_
color: #999;_x000D_
}_x000D_
to {_x000D_
color: black;_x000D_
}_x000D_
}_x000D_
_x000D_
@keyframes item-hover-off {_x000D_
from {_x000D_
color: black;_x000D_
}_x000D_
to {_x000D_
color: #999;_x000D_
}_x000D_
}_x000D_
_x000D_
@-moz-keyframes item-hover-off {_x000D_
from {_x000D_
color: black;_x000D_
}_x000D_
to {_x000D_
color: #999;_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes item-hover-off {_x000D_
from {_x000D_
color: black;_x000D_
}_x000D_
to {_x000D_
color: #999;_x000D_
}_x000D_
}
_x000D_
<ul>_x000D_
<li><a>Home</a></li>_x000D_
<li><a>About</a></li>_x000D_
<li><a>Contacts</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
How do I apply a perspective transform to a UIView?
As Ben said, you'll need to work with the UIView's
layer, using a CATransform3D
to perform the layer's
rotation
. The trick to get perspective working, as described here, is to directly access one of the matrix cells
of the CATransform3D
(m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:
Objective-C
UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
Swift 5.0
if let myView = self.subviews.first {
let layer = myView.layer
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
layer.transform = rotationAndPerspectiveTransform
}
which rebuilds the layer transform from scratch for each rotation.
A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers
, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.
The sublayerTransform
you refer to in your response is a transform that is applied to the sublayers of your UIView's
CALayer
. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers
contained within the one layer that I'm rotating.
print variable and a string in python
If you are using python 3.6 and newer then you can use f-strings to do the task like this.
print(f"I have {card.price}")
just include f in front of your string and add the variable inside curly braces { }.
Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.
.htaccess redirect www to non-www with SSL/HTTPS
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy
Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS
Done in this order, it follows logic and no error occurs.
HERE is my FULL version in side htaccess with WordPress:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Angular ForEach in Angular4/Typescript?
arrayData.forEach((key : any, val: any) => {
key['index'] = val + 1;
arrayData2.forEach((keys : any, vals :any) => {
if (key.group_id == keys.id) {
key.group_name = keys.group_name;
}
})
})
How can I start PostgreSQL server on Mac OS X?
There is some edge case that maybe will be helpful for someone:
There is an option that you will have postgres.pid filled with some PID.
If you restart your machine, and before PostgreSQL will be back again, some other process will take that PID.
If that will happen, both the pg_ctl status and brew service are asked about the PostgreSQL status, will tell you that it is up.
Just do ps aux | grep <yourPID>
and check if it is really PostgreSQL.
How to redirect stdout to both file and console with scripting?
Use logging module to debug and follow your app
Here is how I managed to log to file and to console / stdout
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='logs_file',
filemode='w')
# Until here logs only to file: 'logs_file'
# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')
read it from source:
https://docs.python.org/2/howto/logging-cookbook.html
Tricks to manage the available memory in an R session
I make aggressive use of the subset
parameter with selection of only the required variables when passing dataframes to the data=
argument of regression functions. It does result in some errors if I forget to add variables to both the formula and the select=
vector, but it still saves a lot of time due to decreased copying of objects and reduces the memory footprint significantly. Say I have 4 million records with 110 variables (and I do.) Example:
# library(rms); library(Hmisc) for the cph,and rcs functions
Mayo.PrCr.rbc.mdl <-
cph(formula = Surv(surv.yr, death) ~ age + Sex + nsmkr + rcs(Mayo, 4) +
rcs(PrCr.rat, 3) + rbc.cat * Sex,
data = subset(set1HLI, gdlab2 & HIVfinal == "Negative",
select = c("surv.yr", "death", "PrCr.rat", "Mayo",
"age", "Sex", "nsmkr", "rbc.cat")
) )
By way of setting context and the strategy: the gdlab2
variable is a logical vector that was constructed for subjects in a dataset that had all normal or almost normal values for a bunch of laboratory tests and HIVfinal
was a character vector that summarized preliminary and confirmatory testing for HIV.
Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)
Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100
. But OpenCV uses H: 0-179, S: 0-255, V: 0-255
. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255)
.
Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:
cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)
Now run it. I got an output as follows:
Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.
EDIT:
As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2
module, so users can compare the easiness and flexibility of new cv2
module.
import cv2
import numpy as np
img = cv2.imread('sof.jpg')
ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)
It gives the same result as above. But code is much more simpler.
How to linebreak an svg text within javascript?
use HTML instead of javascript
_x000D_
_x000D_
<html>_x000D_
<head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
<body>_x000D_
<h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
<svg_x000D_
xmlns="http://www.w3.org/2000/svg"_x000D_
viewBox="0 0 300 300"_x000D_
x="0" y="0" height="300" width="300"_x000D_
>_x000D_
_x000D_
<circle_x000D_
r="142" cx="150" cy="150"_x000D_
fill="none" stroke="#000000" stroke-width="2"_x000D_
/>_x000D_
_x000D_
<foreignObject_x000D_
x="50" y="50" width="200" height="200"_x000D_
>_x000D_
<div_x000D_
xmlns="http://www.w3.org/1999/xhtml"_x000D_
style="_x000D_
width: 196px; height: 196px;_x000D_
border: solid 2px #000000;_x000D_
font-size: 32px;_x000D_
overflow: auto; /* scroll */_x000D_
"_x000D_
>_x000D_
<p>this is html in svg 1</p>_x000D_
<p>this is html in svg 2</p>_x000D_
<p>this is html in svg 3</p>_x000D_
<p>this is html in svg 4</p>_x000D_
</div>_x000D_
</foreignObject>_x000D_
_x000D_
</svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_
What is difference between Errors and Exceptions?
Error is something that most of the time you cannot handle it.
Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.
try{
//connect to database 1
}
catch(DatabaseConnctionException err){
//connect to database 2
//write the err to log
}
How to test if a double is zero?
Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.
If this has anything to do with money, do not use float or double, instead use BigDecimal.
What does <> mean in excel?
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
How to resolve conflicts in EGit
This guide was helpful for me
http://wiki.eclipse.org/EGit/User_Guide#Resolving_a_merge_conflict.
UPDATED
Just a note on that about my procedure, this is how I proceed:
- Commit My change
- Fetch (Syncrhonize workspace)
- Pull
- Manage Conflicts with Merge Tool (Team->Merge Tool) and Save
- Add each file to stage (Team -> Add to index)
- Now the Commit Message in the Stage window is prefilled with "Merged XXX". You can leave as it is or change the commit message
- Commit and Push
It is dangerous in some cases but it is very usefull to avoid to use external tool like Git Extension or Source Tree
Can a main() method of class be invoked from another class in java
Sure. Here's a completely silly program that demonstrates calling main
recursively.
public class main
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; ++i)
{
if (args[i] != "")
{
args[i] = "";
System.out.println((args.length - i) + " left");
main(args);
}
}
}
}
Enable SQL Server Broker taking too long
Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:
USE master ;
GO
ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO
Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.
If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:
SELECT
name, database_id, is_broker_enabled
FROM sys.databases
How do I redirect in expressjs while passing some context?
Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :
app.get("/", function(req, res) {
var context = req.app.locals.specialContext;
req.app.locals.specialContext = null;
res.render("home.jade", context);
// or if you are using ejs
res.render("home", {context: context});
});
function middleware(req, res, next) {
req.app.locals.specialContext = * your context goes here *
res.redirect("/");
}
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Switch role after connecting to database
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?
Setup Bitbucket Repository (Command Line with Mac)
Create New APPLICATION from starting with local reposity :
- Terminal -> cd ~/Documents (Paste your APPLICATION base directory path)
- Terminal -> mkdir (create directory with )
- Terminal -> cd (change directory with directory)
- BitBucket A/C -> create repository on bitBucket account
- Xcode -> create new xcode project with same name
- Terminal -> git init (initilize empty repo)
- Terminal -> git remote add origin (Ex. https://[email protected]/app/app.git)
- Terminal -> git add .
- Terminal -> git status
- Terminal -> git commit -m "IntialCommet"
- Terminal -> git push origin master
Create APPLICATION clone repository :
- Terminal -> mkdir (create directory with )
- Terminal -> cd (change directory with directory)
- Terminal -> git clone (Ex. https://[email protected]/app/app.git)
- Terminal -> cd
- Terminal -> git status (Show edit/updated file status)
- Terminal -> git pull origin master
- Terminal -> git add .
- Terminal -> git push origin master
How to specify function types for void (not Void) methods in Java8?
I feel you should be using the Consumer interface instead of Function<T, R>
.
A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)
In your case, you can create a consumer elsewhere in your code like this:
Consumer<Integer> myFunction = x -> {
System.out.println("processing value: " + x);
.... do some more things with "x" which returns nothing...
}
Then you can replace your myForEach
code with below snippet:
public static void myForEach(List<Integer> list, Consumer<Integer> myFunction)
{
list.forEach(x->myFunction.accept(x));
}
You treat myFunction as a first-class object.
Yarn install command error No such file or directory: 'install'
Tried above steps, didn't work on Ubuntu 20.
For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn
Heap space out of memory
There is no way to dynamically increase the heap programatically since the heap is allocated when the Java Virtual Machine is started.
However, you can use this command
java -Xmx1024M YourClass
to set the memory to 1024
or, you can set a min max
java -Xms256m -Xmx1024m YourClassNameHere
How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?
Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.
private func collectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
// Important: if direction is horizontal use minimumItemSpacing instead.
layout.scrollDirection = .vertical
let itemHeight: CGFloat = 240
let minCellWidth :CGFloat = 130.0
let minItemSpacing: CGFloat = 10
let containerWidth: CGFloat = self.view.bounds.width
let maxCellCountPerRow: CGFloat = floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow ) )
// Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumInteritemSpacing = min(minItemSpacing,inset)
layout.minimumLineSpacing = minItemSpacing
layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
return layout
}
How to check if ZooKeeper is running or up from command prompt?
I did some test:
When it's running:
$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower
When it's stopped:
$ zkServer status
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.
I'm not running on the same machine, but you get the idea.
Interface or an Abstract Class: which one to use?
To add to some of the already excellent answers:
Abstract classes let you provide some degree of implementation, interfaces are pure templates. An interface can only define functionality, it can never implement it.
Any class that implements the interface commits to implementing all the methods it defines or it must be declared abstract.
Interfaces can help to manage the fact that, like Java, PHP does not support multiple inheritance. A PHP class can only extend a single parent. However, you can make a class promise to implement as many interfaces as you want.
type: for each interface it implements, the class takes on the corresponding type. Because any class can implement an interface (or more interfaces),
interfaces effectively join types that are otherwise unrelated.
a class can both extend a superclass and implement any number of interfaces:
class SubClass extends ParentClass implements Interface1, Interface2 {
// ...
}
Please explain when I should use an interface and when I should use abstract class?
Use an interface when you need to provide only a template with no implementation what so ever, and you want to make sure any class that implements that interface will have the same methods as any other class that implements it (at least).
Use an abstract class when you want to create a foundation for other objects (a partially built class). The class that extends your abstract class will use some properties or methods defined/implemented:
<?php
// interface
class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code.
// abstract class
class X extends Y { } // this is saying that "X" is going to complete the partial class "Y".
?>
How I can change my abstract class in to an interface?
Here is a simplified case/example. Take out any implementation details out. For example, change your abstract class from:
abstract class ClassToBuildUpon {
public function doSomething() {
echo 'Did something.';
}
}
to:
interface ClassToBuildUpon {
public function doSomething();
}
Convert 4 bytes to int
The following code reads 4 bytes from array
(a byte[]
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
Getting reference to child component in parent component
You may actually go with ViewChild API
...
parent.ts
<button (click)="clicked()">click</button>
export class App {
@ViewChild(Child) vc:Child;
constructor() {
this.name = 'Angular2'
}
func(e) {
console.log(e)
}
clicked(){
this.vc.getName();
}
}
child.ts
export class Child implements OnInit{
onInitialized = new EventEmitter<Child>();
...
...
getName()
{
console.log('called by vc')
console.log(this.name);
}
}
Automatically scroll down chat div
_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
const message = document.getElementsByClassName('message')[0];_x000D_
const newMessage = message.cloneNode(true);_x000D_
messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
// Prior to getting your messages._x000D_
shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
/*_x000D_
* Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
*/_x000D_
appendMessage();_x000D_
// After getting your messages._x000D_
if (!shouldScroll) {_x000D_
scrollToBottom();_x000D_
}_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
height: 200px;_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
<div class="message">_x000D_
Hello world_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
What is python's site-packages directory?
site-packages is just the location where Python installs its modules.
No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).
Programmatically you can find it this way:
import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages
'/Users/foo/.envs/env1/lib/python2.7/site-packages'
Getting realtime output using subprocess
Real Time Output Issue resolved:
I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout);
in my C code. It worked for me. Here is the code.
C program:
#include <stdio.h>
void main()
{
int count = 1;
while (1)
{
printf(" Count %d\n", count++);
fflush(stdout);
sleep(1);
}
}
Python program:
#!/usr/bin/python
import os, sys
import subprocess
procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
while procExe.poll() is None:
line = procExe.stdout.readline()
print("Print:" + line)
Output:
Print: Count 1
Print: Count 2
Print: Count 3
Calling Non-Static Method In Static Method In Java
The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);
Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application
With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS]
error.
I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!
If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename
Finally, I can use adb install myApp.apk
to install the signed release apk.
Delete specific values from column with where condition?
You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.
The general form for this would be an UPDATE
statement:
UPDATE <table name>
SET
ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
ColumnA = <bad value> /* or any other search conditions */
Using C# regular expressions to remove HTML tags
@JasonTrue is correct, that stripping HTML tags should not be done via regular expressions.
It's quite simple to strip HTML tags using HtmlAgilityPack:
public string StripTags(string input) {
var doc = new HtmlDocument();
doc.LoadHtml(input ?? "");
return doc.DocumentNode.InnerText;
}
ERROR Android emulator gets killed
This issue happens when you have two Android SDK installations on your machine and the environment variable "ANDROID_HOME" points to the wrong location.
To fix it go to Android Studio settings, find the proper Android SDK location, update the environment variable and restart Android Studio / your PC.
text-align: right; not working for <label>
Label
is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div
element is a block element so its width is by default 100%.
You will have to place the text-align: right;
on the div
element in your case, or applying display: block;
to your label
Another option is to set a width for each label and then use text-align
. The display: block
method will not be necessary using this.
How to check for an empty struct?
Using reflect.deepEqual also works, especially when you have map inside the struct
package main
import "fmt"
import "time"
import "reflect"
type Session struct {
playerId string
beehive string
timestamp time.Time
}
func (s Session) IsEmpty() bool {
return reflect.DeepEqual(s,Session{})
}
func main() {
x := Session{}
if x.IsEmpty() {
fmt.Print("is empty")
}
}
How do I search an SQL Server database for a string?
I was given access to a database, but not the table where my query was being stored in.
Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.
I found that it can also search a database for a string.
It will search each table and give you how many times it found the string per table!
Passing variable from Form to Module in VBA
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
How to read attribute value from XmlNode in C#?
Try this:
string employeeName = chldNode.Attributes["Name"].Value;
Edit: As pointed out in the comments, this will throw an exception if the attribute doesn't exist. The safe way is:
var attribute = node.Attributes["Name"];
if (attribute != null){
string employeeName = attribute.Value;
// Process the value here
}
Font awesome is not showing icon
Be aware that the new version (5) of font awesome uses "fas"
or "fab"
instead of "fa"
prefix.
Quoted from their website:
The fa prefix has been deprecated in version 5. The new default is the fas solid style and the fab style for brands.
This is why my fonts were showing blank squares. Now fixed.
Example code:
<a class="nav-link" href="//www.facebook.com/xxx" target="_blank"><i class="fab fa-facebook-f"></i></a>
See: https://fontawesome.com/icons/facebook-f?style=brands
How do you wait for input on the same Console.WriteLine() line?
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
Setting the focus to a text field
I have toyed with this for forever, and finally found something that seems to always work!
textField = new JTextField() {
public void addNotify() {
super.addNotify();
requestFocus();
}
};
Why do I always get the same sequence of random numbers with rand()?
rand() returns pseudo-random numbers. It generates numbers based on a given algorithm.
The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.
You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:
srand(time(NULL)); or srand(getpid()); at the start of the program.
Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.
How to use count and group by at the same select statement
With Oracle you could use analytic functions:
select town, count(town), sum(count(town)) over () total_count from user
group by town
Your other options is to use a subquery:
select town, count(town), (select count(town) from user) as total_count from user
group by town
graphing an equation with matplotlib
To plot an equation that is not solved for a specific variable (like circle or hyperbola):
import numpy as np
import matplotlib.pyplot as plt
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100)
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1 # 'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()
More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf
C non-blocking keyboard input
The curses library can be used for this purpose. Of course, select()
and signal handlers can be used too to a certain extent.
Ruby value of a hash key?
This question seems to be ambiguous.
I'll try with my interpretation of the request.
def do_something(data)
puts "Found! #{data}"
end
a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }
This will loop over all the key,value pairs and do something only if the key is 'x'.
Custom Authentication in ASP.Net-Core
@Manish Jain, I suggest to implement the method with boolean return:
public class UserManager
{
// Additional code here...
public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
{
// Additional code here...
// Here the real authentication against a DB or Web Services or whatever
if (user.Email != null)
return false;
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
// This is for give the authentication cookie to the user when authentication condition was met
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return true;
}
}
presenting ViewController with NavigationViewController swift
The accepted answer is great. This is not answer, but just an illustration of the issue.
I present a viewController like this:
inside vc1:
func showVC2() {
if let navController = self.navigationController{
navController.present(vc2, animated: true)
}
}
inside vc2:
func returnFromVC2() {
if let navController = self.navigationController {
navController.popViewController(animated: true)
}else{
print("navigationController is nil") <-- I was reaching here!
}
}
As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"
new solution:
func returnFromVC2() {
dismiss(animated: true, completion: nil)
}
How do I copy a version of a single file from one git branch to another?
I would use git restore
(available since git 2.23)
git restore --source otherbranch path/to/myfile.txt
Why it is better than other options?
git checkout otherbranch -- path/to/myfile.txt
- It copy file to working directory but also to staging area (similar effect as if you would copy this file manually and executed git add
on it). git restore
doesn't touch staging area (unless told it to by --staged
option).
git show otherbranch:path/to/myfile.txt > path/to/myfile.txt
uses standard shell redirection. If you use Powershell then there might be problem with text enconding or you could get broken file if it's binary. With git restore
changing files is done all by git
executable.
Another advantage is that you can restore whole folder with:
git restore --source otherbranch path/to
or with git restore --overlay --source otherbranch path/to
if you want to avoid deleting files. For example if there is less files on otherbranch
than in current working directory (and these files are tracked) without --overlay
option git restore
will delete them. But this is good default bahaviour, you most likely want the state of directory to be "the same like in otherbranch
", not "the same like in otherbranch
but with additional files from my current branch"
Undefined reference to static class member
Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.
Or at least my colleague who resolved this said so.
What are the correct version numbers for C#?
I've summarised most of the versions in this table. The only ones missing should be ASP.NET Core versions. I've also added different versions of ASP.NET MVC.
Note that ASP.NET 5 has been rebranded as ASP.NET Core 1.0 and ASP.NET MVC 6 has been rebranded as ASP.NET Core MVC 1.0.0. I believe this change occurred sometime around Jan 2016.
I have included the release date of ASP.NET 5 RC1 in the table, but I've yet to include ASP.NET core 1.0 and other core versions, because I couldn't find the exact release dates. You can read more about the release dates regarding ASP.NET Core here: When is ASP.NET Core 1.0 (ASP.NET 5 / vNext) scheduled for release?
Is there an easy way to add a border to the top and bottom of an Android View?
Just to add my solution to the list..
I wanted a semi transparent bottom border that extends past the original shape (So the semi-transparent border was outside the parent rectangle).
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#33000000" /> <!-- Border colour -->
</shape>
</item>
<item android:bottom="2dp" >
<shape android:shape="rectangle" >
<solid android:color="#164586" />
</shape>
</item>
</layer-list>
Which gives me;
jQuery: Uncheck other checkbox on one checked
I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View
, like a foreach
loop):
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
Corresponding Jquery
:
$(".list-group-item").each(function (i, li) {
var currentli = $(li);
$(currentli).find("#checkbox1").on('change', function () {
$(currentli).find("#checkbox2").not(this).prop('checked',false);
});
$(currentli).find("#checkbox2").on('change', function () {
$(currentli).find("#checkbox1").not(this).prop('checked', false);
});
});
Working DEMO: https://jsfiddle.net/gr67qk20/
Convert Java Date to UTC String
The following simplified code, based on the accepted answer above, worked for me:
public class GetSync {
public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
static {
isoFormatter.setTimeZone(utc);
}
public static String now() {
return isoFormatter.format(new Date()).toString();
}
}
I hope this helps somebody.
How to change color in markdown cells ipython/jupyter notebook?
If none of the above suggestions works for you, try using the style
attribute.
**Notes**
<p style="color:red;">ERROR: Setting focus didn't work for me when I tried from jupyter. However it worked well when I ran it from the terminal</p>
This gives me the following result
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
Remove the title bar in Windows Forms
Also add this bit of code to your form to allow it to be draggable still.
Just add it right before the constructor (the method that calls InitializeComponent()
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
///
/// Handling the window messages
///
protected override void WndProc(ref Message message)
{
base.WndProc(ref message);
if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
message.Result = (IntPtr)HTCAPTION;
}
That code is from: https://jachman.wordpress.com/2006/06/08/enhanced-drag-and-move-winforms-without-having-a-titlebar/
Now to get rid of the title bar but still have a border combine the code from the other response:
this.ControlBox = false;
this.Text = String.Empty;
with this line:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Put those 3 lines of code into the form's OnLoad event and you should have a nice 'floating' form that is draggable with a thin border (use FormBorderStyle.None if you want no border).
How to count the frequency of the elements in an unordered list?
You can do this:
import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)
Output:
(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
The first array is values, and the second array is the number of elements with these values.
So If you want to get just array with the numbers you should use this:
np.unique(a, return_counts=True)[1]