gpg: no valid OpenPGP data found
By executing the following command, it will save a jenkins-ci.org.key file in the current working directory:
curl -O http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key
Then use the following command to add the key file:
apt-key add jenkins-ci.org.key
If the system returns OK, then the key file has been successfully added.
Static extension methods
specifically I want to overload Boolean.Parse
to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
Global variables in Java
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class
How to start mongodb shell?
bat command to start mongodb
create one folder for database like in this example r0
start /d "{path}\bin" mongod.exe --replSet foo --port 27017 --dbpath {path}mongoDataBase\r0
start /d "{path}\bin" mongo.exe 127.0.0.1:27017
How to call a method in another class of the same package?
You can either create a static method or use the other class as a member of your class calling the function in the constructor.
public class aClass {
private SomeOtherClass oc;
public class aClass( SomeOtherClass otherClass) {
oc = otherClass;
}
public callOtherClassMethod() {
oc.otherClassMethod();
}
}
Change the encoding of a file in Visual Studio Code
Apart from the settings explained in the answer by @DarkNeuron:
"files.encoding": "any encoding"
you can also specify settings for a specific language like so:
"[language id]": {
"files.encoding": "any encoding"
}
For example, I use this when I need to edit PowerShell files previously created with ISE (which are created in ANSI format):
"[powershell]": {
"files.encoding": "windows1252"
}
You can get a list of identifiers of well-known languages here.
Spool Command: Do not output SQL statement to file
My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.
This did not resolve my problem:
set echo off
This resolved my problem:
set verify off
Get PostGIS version
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
MongoDB: Server has startup warnings ''Access control is not enabled for the database''
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
Is ASCII code 7-bit or 8-bit?
ASCII encoding is 7-bit, but in practice, characters encoded in ASCII are not stored in groups of 7 bits. Instead, one ASCII is stored in a byte, with the MSB usually set to 0 (yes, it's wasted in ASCII).
You can verify this by inputting a string in the ASCII character set in a text editor, setting the encoding to ASCII, and viewing the binary/hex:
Aside: the use of (strictly) ASCII encoding is now uncommon, in favor of UTF-8 (which does not waste the MSB mentioned above - in fact, an MSB of 1 indicates the code point is encoded with more than 1 byte).
Set Matplotlib colorbar size to match graph
I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1
module cannot address GeoAxes, whereas adjusting fraction
, pad
, shrink
, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar
its own axes
might be a better solution to address all the issues that have been mentioned.
Code
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
Result
Later on, I find matplotlib.pyplot.colorbar
official documentation also gives ax
option, which are existing axes that will provide room for the colorbar. Therefore, it is useful for multiple subplots, see following.
Code
fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)
Result
Again, you can also achieve similar effects by specifying cax, a more accurate way from my perspective.
Code
fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)
Result
Leaflet changing Marker color
Bind in the icons from this site!
https://github.com/pointhi/leaflet-color-markers
Detailed how-to information included on the website.
Edit: Use the code below to add a marker icon and just replace the link to the one with the color of your choice. (i.e. marker-icon-2x-green.png
to some other image)
var greenIcon = new L.Icon({
iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
When should I use the new keyword in C++?
Are you passing myClass out of a function, or expecting it to exist outside that function? As some others said, it is all about scope when you aren't allocating on the heap. When you leave the function, it goes away (eventually). One of the classic mistakes made by beginners is the attempt to create a local object of some class in a function and return it without allocating it on the heap. I can remember debugging this kind of thing back in my earlier days doing c++.
What is the best way to conditionally apply attributes in AngularJS?
Regarding the accepted solution, the one posted by Ashley Davis, the method described still prints the attribute in the DOM, regardless of the fact that the value it has been assigned is undefined.
For example, on an input field setup with both an ng-model and a value attribute:
<input type="text" name="myInput" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />
Regardless of what's behind myValue, the value attribute still gets printed in the DOM, thus, interpreted. Ng-model then, becomes overridden.
A bit unpleasant, but using ng-if does the trick:
<input type="text" name="myInput" data-ng-if="value" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />
<input type="text" name="myInput" data-ng-if="!value" data-ng-model="myModel" />
I would recommend using a more detailed check inside the ng-if directives :)
How do I test if a variable is a number in Bash?
Did the same thing here with a regular expression that test the entire part and decimals part, separated with a dot.
re="^[0-9]*[.]{0,1}[0-9]*$"
if [[ $1 =~ $re ]]
then
echo "is numeric"
else
echo "Naahh, not numeric"
fi
Javascript Confirm popup Yes, No button instead of OK and Cancel
you can use sweetalert.
import into your HTML:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
and to fire the alert:
Swal.fire({
title: 'Do you want to do this?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Do this!',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
Swal.fire(
'Done!',
'This has been done.',
'success'
)
}
})
for more data visit sweetalert alert website
Integer division with remainder in JavaScript?
If you are just dividing with powers of two, you can use bitwise operators:
export function divideBy2(num) {
return [num >> 1, num & 1];
}
export function divideBy4(num) {
return [num >> 2, num & 3];
}
export function divideBy8(num) {
return [num >> 3, num & 7];
}
(The first is the quotient, the second the remainder)
Quicksort with Python
Quick sort without additional memory (in place)
Usage:
array = [97, 200, 100, 101, 211, 107]
quicksort(array)
# array -> [97, 100, 101, 107, 200, 211]
def partition(array, begin, end):
pivot = begin
for i in xrange(begin+1, end+1):
if array[i] <= array[begin]:
pivot += 1
array[i], array[pivot] = array[pivot], array[i]
array[pivot], array[begin] = array[begin], array[pivot]
return pivot
def quicksort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
def _quicksort(array, begin, end):
if begin >= end:
return
pivot = partition(array, begin, end)
_quicksort(array, begin, pivot-1)
_quicksort(array, pivot+1, end)
return _quicksort(array, begin, end)
How to convert an int to string in C?
After having looked at various versions of itoa for gcc, the most flexible version I have found that is capable of handling conversions to binary, decimal and hexadecimal, both positive and negative is the fourth version found at http://www.strudel.org.uk/itoa/. While sprintf
/snprintf
have advantages, they will not handle negative numbers for anything other than decimal conversion. Since the link above is either off-line or no longer active, I've included their 4th version below:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
How to get the date 7 days earlier date from current date in Java
Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Foo {
public static void main(String[] args) {
DateTimeFormatter format =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusDays(7);
System.out.println(String.format(
"Now: %s\nThen: %s",
now.format(format),
then.format(format)
));
/*
Example output:
Now: 2014-05-09T14:51:48Z
Then: 2014-05-02T14:51:48Z
*/
}
}
Convert line endings
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
How to get just the parent directory name of a specific file
If you have just String path and don't want to create new File object you can use something like:
public static String getParentDirPath(String fileOrDirPath) {
boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar,
endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
}
submit form on click event using jquery
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Display Adobe pdf inside a div
may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.
1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.
2) if u don't have many pdf and if u don't know then just upload that file on google docs
and then just put the share link file....and then just use ajax or jquery.
i prefer jquery if u don't have use AJAX.
how to get right offset of an element? - jQuery
Alex, Gary:
As requested, here is my comment posted as an answer:
var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
Thanks for letting me know.
In pseudo code that can be expressed as:
The right offset is:
The window's width MINUS
( The element's left offset PLUS the element's outer width )
If strings starts with in PowerShell
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.
@all
Whole view.
@form
Closest ancestor form of current component.
@none
No component.
and the standard JSF 2.3+ keywords:
@child(n)
nth child.
@composite
Closest composite component ancestor.
@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.
@namingcontainer
Closest ancestor naming container of current component.
@parent
Parent of the current component.
@previous
Previous sibling.
@next
Next sibling.
@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.
But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.
@widgetVar(name)
Component with given widgetVar.
And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
Convert integer value to matching Java Enum
if you have enum like this
public enum PcapLinkType {
DLT_NULL(0)
DLT_EN10MB(1)
DLT_EN3MB(2),
DLT_AX25(3),
DLT_UNKNOWN(-1);
private final int value;
PcapLinkType(int value) {
this.value= value;
}
}
then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
Using Razor within JavaScript
None of the previous solutions work correctly... I have tried all the ways, but it did not give me the expected result... At last I found that there are some errors in the code... And the full code is given below.
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.00, 90.00),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
@foreach (var item in Model)
{
<text>
var markerlatLng = new google.maps.LatLng(@(item.LATITUDE), @(item.LONGITUDE));
var title = '@(item.EMP_ID)';
var description = '@(item.TIME)';
var contentString = '<h3>' + "Employee " +title+ " was here at "+description+ '</h3>' + '<p>'+" "+ '</p>'
var infowindow = new google.maps.InfoWindow({
// content: contentString
});
var marker = new google.maps.Marker({
position: markerlatLng,
title: title,
map: map,
draggable: false,
content: contentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
</script>
Password encryption at client side
I would choose this simple solution.
Summarizing it:
- Client "I want to login"
- Server generates a random number
#S
and sends it to the Client
- Client
- reads username and password typed by the user
- calculates the hash of the password, getting
h(pw)
(which is what is stored in the DB)
- generates another random number
#C
- concatenates
h(pw) + #S + #C
and calculates its hash, call it h(all)
- sends to the server
username
, #C
and h(all)
- Server
- retrieves
h(pw)'
for the specified username
, from the DB
- now it has all the elements to calculate
h(all')
, like Client did
- if
h(all)
= h(all')
then h(pw)
= h(pw)'
, almost certainly
No one can repeat the request to log in as the specified user. #S
adds a variable component to the hash, each time (it's fundamental). #C
adds additional noise in it.
Java int to String - Integer.toString(i) vs new Integer(i).toString()
Here
Integer.toString
calls the static method in the class Integer. It does not require the object to call.
If you call new Integer(i)
you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. Then you call the toString
method on it to ask it to return a string representation of itself.
What is the meaning of curly braces?
In Python, curly braces are used to define a dictionary.
a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3
In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.
for entry in entries:
code....
There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.
from __future__ import braces
Remove all stylings (border, glow) from textarea
The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.
textarea {
border: none;
overflow: auto;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
resize: none; /*remove the resize handle on the bottom right*/
}
You may also try adding !important to prioritize this CSS.
Freeze the top row for an html table only (Fixed Table Header Scrolling)
This is called Fixed Header Scrolling. There are a number of documented approaches:
http://www.imaputz.com/cssStuff/bigFourVersion.html
You won't effectively pull this off without JavaScript ... especially if you want cross browser support.
There are a number of gotchyas with any approach you take, especially concerning cross browser/version support.
Edit:
Even if it's not the header you want to fix, but the first row of data, the concept is still the same. I wasn't 100% which you were referring to.
Additional thought
I was tasked by my company to research a solution for this that could function in IE7+, Firefox, and Chrome.
After many moons of searching, trying, and frustration it really boiled down to a fundamental problem. For the most part, in order to gain the fixed header, you need to implement fixed height/width columns because most solutions involve using two separate tables, one for the header which will float and stay in place over the second table that contains the data.
//float this one right over second table
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</table>
<table>
//Data
</table>
An alternative approach some try is utilize the tbody and thead tags but that is flawed too because IE will not allow you put a scrollbar on the tbody which means you can't limit its height (so stupid IMO).
<table>
<thead style="do some stuff to fix its position">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody style="No scrolling allowed here!">
Data here
</tbody>
</table>
This approach has many issues such as ensures EXACT pixel widths because tables are so cute in that different browsers will allocate pixels differently based on calculations and you simply CANNOT (AFAIK) guarantee that the distribution will be perfect in all cases. It becomes glaringly obvious if you have borders within your table.
I took a different approach and said screw tables since you can't make this guarantee. I used divs to mimic tables. This also has issues of positioning the rows and columns (mainly because floating has issues, using in-line block won't work for IE7, so it really left me with using absolute positioning to put them in their proper places).
There is someone out there that made the Slick Grid which has a very similar approach to mine and you can use and a good (albeit complex) example for achieving this.
https://github.com/6pac/SlickGrid/wiki
Put buttons at bottom of screen with LinearLayout?
You can bundle your Button(s) within a RelativeLayout even if your Parent Layout is Linear. Make Sure the outer most parent has android:layout_height attribute set to match_parent.
And in that Button tag add
'android:alignParentBottom="True" '
Repeating a function every few seconds
There are lot of different Timers in the .NET BCL:
When to use which?
System.Timers.Timer
, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Threading.Timer
, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Windows.Forms.Timer
(.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
System.Web.UI.Timer
(.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
System.Windows.Threading.DispatcherTimer
, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.
Source
Some of them needs explicit Start
call to begin ticking (for example System.Timers
, System.Windows.Forms
). And an explicit Stop
to finish ticking.
using TimersTimer = System.Timers.Timer;
static void Main(string[] args)
{
var timer = new TimersTimer(1000);
timer.Elapsed += (s, e) => Console.WriteLine("Beep");
Thread.Sleep(1000); //1 second delay
timer.Start();
Console.ReadLine();
timer.Stop();
}
While on the other hand there are some Timers (like: System.Threading
) where you don't need explicit Start
and Stop
calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.
So, the following two versions will work in the same way:
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
But if your timer
disposed then it will stop ticking obviously.
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
GC.Collect(0);
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
Understanding Python super() with __init__() methods
It's been noted that in Python 3.0+ you can use
super().__init__()
to make your call, which is concise and does not require you to reference the parent OR class names explicitly, which can be handy. I just want to add that for Python 2.7 or under, some people implement a name-insensitive behaviour by writing self.__class__
instead of the class name, i.e.
super(self.__class__, self).__init__() # DON'T DO THIS!
HOWEVER, this breaks calls to super
for any classes that inherit from your class, where self.__class__
could return a child class. For example:
class Polygon(object):
def __init__(self, id):
self.id = id
class Rectangle(Polygon):
def __init__(self, id, width, height):
super(self.__class__, self).__init__(id)
self.shape = (width, height)
class Square(Rectangle):
pass
Here I have a class Square
, which is a sub-class of Rectangle
. Say I don't want to write a separate constructor for Square
because the constructor for Rectangle
is good enough, but for whatever reason I want to implement a Square so I can reimplement some other method.
When I create a Square
using mSquare = Square('a', 10,10)
, Python calls the constructor for Rectangle
because I haven't given Square
its own constructor. However, in the constructor for Rectangle
, the call super(self.__class__,self)
is going to return the superclass of mSquare
, so it calls the constructor for Rectangle
again. This is how the infinite loop happens, as was mentioned by @S_C. In this case, when I run super(...).__init__()
I am calling the constructor for Rectangle
but since I give it no arguments, I will get an error.
Saving an Object (Data persistence)
I think it's a pretty strong assumption to assume that the object is a class
. What if it's not a class
? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__
after creation, pickle
doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle
serializes by reference to the object definition).
In all these cases, pickle
and cPickle
can fail you horribly.
If you are looking to save an object
(arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill
, which can serialize almost anything in python.
We start with a class…
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
... pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
...
>>>
Now shut down, and restart...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
... company1 = pickle.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>>
Oops… pickle
can't handle it. Let's try dill
. We'll throw in another object type (a lambda
) for good measure.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> with open('company_dill.pkl', 'wb') as f:
... dill.dump(company1, f)
... dill.dump(company2, f)
...
>>>
And now read the file.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
... company1 = dill.load(f)
... company2 = dill.load(f)
...
>>> company1
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>
It works. The reason pickle
fails, and dill
doesn't, is that dill
treats __main__
like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle
does). The reason dill
can pickle a lambda
is that it gives it a name… then pickling magic can happen.
Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> dill.dump_session('dill.pkl')
>>>
Now shut down your computer, go enjoy an espresso or whatever, and come back later...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>
The only major drawback is that dill
is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.
However, if you are able to install python packages on your system, you can get the latest dill
with git+https://github.com/uqfoundation/dill.git@master#egg=dill
. And you can get the latest released version with pip install dill
.
How to close existing connections to a DB
Short Answer:
You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.
Long Answer:
Right Click on the Databases under your Server-Name as shown below:
and select the option: "Restore Database..." from it.
In the "Restore Database" wizard,
- select one of your databases to restore
- in the left vertical menu, click on "Options"
Here you can find the checkbox saying, "close existing connections to destination database"
Just check it, and you can proceed for the restore operation.
It automatically will resume all connections after completion of the Restore.
How to host google web fonts on my own server?
As you want to host all fonts (or some of them) at your own server, you a download fonts from this repo and use it the way you want: https://github.com/praisedpk/Local-Google-Fonts
If you just want to do this to fix the leverage browser caching issue that comes with Google Fonts, you can use alternative fonts CDN, and include fonts as:
<link href="https://pagecdn.io/lib/easyfonts/fonts.css" rel="stylesheet" />
Or a specific font, as:
<link href="https://pagecdn.io/lib/easyfonts/lato.css" rel="stylesheet" />
How to skip "are you sure Y/N" when deleting files in batch files
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
How to print color in console using System.out.println?
Try the following enum :
enum Color {
//Color end string, color reset
RESET("\033[0m"),
// Regular Colors. Normal color, no bold, background color etc.
BLACK("\033[0;30m"), // BLACK
RED("\033[0;31m"), // RED
GREEN("\033[0;32m"), // GREEN
YELLOW("\033[0;33m"), // YELLOW
BLUE("\033[0;34m"), // BLUE
MAGENTA("\033[0;35m"), // MAGENTA
CYAN("\033[0;36m"), // CYAN
WHITE("\033[0;37m"), // WHITE
// Bold
BLACK_BOLD("\033[1;30m"), // BLACK
RED_BOLD("\033[1;31m"), // RED
GREEN_BOLD("\033[1;32m"), // GREEN
YELLOW_BOLD("\033[1;33m"), // YELLOW
BLUE_BOLD("\033[1;34m"), // BLUE
MAGENTA_BOLD("\033[1;35m"), // MAGENTA
CYAN_BOLD("\033[1;36m"), // CYAN
WHITE_BOLD("\033[1;37m"), // WHITE
// Underline
BLACK_UNDERLINED("\033[4;30m"), // BLACK
RED_UNDERLINED("\033[4;31m"), // RED
GREEN_UNDERLINED("\033[4;32m"), // GREEN
YELLOW_UNDERLINED("\033[4;33m"), // YELLOW
BLUE_UNDERLINED("\033[4;34m"), // BLUE
MAGENTA_UNDERLINED("\033[4;35m"), // MAGENTA
CYAN_UNDERLINED("\033[4;36m"), // CYAN
WHITE_UNDERLINED("\033[4;37m"), // WHITE
// Background
BLACK_BACKGROUND("\033[40m"), // BLACK
RED_BACKGROUND("\033[41m"), // RED
GREEN_BACKGROUND("\033[42m"), // GREEN
YELLOW_BACKGROUND("\033[43m"), // YELLOW
BLUE_BACKGROUND("\033[44m"), // BLUE
MAGENTA_BACKGROUND("\033[45m"), // MAGENTA
CYAN_BACKGROUND("\033[46m"), // CYAN
WHITE_BACKGROUND("\033[47m"), // WHITE
// High Intensity
BLACK_BRIGHT("\033[0;90m"), // BLACK
RED_BRIGHT("\033[0;91m"), // RED
GREEN_BRIGHT("\033[0;92m"), // GREEN
YELLOW_BRIGHT("\033[0;93m"), // YELLOW
BLUE_BRIGHT("\033[0;94m"), // BLUE
MAGENTA_BRIGHT("\033[0;95m"), // MAGENTA
CYAN_BRIGHT("\033[0;96m"), // CYAN
WHITE_BRIGHT("\033[0;97m"), // WHITE
// Bold High Intensity
BLACK_BOLD_BRIGHT("\033[1;90m"), // BLACK
RED_BOLD_BRIGHT("\033[1;91m"), // RED
GREEN_BOLD_BRIGHT("\033[1;92m"), // GREEN
YELLOW_BOLD_BRIGHT("\033[1;93m"), // YELLOW
BLUE_BOLD_BRIGHT("\033[1;94m"), // BLUE
MAGENTA_BOLD_BRIGHT("\033[1;95m"), // MAGENTA
CYAN_BOLD_BRIGHT("\033[1;96m"), // CYAN
WHITE_BOLD_BRIGHT("\033[1;97m"), // WHITE
// High Intensity backgrounds
BLACK_BACKGROUND_BRIGHT("\033[0;100m"), // BLACK
RED_BACKGROUND_BRIGHT("\033[0;101m"), // RED
GREEN_BACKGROUND_BRIGHT("\033[0;102m"), // GREEN
YELLOW_BACKGROUND_BRIGHT("\033[0;103m"), // YELLOW
BLUE_BACKGROUND_BRIGHT("\033[0;104m"), // BLUE
MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"), // MAGENTA
CYAN_BACKGROUND_BRIGHT("\033[0;106m"), // CYAN
WHITE_BACKGROUND_BRIGHT("\033[0;107m"); // WHITE
private final String code;
Color(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
And now we will make a small example:
class RunApp {
public static void main(String[] args) {
System.out.print(Color.BLACK_BOLD);
System.out.println("Black_Bold");
System.out.print(Color.RESET);
System.out.print(Color.YELLOW);
System.out.print(Color.BLUE_BACKGROUND);
System.out.println("YELLOW & BLUE");
System.out.print(Color.RESET);
System.out.print(Color.YELLOW);
System.out.println("YELLOW");
System.out.print(Color.RESET);
}
}
Maven with Eclipse Juno
From Eclipse
- Go to Help
- Eclipse Marketplace
- Search for m2e or maven integration for eclipse
- click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
- Restart and Enjoy!!!
Ship an application with a database
I wrote a library to simplify this process.
dataBase = new DataBase.Builder(context, "myDb").
// setAssetsPath(). // default "databases"
// setDatabaseErrorHandler().
// setCursorFactory().
// setUpgradeCallback()
// setVersion(). // default 1
build();
It will create a dataBase from assets/databases/myDb.db
file.
In addition you will get all those functionality:
- Load database from file
- Synchronized access to the database
- Using sqlite-android by requery, Android specific distribution of the latest versions of SQLite.
Clone it from github.
XPath: How to select elements based on their value?
The condition below:
//Element[@attribute1="abc" and @attribute2="xyz" and Data]
checks for the existence of the element Data within Element and not for element value Data.
Instead you can use
//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
Key Shortcut for Eclipse Imports
You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports
via Java Editor
- Save Action
. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.
Side-by-side plots with ggplot2
The cowplot
package gives you a nice way to do this, in a manner that suits publication.
x <- rnorm(100)
eps <- rnorm(100,0,.2)
A = qplot(x,3*x+eps, geom = c("point", "smooth"))+theme_gray()
B = qplot(x,2*x+eps, geom = c("point", "smooth"))+theme_gray()
cowplot::plot_grid(A, B, labels = c("A", "B"), align = "v")
Passing arguments forward to another javascript function
Spread operator
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.
Example without using the apply
method:
_x000D_
_x000D_
function a(...args){_x000D_
b(...args);_x000D_
b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
_x000D_
_x000D_
Note This snippet returns a syntax error if your browser still uses ES5.
Editor's note: Since the snippet uses console.log()
, you must open your browser's JS console to see the result - there will be no in-page result.
It will display this result:
In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters
How to copy text to the client's clipboard using jQuery?
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
Simple VBA selection: Selecting 5 cells to the right of the active cell
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
printf \t option
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
nuget 'packages' element is not declared warning
This happens because VS doesn't know the schema of this file. Note that this file is more of an implementation detail, and not something you normally need to open directly. Instead, you can use the NuGet dialog to manage the packages installed in a project.
how to save and read array of array in NSUserdefaults in swift?
The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults
. For those people I will add a few common examples.
String array
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
Int array
Save array
let array = [15, 33, 36, 723, 77, 4]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray") as? [Int] ?? [Int]()
Bool array
Save array
let array = [true, true, false, true, false]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray") as? [Bool] ?? [Bool]()
Date array
Save array
let array = [Date(), Date(), Date(), Date()]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray") as? [Date] ?? [Date]()
Object array
Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults
. See the following links for how to do it.
Notes
- The nil coalescing operator (
??
) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ??
operator will be used instead.
- As you can see, the basic setup was the same for
Int
, Bool
, and Date
. I also tested it with Double
. As far as I know, anything that you can save in a property list will work like this.
Convert blob URL to normal URL
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
Should a retrieval method return 'null' or throw an exception when it can't produce the return value?
I just wanted to recapitulate the options mentioned before, throwing some new ones in:
- return null
- throw an Exception
- use the null object pattern
- provide a boolean parameter to you method, so the caller can chose if he wants you to throw an exception
- provide an extra parameter, so the caller can set a value which he gets back if no value is found
Or you might combine these options:
Provide several overloaded versions of your getter, so the caller can decide which way to go. In most cases, only the first one has an implementation of the search algorithm, and the other ones just wrap around the first one:
Object findObjectOrNull(String key);
Object findObjectOrThrow(String key) throws SomeException;
Object findObjectOrCreate(String key, SomeClass dataNeededToCreateNewObject);
Object findObjectOrDefault(String key, Object defaultReturnValue);
Even if you choose to provide only one implementation, you might want to use a naming convention like that to clarify your contract, and it helps you should you ever decide to add other implementations as well.
You should not overuse it, but it may be helpfull, espeacially when writing a helper Class which you will use in hundreds of different applications with many different error handling conventions.
Is there a shortcut to make a block comment in Xcode?
There is a symbol before help menu on xcode which has Edit user script. On Un/Comment Selection under comments section change
my $cCmt = "//";
to
my $cCmt = "#";
or whatever your IDE works with.
Then by selecting lines and command + / (It's my xcode default) you can comment and uncomment the selected lines.
Save Javascript objects in sessionStorage
Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.
I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.
Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
What exactly does numpy.exp() do?
It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5))
is similar to [math.e**x for x in range(5)]
.
How do I run Python script using arguments in windows command line
Here are all of the previous answers summarized:
- modules should be imported outside of functions.
- hello(sys.argv[2]) needs to be indented since it is inside an if statement.
- hello has 2 arguments so you need to call 2 arguments.
- as far as calling the function from terminal, you need to call python .py ...
The code should look like this:
import sys
def hello(a, b):
print "hello and that's your sum:"
sum = a+b
print sum
if __name__== "__main__":
hello(int(sys.argv[1]), int(sys.argv[2]))
Then run the code with this command:
python hello.py 1 1
UICollectionView Self Sizing Cells with Auto Layout
Updated for Swift 5
preferredLayoutAttributesFittingAttributes
renamed to preferredLayoutAttributesFitting
and use auto sizing
Updated for Swift 4
systemLayoutSizeFittingSize
renamed to systemLayoutSizeFitting
Updated for iOS 9
After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.
TL;DR
Check out my GitHub project
Self sizing cells are only supported with flow layout so make sure thats what you are using.
There are two things you need to setup for self sizing cells to work.
1. Set estimatedItemSize
on UICollectionViewFlowLayout
Flow layout will become dynamic in nature once you set the estimatedItemSize
property.
self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
2. Add support for sizing on your cell subclass
This comes in 2 flavours; Auto-Layout or custom override of preferredLayoutAttributesFittingAttributes
.
Create and configure cells with Auto Layout
I won't go to in to detail about this as there's a brilliant SO post about configuring constraints for a cell. Just be wary that Xcode 6 broke a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. awakeFromNib
).
Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.
Implement preferredLayoutAttributesFittingAttributes
in your custom cell
When this function is called your view has already been configured with content (i.e. cellForItem
has been called). Assuming your constraints have been appropriately set you could have an implementation like this:
//forces the system to do one layout pass
var isHeightCalculated: Bool = false
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//Exhibit A - We need to cache our calculation to prevent a crash.
if !isHeightCalculated {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.width = CGFloat(ceilf(Float(size.width)))
layoutAttributes.frame = newFrame
isHeightCalculated = true
}
return layoutAttributes
}
NOTE On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more here). When you implement preferredLayoutAttributesFittingAttributes
you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the isHeightCalculated
property.
Experience your layout
At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like UITableView
wins the battle for dynamic sizing IMHO.
Caveats
Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your XIB uses size classes. The reason for this is that when you load your cell from a XIB its size class will be configured with Undefined
. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the traitCollection
getter and return the appropriate traits. It's up to you.
Let me know if I missed anything, hope I helped and good luck coding
How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)
I have some additions to above mentioned answers
Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to
private SSLSocketFactory delegate;
This is my TLSSocketFactory class
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
and this is how i used it with okhttp and retrofit
OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
How to dynamically add and remove form fields in Angular 2
This is a few months late but I thought I'd provide my solution based on this here tutorial. The gist of it is that it's a lot easier to manage once you change the way you approach forms.
First, use ReactiveFormsModule
instead of or in addition to the normal FormsModule
. With reactive forms you create your forms in your components/services and then plug them into your page instead of your page generating the form itself. It's a bit more code but it's a lot more testable, a lot more flexible, and as far as I can tell the best way to make a lot of non-trivial forms.
The end result will look a little like this, conceptually:
You have one base FormGroup
with whatever FormControl
instances you need for the entirety of the form. For example, as in the tutorial I linked to, lets say you want a form where a user can input their name once and then any number of addresses. All of the one-time field inputs would be in this base form group.
Inside that FormGroup
instance there will be one or more FormArray
instances. A FormArray
is basically a way to group multiple controls together and iterate over them. You can also put multiple FormGroup
instances in your array and use those as essentially "mini-forms" nested within your larger form.
By nesting multiple FormGroup
and/or FormControl
instances within a dynamic FormArray
, you can control validity and manage the form as one, big, reactive piece made up of several dynamic parts. For example, if you want to check if every single input is valid before allowing the user to submit, the validity of one sub-form will "bubble up" to the top-level form and the entire form becomes invalid, making it easy to manage dynamic inputs.
As a FormArray
is, essentially, a wrapper around an array interface but for form pieces, you can push, pop, insert, and remove controls at any time without recreating the form or doing complex interactions.
In case the tutorial I linked to goes down, here some sample code you can implement yourself (my examples use TypeScript) that illustrate the basic ideas:
Base Component code:
import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-form-component',
templateUrl: './my-form.component.html'
})
export class MyFormComponent implements OnInit {
@Input() inputArray: ArrayType[];
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
let newForm = this.fb.group({
appearsOnce: ['InitialValue', [Validators.required, Validators.maxLength(25)]],
formArray: this.fb.array([])
});
const arrayControl = <FormArray>newForm.controls['formArray'];
this.inputArray.forEach(item => {
let newGroup = this.fb.group({
itemPropertyOne: ['InitialValue', [Validators.required]],
itemPropertyTwo: ['InitialValue', [Validators.minLength(5), Validators.maxLength(20)]]
});
arrayControl.push(newGroup);
});
this.myForm = newForm;
}
addInput(): void {
const arrayControl = <FormArray>this.myForm.controls['formArray'];
let newGroup = this.fb.group({
/* Fill this in identically to the one in ngOnInit */
});
arrayControl.push(newGroup);
}
delInput(index: number): void {
const arrayControl = <FormArray>this.myForm.controls['formArray'];
arrayControl.removeAt(index);
}
onSubmit(): void {
console.log(this.myForm.value);
// Your form value is outputted as a JavaScript object.
// Parse it as JSON or take the values necessary to use as you like
}
}
Sub-Component Code: (one for each new input field, to keep things clean)
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'my-form-sub-component',
templateUrl: './my-form-sub-component.html'
})
export class MyFormSubComponent {
@Input() myForm: FormGroup; // This component is passed a FormGroup from the base component template
}
Base Component HTML
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
<label>Appears Once:</label>
<input type="text" formControlName="appearsOnce" />
<div formArrayName="formArray">
<div *ngFor="let control of myForm.controls['formArray'].controls; let i = index">
<button type="button" (click)="delInput(i)">Delete</button>
<my-form-sub-component [myForm]="myForm.controls.formArray.controls[i]"></my-form-sub-component>
</div>
</div>
<button type="button" (click)="addInput()">Add</button>
<button type="submit" [disabled]="!myForm.valid">Save</button>
</form>
Sub-Component HTML
<div [formGroup]="form">
<label>Property One: </label>
<input type="text" formControlName="propertyOne"/>
<label >Property Two: </label>
<input type="number" formControlName="propertyTwo"/>
</div>
In the above code I basically have a component that represents the base of the form and then each sub-component manages its own FormGroup
instance within the FormArray
situated inside the base FormGroup
. The base template passes along the sub-group to the sub-component and then you can handle validation for the entire form dynamically.
Also, this makes it trivial to re-order component by strategically inserting and removing them from the form. It works with (seemingly) any number of inputs as they don't conflict with names (a big downside of template-driven forms as far as I'm aware) and you still retain pretty much automatic validation. The only "downside" of this approach is, besides writing a little more code, you do have to relearn how forms work. However, this will open up possibilities for much larger and more dynamic forms as you go on.
If you have any questions or want to point out some errors, go ahead. I just typed up the above code based on something I did myself this past week with the names changed and other misc. properties left out, but it should be straightforward. The only major difference between the above code and my own is that I moved all of the form-building to a separate service that's called from the component so it's a bit less messy.
How to cast ArrayList<> from List<>
You can cast List<> to ArrayList<> if you understand what you doing. Java compiler won't block it.
But:
- It's bad practice to casting parent type to child type (or interface to implementation type) without checking.
This way better:
if (list instanceof ArrayList<Task>) {
ArrayList<Task> arraylist = (ArrayList<Task>) list;
}
- Maybe you don't need implementation type as reference. Look SonarQube warning https://sbforge.org/sonar/rules/show/squid:S1319. You can avoid this casting in the most cases.
- You can use Guava method:
ArrayList<Task> arraylist = Lists.newArrayList(list);
Can't connect to Postgresql on port 5432
You have to edit postgresql.conf file and change line with 'listen_addresses'.
This file you can find in the /etc/postgresql/9.3/main
directory.
Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:
listen_addresses = '*'
Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:
host all all 192.168.1.0/24 md5
Please, read comments in this file...
EDIT:
After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.
EDIT2: Highlited configuration files.
What is the best workaround for the WCF client `using` block issue?
I'd like to add implementation of Service from Marc Gravell's answer for case of using ServiceClient instead of ChannelFactory.
public interface IServiceConnector<out TServiceInterface>
{
void Connect(Action<TServiceInterface> clientUsage);
TResult Connect<TResult>(Func<TServiceInterface, TResult> channelUsage);
}
internal class ServiceConnector<TService, TServiceInterface> : IServiceConnector<TServiceInterface>
where TServiceInterface : class where TService : ClientBase<TServiceInterface>, TServiceInterface, new()
{
public TResult Connect<TResult>(Func<TServiceInterface, TResult> channelUsage)
{
var result = default(TResult);
Connect(channel =>
{
result = channelUsage(channel);
});
return result;
}
public void Connect(Action<TServiceInterface> clientUsage)
{
if (clientUsage == null)
{
throw new ArgumentNullException("clientUsage");
}
var isChanneldClosed = false;
var client = new TService();
try
{
clientUsage(client);
client.Close();
isChanneldClosed = true;
}
finally
{
if (!isChanneldClosed)
{
client.Abort();
}
}
}
}
Django template how to look up a dictionary value with a variable
env: django 2.1.7
view:
dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})
template:
{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>
SQL Query Where Field DOES NOT Contain $x
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
Should try...catch go inside or outside a loop?
All right, after Jeffrey L Whitledge said that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
public class Main {
private static final int NUM_TESTS = 100;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, Jeffrey is correct; there is absolutely no performance difference on Java 6, Sun client VM (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or Ray Hayes's way.
How to get current date in jquery?
function createDate() {
var date = new Date(),
yr = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
todayDate = yr + '-' + month + '-' + day;
console.log("Today date is :" + todayDate);
HTML list-style-type dash
I do not know if there is a better way, but you can create a custom bullet point graphic depicting a dash, and then let the browser know you want to use it in your list with the list-style-type property. An example on that page shows how to use a graphic as a bullet.
I have never tried to use :before in the way you have, although it may work. The downside is that it will not be supported by some older browsers. My gut reaction is that this is still important enough to take into consideration. In the future, this may not be as important.
EDIT: I have done a little testing with the OP's approach. In IE8, I couldn't get the technique to work, so it definitely is not yet cross-browser. Moreover, in Firefox and Chrome, setting list-style-type to none in conjunction appears to be ignored.
Date format Mapping to JSON Jackson
I want to point out that setting a SimpleDateFormat
like described in the other answer only works for a java.util.Date
which I assume is meant in the question.
But for java.sql.Date
the formatter does not work.
In my case it was not very obvious why the formatter did not work because in the model which should be serialized the field was in fact a java.utl.Date
but the actual object ended up beeing a java.sql.Date
.
This is possible because
public class java.sql extends java.util.Date
So this is actually valid
java.util.Date date = new java.sql.Date(1542381115815L);
So if you are wondering why your Date field is not correctly formatted make sure that the object is really a java.util.Date
.
Here is also mentioned why handling java.sql.Date
will not be added.
This would then be breaking change, and I don't think that is warranted. If we were starting from scratch I would agree with the change, but as things are not so much.
How to display Oracle schema size with SQL query?
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Bash script error [: !=: unary operator expected
Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
Passing html values into javascript functions
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
Biggest advantage to using ASP.Net MVC vs web forms
In webforms you could also render almost whole html by hand, except few tags like viewstate, eventvalidation and similar, which can be removed with PageAdapters. Nobody force you to use GridView or some other server side control that has bad html rendering output.
I would say that biggest advantage of MVC is SPEED!
Next is forced separation of concern. But it doesn't forbid you to put whole BL and DAL logic inside Controller/Action! It's just separation of view, which can be done also in webforms (MVP pattern for example). A lot of things that people mentions for mvc can be done in webforms, but with some additional effort.
Main difference is that request comes to controller, not view, and those two layers are separated, not connected via partial class like in webforms (aspx + code behind)
In Java, how can I determine if a char array contains a particular character?
Here's a variation of Oscar's first version that doesn't use a for-each loop.
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'q') {
// do something
break;
}
}
You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.
How to add a constant column in a Spark DataFrame?
As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
You can automatically encode into Json, your complex entity with:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');
Split string and get first value only
These are the two options I managed to build, not having the luxury of working with var
type, nor with additional variables on the line:
string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);
string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
This is what it gets:
Return row of Data Frame based on value in a column - R
Use which.min
:
df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]
> df[which.min(df$Amount),]
Name Amount
2 B 120
From the help docs:
Determines the location, i.e., index of the (first) minimum or maximum
of a numeric (or logical) vector.
Android difference between Two Dates
It will give you difference in months
long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
System.out.println(String.format("%d months", elapsedDays/30));
Where is HttpContent.ReadAsAsync?
You can write extention method:
public static async Task<Tout> ReadAsAsync<Tout>(this System.Net.Http.HttpContent content) {
return Newtonsoft.Json.JsonConvert.DeserializeObject<Tout>(await content.ReadAsStringAsync());
}
Set textbox to readonly and background color to grey in jquery
As per you question this is what you can do
HTML
<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>
JS/Jquery
$(function () {
$('#sample').attr('readonly', 'true'); // mark it as read only
$('#sample').css('background-color' , '#DEDEDE'); // change the background color
});
or add a class in you css with the required styling
$('#sample').addClass('yourclass');
DEMO
Let me know if the requirement was different
LINQ to read XML
Try this.
using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
Can I display the value of an enum with printf()?
The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.
Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:
main.c:
#include "Enum.h"
CreateEnum(
EnumerationName,
ENUMValue1,
ENUMValue2,
ENUMValue3);
int main(void)
{
int i;
EnumerationName EnumInstance = ENUMValue1;
/* Prints "ENUMValue1" */
PrintEnumValue(EnumerationName, EnumInstance);
/* Prints:
* ENUMValue1
* ENUMValue2
* ENUMValue3
*/
for (i=0;i<3;i++)
{
PrintEnumValue(EnumerationName, i);
}
return 0;
}
Enum.h:
#include <stdio.h>
#include <string.h>
#ifdef NDEBUG
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name; \
const char Lookup##name[] = \
#__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif
Enum.c
#include "Enum.h"
#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
char *lookup_copy;
int lookup_length;
char *pch;
lookup_length = strlen(lookup);
lookup_copy = malloc((1+lookup_length)*sizeof(char));
strcpy(lookup_copy, lookup);
pch = strtok(lookup_copy," ,");
while (pch != NULL)
{
if (value == 0)
{
printf("%s\n",pch);
break;
}
else
{
pch = strtok(NULL, " ,.-");
value--;
}
}
free(lookup_copy);
}
#endif
Disclaimer: don't do this.
Sorting a tab delimited file
You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.
Beware, though, because copying and pasting from another place generally does not preserve tabs.
There is already an open DataReader associated with this Command which must be closed first
You can use the ToList()
method before the return
statement.
var accounts =
from account in context.Accounts
from guranteer in account.Gurantors
select new AccountsReport
{
CreditRegistryId = account.CreditRegistryId,
AccountNumber = account.AccountNo,
DateOpened = account.DateOpened,
};
return accounts.AsEnumerable()
.Select((account, index) => new AccountsReport()
{
RecordNumber = FormattedRowNumber(account, index + 1),
CreditRegistryId = account.CreditRegistryId,
DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)}).OrderBy(c=>c.FormattedRecordNumber).ThenByDescending(c => c.StateChangeDate).ToList();
public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
{
var dateReported = (from h in context.AccountHistory
where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
select h.LastUpdated).Max();
return dateReported;
}
ng if with angular for string contains
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
- If the needle is not present in the haystack -1 is returned.
- If needle is present at the beginning of the haystack 0 is returned.
- Else the index at which needle is, is returned.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
Android statusbar icons color
if you have API level smaller than 23 than you must use it this way.
it worked for me declare this under v21/style.
<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
<item name="android:windowLightStatusBar" tools:targetApi="23">true</item>
How do I get the day month and year from a Windows cmd.exe script?
You can use simple variable syntax, here is an example:
@echo off
set month=%date:~0,2%
set day=%date:~3,2%
set year=%date:~6,4%
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul
Another option is the for
command, again here is my example:
@echo off
for /f "delims=/ tokens=1-3" %%a in ("%date%") do (
set month=%%a
set day=%%b
set year=%%c
)
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul
Running CMD command in PowerShell
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH
from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Examples
Calling git from a PS script
I had to repackage a git
client wrapped in Chocolatey
(for those who may not know, it's a kind of app-store for Windows) which massively uses PS scripts.
I found out that, once git
is in the PATH
, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git
crt
file in $ca_bundle
variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where
command
$java_exe = cmd.exe /c where java
will store the location of java.exe
file in $java_exe
variable.
What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?
JAVA HOME
is used for setting up the environment variable for JAVA. It means that you are providing a path for compiling a JAVA program and also running the same. So, if you do not set the JAVA HOME( PATH ) and try to run a java or any dependent program in the command prompt.
You will deal with an error as
javac : not recognized as internal or external command
.
Now to set this, Just open your Java jdk then open bin folder then copy the PATH of that bin folder.
Now, go to My computer right click on it----> select properties-----> select Advanced system settings----->Click on Environment Variables------>select New----->give a name in the text box Variable Name and then paste the path in Value.
That's All!!
Append values to query string
The provided answers have issues with relative Url's, such as "/some/path/"
This is a limitation of the Uri and UriBuilder class, which is rather hard to understand, since I don't see any reason why relative urls would be problematic when it comes to query manipulation.
Here is a workaround that works for both absolute and relative paths, written and tested in .NET 4:
(small note: this should also work in .NET 4.5, you will only have to change propInfo.GetValue(values, null)
to propInfo.GetValue(values)
)
public static class UriExtensions{
/// <summary>
/// Adds query string value to an existing url, both absolute and relative URI's are supported.
/// </summary>
/// <example>
/// <code>
/// // returns "www.domain.com/test?param1=val1&param2=val2&param3=val3"
/// new Uri("www.domain.com/test?param1=val1").ExtendQuery(new Dictionary<string, string> { { "param2", "val2" }, { "param3", "val3" } });
///
/// // returns "/test?param1=val1&param2=val2&param3=val3"
/// new Uri("/test?param1=val1").ExtendQuery(new Dictionary<string, string> { { "param2", "val2" }, { "param3", "val3" } });
/// </code>
/// </example>
/// <param name="uri"></param>
/// <param name="values"></param>
/// <returns></returns>
public static Uri ExtendQuery(this Uri uri, IDictionary<string, string> values) {
var baseUrl = uri.ToString();
var queryString = string.Empty;
if (baseUrl.Contains("?")) {
var urlSplit = baseUrl.Split('?');
baseUrl = urlSplit[0];
queryString = urlSplit.Length > 1 ? urlSplit[1] : string.Empty;
}
NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString);
foreach (var kvp in values ?? new Dictionary<string, string>()) {
queryCollection[kvp.Key] = kvp.Value;
}
var uriKind = uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative;
return queryCollection.Count == 0
? new Uri(baseUrl, uriKind)
: new Uri(string.Format("{0}?{1}", baseUrl, queryCollection), uriKind);
}
/// <summary>
/// Adds query string value to an existing url, both absolute and relative URI's are supported.
/// </summary>
/// <example>
/// <code>
/// // returns "www.domain.com/test?param1=val1&param2=val2&param3=val3"
/// new Uri("www.domain.com/test?param1=val1").ExtendQuery(new { param2 = "val2", param3 = "val3" });
///
/// // returns "/test?param1=val1&param2=val2&param3=val3"
/// new Uri("/test?param1=val1").ExtendQuery(new { param2 = "val2", param3 = "val3" });
/// </code>
/// </example>
/// <param name="uri"></param>
/// <param name="values"></param>
/// <returns></returns>
public static Uri ExtendQuery(this Uri uri, object values) {
return ExtendQuery(uri, values.GetType().GetProperties().ToDictionary
(
propInfo => propInfo.Name,
propInfo => { var value = propInfo.GetValue(values, null); return value != null ? value.ToString() : null; }
));
}
}
And here is a suite of unit tests to test the behavior:
[TestFixture]
public class UriExtensionsTests {
[Test]
public void Add_to_query_string_dictionary_when_url_contains_no_query_string_and_values_is_empty_should_return_url_without_changing_it() {
Uri url = new Uri("http://www.domain.com/test");
var values = new Dictionary<string, string>();
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test")));
}
[Test]
public void Add_to_query_string_dictionary_when_url_contains_hash_and_query_string_values_are_empty_should_return_url_without_changing_it() {
Uri url = new Uri("http://www.domain.com/test#div");
var values = new Dictionary<string, string>();
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test#div")));
}
[Test]
public void Add_to_query_string_dictionary_when_url_contains_no_query_string_should_add_values() {
Uri url = new Uri("http://www.domain.com/test");
var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1¶m2=val2")));
}
[Test]
public void Add_to_query_string_dictionary_when_url_contains_hash_and_no_query_string_should_add_values() {
Uri url = new Uri("http://www.domain.com/test#div");
var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test#div?param1=val1¶m2=val2")));
}
[Test]
public void Add_to_query_string_dictionary_when_url_contains_query_string_should_add_values_and_keep_original_query_string() {
Uri url = new Uri("http://www.domain.com/test?param1=val1");
var values = new Dictionary<string, string> { { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1¶m2=val2")));
}
[Test]
public void Add_to_query_string_dictionary_when_url_is_relative_contains_no_query_string_should_add_values() {
Uri url = new Uri("/test", UriKind.Relative);
var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1¶m2=val2", UriKind.Relative)));
}
[Test]
public void Add_to_query_string_dictionary_when_url_is_relative_and_contains_query_string_should_add_values_and_keep_original_query_string() {
Uri url = new Uri("/test?param1=val1", UriKind.Relative);
var values = new Dictionary<string, string> { { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1¶m2=val2", UriKind.Relative)));
}
[Test]
public void Add_to_query_string_dictionary_when_url_is_relative_and_contains_query_string_with_existing_value_should_add_new_values_and_update_existing_ones() {
Uri url = new Uri("/test?param1=val1", UriKind.Relative);
var values = new Dictionary<string, string> { { "param1", "new-value" }, { "param2", "val2" } };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=new-value¶m2=val2", UriKind.Relative)));
}
[Test]
public void Add_to_query_string_object_when_url_contains_no_query_string_should_add_values() {
Uri url = new Uri("http://www.domain.com/test");
var values = new { param1 = "val1", param2 = "val2" };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1¶m2=val2")));
}
[Test]
public void Add_to_query_string_object_when_url_contains_query_string_should_add_values_and_keep_original_query_string() {
Uri url = new Uri("http://www.domain.com/test?param1=val1");
var values = new { param2 = "val2" };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1¶m2=val2")));
}
[Test]
public void Add_to_query_string_object_when_url_is_relative_contains_no_query_string_should_add_values() {
Uri url = new Uri("/test", UriKind.Relative);
var values = new { param1 = "val1", param2 = "val2" };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1¶m2=val2", UriKind.Relative)));
}
[Test]
public void Add_to_query_string_object_when_url_is_relative_and_contains_query_string_should_add_values_and_keep_original_query_string() {
Uri url = new Uri("/test?param1=val1", UriKind.Relative);
var values = new { param2 = "val2" };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1¶m2=val2", UriKind.Relative)));
}
[Test]
public void Add_to_query_string_object_when_url_is_relative_and_contains_query_string_with_existing_value_should_add_new_values_and_update_existing_ones() {
Uri url = new Uri("/test?param1=val1", UriKind.Relative);
var values = new { param1 = "new-value", param2 = "val2" };
var result = url.ExtendQuery(values);
Assert.That(result, Is.EqualTo(new Uri("/test?param1=new-value¶m2=val2", UriKind.Relative)));
}
}
Deleting an SVN branch
From the working copy:
svn rm branches/features
svn commit -m "delete stale feature branch"
What's the difference between session.persist() and session.save() in Hibernate?
From this forum post
persist()
is well defined. It makes a
transient instance persistent.
However, it doesn't guarantee that the
identifier value will be assigned to
the persistent instance immediately,
the assignment might happen at flush
time. The spec doesn't say that, which
is the problem I have with persist()
.
persist()
also guarantees that it will
not execute an INSERT statement if it
is called outside of transaction
boundaries. This is useful in
long-running conversations with an
extended Session/persistence context.
A method like persist()
is required.
save()
does not guarantee the same, it
returns an identifier, and if an
INSERT has to be executed to get the
identifier (e.g. "identity" generator,
not "sequence"), this INSERT happens
immediately, no matter if you are
inside or outside of a transaction.
This is not good in a long-running
conversation with an extended
Session/persistence context.
Creating an empty bitmap and drawing though canvas in Android
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
How do I print the content of httprequest request?
Rewrite @Juned Ahsan solution via stream in one line (headers are treated the same way):
public static String printRequest(HttpServletRequest req) {
String params = StreamSupport.stream(
((Iterable<String>) () -> req.getParameterNames().asIterator()).spliterator(), false)
.map(pName -> pName + '=' + req.getParameter(pName))
.collect(Collectors.joining("&"));
return req.getRequestURI() + '?' + params;
}
See also how to convert an iterator to a stream solution.
Securing a password in a properties file
The poor mans compromise solution is to use a simplistic multi signature approach.
For Example the DBA sets the applications database password to a 50 character random string.
TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU
He or she give half the password to the application developer who then hard codes it into the java binary.
private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"
The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.
java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU
When the application starts it uses pass1 + pass2 and connects to the database.
This solution has many advantages with out the downfalls mentioned.
You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.
The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.
The source code can also be semi public as reading it and the password will not give you application access.
You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.
How to generate access token using refresh token through google drive API?
If you are using web api then you should make a http POST
call to URL : https://www.googleapis.com/oauth2/v4/token
with following request body
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token
refresh token never expires so you can use it any number of times. The response will be a JSON like this:
{
"access_token": "your refreshed access token",
"expires_in": 3599,
"scope": "Set of scope which you have given",
"token_type": "Bearer"
}
Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception
Did you try to specify resource only in context.xml
<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />
and remove <resource-ref>
section from web.xml
?
In one project I've seen configuration without <resource-ref>
section in web.xml
and it worked.
It's an educated guess, but I think <resource-ref>
declaration of JNDI
resource named jdbc/PollDatasource
in web.xml
may override declaration of resource with same name in context.xml
and the declaration in web.xml
is missing both driverClassName
and url
hence the NPEs for that properties.
How to get element value in jQuery
<div class="inter">
<p>Liste des Produits</p>
<ul>
<li><a href="#1">P1</a></li>
<li><a href="#2">P2</a></li>
<li><a href="#3">P3</a></li>
</ul>
</div>
$(document).ready(function(){
$(".inter li").bind(
"click", function(){
alert($(this).children("a").text());
});
});
Adding files to java classpath at runtime
The way I have done this is by using my own class loader
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);
And create the following class:
public class DynamicURLClassLoader extends URLClassLoader {
public DynamicURLClassLoader(URLClassLoader classLoader) {
super(classLoader.getURLs());
}
@Override
public void addURL(URL url) {
super.addURL(url);
}
}
Works without any reflection
Jackson serialization: ignore empty values (or null)
I was having similar problem recently with version 2.6.6.
@JsonInclude(JsonInclude.Include.NON_NULL)
Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.
I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.
So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.
How to add values in a variable in Unix shell scripting?
I don't have a unix system under my hands, but try this:
count7=$((${count7} + ${count1}))
Or maybe you have a shell that doesn't support this expression.
I think bash
does support it, but sh
doesn't.
EDIT: There is another syntax, try:
count7=`expr $count7 + $count1`
use current date as default value for a column
Table creation Syntax can be like:
Create table api_key(api_key_id INT NOT NULL IDENTITY(1,1)
PRIMARY KEY, date_added date DEFAULT
GetDate());
Insertion query syntax can be like:
Insert into api_key values(GETDATE());
Inserting multiple rows in a single SQL query?
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
How can I build XML in C#?
For simple cases, I would also suggest looking at XmlOutput a fluent interface for building Xml.
XmlOutput is great for simple Xml creation with readable and maintainable code, while generating valid Xml. The orginal post has some great examples.
equivalent of rm and mv in windows .cmd
move
and del
ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move
command. And the same thing applies with del
.
The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.
mv
and rm
are in the CoreUtils package and they work wonderfully!
Safe String to BigDecimal conversion
The code could be cleaner, but this seems to do the trick for different locales.
import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Main
{
public static void main(String[] args)
{
final BigDecimal numberA;
final BigDecimal numberB;
numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
System.out.println(numberA);
System.out.println(numberB);
}
private static BigDecimal stringToBigDecimal(final String formattedString,
final Locale locale)
{
final DecimalFormatSymbols symbols;
final char groupSeparatorChar;
final String groupSeparator;
final char decimalSeparatorChar;
final String decimalSeparator;
String fixedString;
final BigDecimal number;
symbols = new DecimalFormatSymbols(locale);
groupSeparatorChar = symbols.getGroupingSeparator();
decimalSeparatorChar = symbols.getDecimalSeparator();
if(groupSeparatorChar == '.')
{
groupSeparator = "\\" + groupSeparatorChar;
}
else
{
groupSeparator = Character.toString(groupSeparatorChar);
}
if(decimalSeparatorChar == '.')
{
decimalSeparator = "\\" + decimalSeparatorChar;
}
else
{
decimalSeparator = Character.toString(decimalSeparatorChar);
}
fixedString = formattedString.replaceAll(groupSeparator , "");
fixedString = fixedString.replaceAll(decimalSeparator , ".");
number = new BigDecimal(fixedString);
return (number);
}
}
How to update core-js to core-js@3 dependency?
Install
npm i core-js
Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.
Read: https://www.npmjs.com/package/core-js
How to convert time milliseconds to hours, min, sec format in JavaScript?
Worked for me
msToTime(milliseconds) {
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}
Make div fill remaining space along the main axis in flexbox
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
_x000D_
_x000D_
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_
Create directory if it does not exist
[System.IO.Directory]::CreateDirectory('full path to directory')
This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.
How can I generate a list of consecutive numbers?
Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.
list = []
calc = 0
while int(calc) < 9:
list.append(calc)
calc = int(calc) + 1
print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]
The import com.google.android.gms cannot be resolved
In my case only after I added gcm.jar
to lib folder, it started to work.
It was here: C:\adt-bundle-windows-x86_64-20131030\sdk\extras\google\gcm\gcm-client\dist
So the google-play-services.jar
didn't work...
Laravel assets url
Besides put all your assets in the public folder, you can use the HTML::image()
Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('imgs/picture.jpg') }}
Which generates the follow HTML code:
<img src="http://localhost:8000/imgs/picture.jpg">
The link to other elements of HTML::image()
Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element
How to read text files with ANSI encoding and non-English letters?
If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding.
You would have to create a StreamReader with the correct encoding and use that as the parameter.
xmlDoc.Load(new StreamReader(
File.Open("file.xml"),
Encoding.GetEncoding("iso-8859-15")));
I just stumbled across KB308061 from Microsoft. There's an interesting passage:
Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:
<?xml version="1.0" encoding="UTF-16"?>
Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.
Link Source:
XmlDocument.Load() method fails to decode € (euro)
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
JQuery create new select option
Something like:
function populate(selector) {
$(selector)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
populate('#myform .myselect');
Or even:
$.fn.populate = function() {
$(this)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
$('#myform .myselect').populate();
How can I print literal curly-brace characters in a string and also use .format on it?
I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:
Lets say you want to print out a product of mulitple variables with indices such as
, which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$
The following code does the job with named fields so that for many indices it stays readable:
idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
how to stop Javascript forEach?
var f = "how to stop Javascript forEach?".split(' ');
f.forEach(function (a,b){
console.info(b+1);
if (a == 'stop') {
console.warn("\tposition: \'stop\'["+(b+1)+"] \r\n\tall length: " + (f.length));
f.length = 0; //<--!!!
}
});
JavaScript: IIF like statement
I typed this in my URL bar:
javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }
How to create a showdown.js markdown extension
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
AngularJS view not updating on model change
setTimout
executes outside of angular. You need to use $timeout
service for this to work:
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $timeout) {
$scope.testValue = 0;
$timeout(function() {
console.log($scope.testValue++);
}, 500);
});
The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply()
kicks off a $digest
cycle. This will apply the binding. $timeout
handles the $apply
for you so it is the recommended service to use when using timeouts.
Essentially, binding happens during the $digest
cycle (if the value is seen to be different).
Ajax success event not working
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
- The result was not being returned in JSON format
- I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
Set equal width of columns in table layout in Android
Try this.
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
How to make a JTable non-editable
If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:
JTable table = new JTable(my_rows, my_header);
for (int c = 0; c < table.getColumnCount(); c++)
{
Class<?> col_class = table.getColumnClass(c);
table.setDefaultEditor(col_class, null); // remove editor
}
Without editors, data will be not editable.
SQL Server: combining multiple rows into one row
_x000D_
_x000D_
declare @maxColumnCount int=0;
declare @Query varchar(max)='';
declare @DynamicColumnName nvarchar(MAX)='';
-- table type variable that store all values of column row no
DECLARE @TotalRows TABLE( row_count int)
INSERT INTO @TotalRows (row_count)
SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma
-- Get the MAX value from @TotalRows table
set @maxColumnCount= (select max(row_count) from @TotalRows)
-- loop to create Dynamic max/case and store it into local variable
DECLARE @cnt INT = 1;
WHILE @cnt <= @maxColumnCount
BEGIN
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''
SET @cnt = @cnt + 1;
END;
-- Create dynamic CTE and store it into local variable @query
set @Query='
with CTE_tbl as
(
SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
FROM tblExportPartProforma
)
select
InvoiceNo
'+@DynamicColumnName+'
FROM CTE_tbl
group By InvoiceNo'
-- Execute the Query
execute (@Query)
_x000D_
_x000D_
_x000D_
onclick event pass <li> id or value
Try this:
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
function getPaging(str)
{
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
How to search in array of object in mongodb
You can do this in two ways:
ElementMatch - $elemMatch
(as explained in above answers)
db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })
Use $and
with find
db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})
Find methods calls in Eclipse project
You can also search for specific methods. For e.g. If you want to search for isEmpty()
method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty()
and in the 'Search For' option use Method.
You can then select the scope that you require.
How do I change the default library path for R packages
See help(Startup)
and help(.libPaths)
as you have several possibilities where this may have gotten set. Among them are
- setting
R_LIBS_USER
- assigning
.libPaths()
in .Rprofile
or Rprofile.site
and more.
In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want
is set.
To otherwise ignore it you need to override it use explicitly i.e. via
library("somePackage", lib.loc=.libPaths()[-1])
when loading a package.
Rails 4: before_filter vs. before_action
before_filter/before_action: means anything to be executed before any action executes.
Both are same. they are just alias for each other as their behavior is same.
Script Tag - async & defer
Rendering engine goes several steps till it paints anything on the screen.
it looks like this:
- Converting HTML bytes to characters depending on encoding we set to the document;
- Tokens are created according to characters. Tokens mean analyze characters and specify opening tangs and nested tags;
- From tokens separated nodes are created. they are objects and according to information delivered from tokenization process, engine creates objects which includes all necessary information about each node;
- after that DOM is created. DOM is tree data structure and represents whole hierarchy and information about relationship and specification of tags;
The same process goes to CSS. for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model)
Browser works only with Object models so it needs to know all information about DOM and CSSDOM.
The next step is combining somehow DOM and CSSOM. because without CSSOM browser do not know how to style each element during rendering process.
All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process. If you are familiar with event loop, there is simple rule how event loop executes tasks:
- Execute macro tasks;
- execute micro tasks;
- Rendering;
So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.
Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering. it will find out Script tag and will stop until JS is done.
But HTML provided two additional options for script tag: async and defer.
Async - means execute code when it is downloaded and do not block DOM construction during downloading process.
Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.
PHP 7 RC3: How to install missing MySQL PDO
I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.
Hope this helps!
Where to find extensions installed folder for Google Chrome on Mac?
They are found on either one of the below locations depending on how chrome was installed
- When chrome is installed at the user level, it's located at:
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
- When installed at the root level, it's at:
/Library/Application\ Support/Google/Chrome/Default/Extensions
How can I enable CORS on Django REST Framework
Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0
Follow the official instruction doesn't work
Finally use the old way to figure it out.
ADD:
# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
#proj/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'proj.middlewares.CsrfExemptSessionAuthentication',
),
}
What's the best practice using a settings file in Python?
Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.
>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))
{u'handler': u'adminhandler.py', u'timeoutsec': 5}
Maintaining href "open in new tab" with an onClick handler in React
Most Secure Solution, JS only
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Add day(s) to a Date object
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
Getting the source HTML of the current page from chrome extension
Here is my solution:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
Git copy file preserving history
I've slightly modified Peter's answer here to create a reusable, non-interactive shell script called git-split.sh
:
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv "$1" "$2"
git commit -n -m "Split history $1 to $2 - rename file to target-name"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv "$1" temp
git commit -n -m "Split history $1 to $2 - rename source-file to temp"
git merge $REV
git commit -a -n -m "Split history $1 to $2 - resolve conflict and keep both files"
git mv temp "$1"
git commit -n -m "Split history $1 to $2 - restore name of source-file"
When to use 'raise NotImplementedError'?
As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.
There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.
Here's a Python 3 example:
class C(abc.ABC):
@abc.abstractmethod
def my_abstract_method(self, ...):
...
When instantiating C
, you'll get an error because my_abstract_method
is abstract. You need to implement it in a child class.
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
Subclass C
and implement my_abstract_method
.
class D(C):
def my_abstract_method(self, ...):
...
Now you can instantiate D
.
C.my_abstract_method
does not have to be empty. It can be called from D
using super()
.
An advantage of this over NotImplementedError
is that you get an explicit Exception
at instantiation time, not at method call time.
How do I use ROW_NUMBER()?
ROW_NUMBER()
returns a unique number for each row starting with 1. You can easily use this by simply writing:
ROW_NUMBER() OVER (ORDER BY 'Column_Name' DESC) as ROW_NUMBER
How to filter array in subdocument with MongoDB
Using aggregate
is the right approach, but you need to $unwind
the list
array before applying the $match
so that you can filter individual elements and then use $group
to put it back together:
db.test.aggregate([
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $unwind: '$list'},
{ $match: {'list.a': {$gt: 3}}},
{ $group: {_id: '$_id', list: {$push: '$list.a'}}}
])
outputs:
{
"result": [
{
"_id": ObjectId("512e28984815cbfcb21646a7"),
"list": [
4,
5
]
}
],
"ok": 1
}
MongoDB 3.2 Update
Starting with the 3.2 release, you can use the new $filter
aggregation operator to do this more efficiently by only including the list
elements you want during a $project
:
db.test.aggregate([
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $project: {
list: {$filter: {
input: '$list',
as: 'item',
cond: {$gt: ['$$item.a', 3]}
}}
}}
])