Rename a dictionary key
In case someone wants to rename all the keys at once providing a list with the new names:
def rename_keys(dict_, new_keys):
"""
new_keys: type List(), must match length of dict_
"""
# dict_ = {oldK: value}
# d1={oldK:newK,} maps old keys to the new ones:
d1 = dict( zip( list(dict_.keys()), new_keys) )
# d1{oldK} == new_key
return {d1[oldK]: value for oldK, value in dict_.items()}
Can I get JSON to load into an OrderedDict?
The normally used load command will work if you specify the object_pairs_hook parameter:
import json
from collections import OrderedDict
with open('foo.json', 'r') as fp:
metrics_types = json.load(fp, object_pairs_hook=OrderedDict)
Converting dict to OrderedDict
You are creating a dictionary first, then passing that dictionary to an OrderedDict
. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict
is inherently not ordered.
Pass in a sequence of tuples instead:
ship = [("NAME", "Albatross"),
("HP", 50),
("BLASTERS", 13),
("THRUSTERS", 18),
("PRICE", 250)]
ship = collections.OrderedDict(ship)
What you see when you print the OrderedDict
is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
just shows you, in a reproducable representation, what the contents are of the OrderedDict
.
(*): In the CPython 3.6 implementation, the dict
type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict()
for certain cases.
Accessing items in an collections.OrderedDict by index
It is dramatically more efficient to use IndexedOrderedDict from the indexed
package.
Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.
In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop
In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop
IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.
How to convert an OrderedDict into a regular dict in python3
Here is what seems simplest and works in python 3.7
from collections import OrderedDict
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d) # Now a normal dict
Now to check this:
>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True
NOTE: This also works, and gives same result -
>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True
As well as this -
>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True
Cheers
Getting Gradle dependencies in IntelliJ IDEA using Gradle build
When importing an existing Gradle project (one with a build.gradle
) into IntelliJ IDEA, when presented with the following screen, select Import from external model -> Gradle.
![Import project from external model](https://i.stack.imgur.com/1IuPt.png)
Optionally, select Auto Import on the next screen to automatically import new dependencies.
Table with table-layout: fixed; and how to make one column wider
You could just give the first cell (therefore column) a width and have the rest default to auto
_x000D_
_x000D_
table {_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
width: 150px;_x000D_
}_x000D_
td+td {_x000D_
width: auto;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>150px</td>_x000D_
<td>equal</td>_x000D_
<td>equal</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
or alternatively the "proper way" to get column widths might be to use the col
element itself
_x000D_
_x000D_
table {_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
width: 150px;_x000D_
}
_x000D_
<table>_x000D_
<col span="1" class="wide">_x000D_
<tr>_x000D_
<td>150px</td>_x000D_
<td>equal</td>_x000D_
<td>equal</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
why is plotting with Matplotlib so slow?
For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.
So just put the background line after the canvas.draw():
[...]
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)
As @idleberg mentions, on Mac OS, it is best to install rbenv to avoid permissions errors when using manually installed ruby.
Installation
$ brew update
$ brew install rbenv
Add the following in .bashrc
file:
eval "$(rbenv init -)"
Now, we can look at the list of ruby versions available for install
$ rbenv install -l
Install version 2.3.8 for example
$ rbenv install 2.3.8
Now we can use this ruby version globally
$ rbenv global 2.3.8
Finally run
$ rbenv rehash
$ which ruby
/Users/myuser/.rbenv/shims/ruby
$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [x86_64-darwin17]
Go for it
Now install bundler
$ gem install bundler
All done!
Open another page in php
Use something like header( 'Location: /my-other-page.html' );
to redirect. You can't have sent any other data on the page before you do this though.
How do I find the size of a struct?
This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment.
Understanding Chrome network log "Stalled" state
https://developers.google.com/web/tools/chrome-devtools/network-performance/understanding-resource-timing
This comes from the official site of Chome-devtools and it helps.
Here i quote:
- Queuing
If a request is queued it indicated that:
- The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
- The request was put on hold to wait for an unavailable TCP socket that's about to free up.
- The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1.
Time spent making disk cache entries (typically very quick.)
- Stalled/Blocking
Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.
Cannot Resolve Collation Conflict
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
Best way to incorporate Volley (or other library) into Android Studio project
I have set up Volley as a separate Project. That way its not tied to any project and exist independently.
I also have a Nexus server (Internal repo) setup so I can access volley as
compile 'com.mycompany.volley:volley:1.0.4' in any project I need.
Any time I update Volley project, I just need to change the version number in other projects.
I feel very comfortable with this approach.
Reading settings from app.config or web.config in .NET
I strongly recommend you to create a wrapper for this call. Something like a ConfigurationReaderService
and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.
So use the ConfigurationManager.AppSettings["something"];
suggested and return this value. With this method you can create some kind of default return if there isn't any key available in the .config file.
How to create a property for a List<T>
You could do this but the T
generic parameter needs to be declared at the containing class:
public class Foo<T>
{
public List<T> NewList { get; set; }
}
How to disable mouse scroll wheel scaling with Google Maps API
Use that piece of code, that will give you all the color and zooming control of google map. (scaleControl: false and scrollwheel: false will prevent the mousewheel from zoom up or down)
_x000D_
_x000D_
function initMap() {_x000D_
// Styles a map in night mode._x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
center: {lat: 23.684994, lng: 90.356331},_x000D_
zoom: 8,_x000D_
scaleControl: false,_x000D_
scrollwheel: false,_x000D_
styles: [_x000D_
{elementType: 'geometry', stylers: [{color: 'F1F2EC'}]},_x000D_
{elementType: 'labels.text.stroke', stylers: [{color: '877F74'}]},_x000D_
{elementType: 'labels.text.fill', stylers: [{color: '877F74'}]},_x000D_
{_x000D_
featureType: 'administrative.locality',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#d59563'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#d59563'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi.park',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#263c3f'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi.park',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'geometry.stroke',_x000D_
stylers: [{color: '#212a37'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#746855'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'geometry.stroke',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'transit',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#2f3948'}]_x000D_
},_x000D_
{_x000D_
featureType: 'transit.station',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b3'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#0676b6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#515c6d'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'labels.text.stroke',_x000D_
stylers: [{color: '#17263c'}]_x000D_
}_x000D_
]_x000D_
});_x000D_
_x000D_
var marker = new google.maps.Marker({_x000D_
position: {lat: 23.684994, lng: 90.356331},_x000D_
map: map,_x000D_
title: 'BANGLADESH'_x000D_
});_x000D_
}
_x000D_
_x000D_
_x000D_
Fill remaining vertical space with CSS using display:flex
The example below includes scrolling behaviour if the content of the expanded centre component extends past its bounds. Also the centre component takes 100% of remaining space in the viewport.
jsfiddle here
html, body, .r_flex_container{
height: 100%;
display: flex;
flex-direction: column;
background: red;
margin: 0;
}
.r_flex_container {
display:flex;
flex-flow: column nowrap;
background-color:blue;
}
.r_flex_fixed_child {
flex:none;
background-color:black;
color:white;
}
.r_flex_expand_child {
flex:auto;
background-color:yellow;
overflow-y:scroll;
}
Example of html that can be used to demonstrate this behaviour
<html>
<body>
<div class="r_flex_container">
<div class="r_flex_fixed_child">
<p> This is the fixed 'header' child of the flex container </p>
</div>
<div class="r_flex_expand_child">
<article>this child container expands to use all of the space given to it - but could be shared with other expanding childs in which case they would get equal space after the fixed container space is allocated.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
</article>
</div>
<div class="r_flex_fixed_child">
this is the fixed footer child of the flex container
asdfadsf
<p> another line</p>
</div>
</div>
</body>
</html>
Selecting a Linux I/O Scheduler
It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like
# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"
inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules
). This answer is based on the debian wiki
To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:
for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done
Creating multiline strings in JavaScript
the pattern text = <<"HERE" This Is A Multiline String HERE
is not available in js (I remember using it much in my good old Perl days).
To keep oversight with complex or long multiline strings I sometimes use an array pattern:
var myString =
['<div id="someId">',
'some content<br />',
'<a href="#someRef">someRefTxt</a>',
'</div>'
].join('\n');
or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:
var myString =
'<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';
Here's another weird but working 'trick'1:
var myString = (function () {/*
<div id="someId">
some content<br />
<a href="#someRef">someRefTxt</a>
</div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
external edit: jsfiddle
ES20xx supports spanning strings over multiple lines using template strings:
let str = `This is a text
with multiple lines.
Escapes are interpreted,
\n is a newline.`;
let str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.`;
1 Note: this will be lost after minifying/obfuscating your code
How to extract the year from a Python datetime object?
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
How can I add raw data body to an axios request?
The key is to use "Content-Type": "text/plain"
as mentioned by @MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET
is that a raw string to a controller will return 415 Unsupported Media Type
. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json"
:
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Switch statement for string matching in JavaScript
You can't do it in a switch
unless you're doing full string matching; that's doing substring matching. (This isn't quite true, as Sean points out in the comments. See note at the end.)
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching. It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):
function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
change <audio> src with javascript
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps
I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.
@propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt @props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
Histogram with Logarithmic Scale and custom breaks
I've put together a function that behaves identically to hist in the default case, but accepts the log argument. It uses several tricks from other posters, but adds a few of its own. hist(x)
and myhist(x)
look identical.
The original problem would be solved with:
myhist(mydata$V3, breaks=c(0,1,2,3,4,5,25), log="xy")
The function:
myhist <- function(x, ..., breaks="Sturges",
main = paste("Histogram of", xname),
xlab = xname,
ylab = "Frequency") {
xname = paste(deparse(substitute(x), 500), collapse="\n")
h = hist(x, breaks=breaks, plot=FALSE)
plot(h$breaks, c(NA,h$counts), type='S', main=main,
xlab=xlab, ylab=ylab, axes=FALSE, ...)
axis(1)
axis(2)
lines(h$breaks, c(h$counts,NA), type='s')
lines(h$breaks, c(NA,h$counts), type='h')
lines(h$breaks, c(h$counts,NA), type='h')
lines(h$breaks, rep(0,length(h$breaks)), type='S')
invisible(h)
}
Exercise for the reader: Unfortunately, not everything that works with hist works with myhist as it stands. That should be fixable with a bit more effort, though.
Warning message: In `...` : invalid factor level, NA generated
I have got similar issue which data retrieved from .xlsx file. Unfortunately, I could not find the proper answer here. I handled it on my own with dplyr as below which might help others:
#install.packages("xlsx")
library(xlsx)
extracted_df <- read.xlsx("test.xlsx", sheetName='Sheet1', stringsAsFactors=FALSE)
# Replace all NAs in a data frame with "G" character
extracted_df[is.na(extracted_df)] <- "G"
However, I could not handle it with the readxl
package which does not have similar parameter to the stringsAsFactors
. For the reason, I have moved to the xlsx
package.
PHP MySQL Google Chart JSON - Complete Example
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
What is the recommended way to delete a large number of items from DynamoDB?
Thought about using the test to pass in the vars? Something like:
Test input would be something like:
{
"TABLE_NAME": "MyDevTable",
"PARTITION_KEY": "REGION",
"SORT_KEY": "COUNTRY"
}
Adjusted your code to accept the inputs:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });
exports.handler = async (event) => {
const TABLE_NAME = event.TABLE_NAME;
const PARTITION_KEY = event.PARTITION_KEY;
const SORT_KEY = event.SORT_KEY;
let params = {
TableName: TABLE_NAME,
};
console.log(`keys: ${PARTITION_KEY} ${SORT_KEY}`);
let items = [];
let data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
while (typeof data.LastEvaluatedKey != 'undefined') {
params.ExclusiveStartKey = data.LastEvaluatedKey;
data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
}
let leftItems = items.length;
let group = [];
let groupNumber = 0;
console.log('Total items to be deleted', leftItems);
for (const i of items) {
// console.log(`item: ${i[PARTITION_KEY] } ${i[SORT_KEY]}`);
const deleteReq = {DeleteRequest: {Key: {},},};
deleteReq.DeleteRequest.Key[PARTITION_KEY] = i[PARTITION_KEY];
deleteReq.DeleteRequest.Key[SORT_KEY] = i[SORT_KEY];
// console.log(`DeleteRequest: ${JSON.stringify(deleteReq)}`);
group.push(deleteReq);
leftItems--;
if (group.length === 25 || leftItems < 1) {
groupNumber++;
console.log(`Batch ${groupNumber} to be deleted.`);
const params = {
RequestItems: {
[TABLE_NAME]: group,
},
};
await docClient.batchWrite(params).promise();
console.log(
`Batch ${groupNumber} processed. Left items: ${leftItems}`
);
// reset
group = [];
}
}
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Can't subtract offset-naive and offset-aware datetimes
The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:
def pg_utcnow():
import psycopg2
return datetime.utcnow().replace(
tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))
and just use pg_utcnow
whenever you need the current time to compare against a PostgreSQL timestamptz
Jquery change <p> text programmatically
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
Inserting Data Into a MySQL Database using PHP
ReactJS call parent method
You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:
var Parent = React.createClass({
someMethod: function(value) {
console.log("value from child", value)
},
someMethod2: function(value) {
console.log("second method used", value)
},
render: function() {
return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
}
});
And use it into the Child like this (for any actions or into any child methods):
var Child = React.createClass({
getInitialState: function() {
return {
value: 'bar'
}
},
render: function() {
return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
}
});
mean() warning: argument is not numeric or logical: returning NA
From R 3.0.0 onwards mean(<data.frame>)
is defunct (and passing a data.frame to mean
will give the error you state)
A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".
In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following
lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
run program in Python shell
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
Flask SQLAlchemy query, specify column names
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
Find the last time table was updated
If you want to see data updates you could use this technique with required permissions:
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASE')
AND OBJECT_ID=OBJECT_ID('TABLE')
How do I do a case-insensitive string comparison?
Section 3.13 of the Unicode standard defines algorithms for caseless
matching.
X.casefold() == Y.casefold()
in Python 3 implements the "default caseless matching" (D144).
Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å'
vs. 'a°'
). D145 introduces "canonical caseless matching":
import unicodedata
def NFD(text):
return unicodedata.normalize('NFD', text)
def canonical_caseless(text):
return NFD(NFD(text).casefold())
NFD()
is called twice for very infrequent edge cases involving U+0345 character.
Example:
>>> 'å'.casefold() == 'a°'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('a°')
True
There are also compatibility caseless matching (D146) for cases such as '?'
(U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.
How to move all HTML element children to another parent using JavaScript?
If you not use -
in id's names then you can do this
_x000D_
_x000D_
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
<span>Foo</span>_x000D_
<b>Bar</b>_x000D_
Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
_x000D_
_x000D_
When should I use Kruskal as opposed to Prim (and vice versa)?
Use Prim's algorithm when you have a graph with lots of edges.
For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.
Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.
Can I use DIV class and ID together in CSS?
Yes, yes you can.
#y.x {
/* will select element of id="y" that also has class="x" */
}
Similarly:
.x#y {
/* will select elements of class="x" that also have an id="y" */
}
Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since id
s are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
@aravk33 's answer is absolutely correct.
I was going through the same problem. I had a data set of 2450 images. I just could not figure out why I was facing this issue.
Check the dimensions of all the images in your training data.
Add the following snippet while appending your image into your list:
if image.shape==(1,512,512):
trainx.append(image)
Make an Installation program for C# applications and include .NET Framework installer into the setup
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
![enter image description here](https://i.stack.imgur.com/3paMR.png)
Select project type.
![enter image description here](https://i.stack.imgur.com/i6it2.png)
Select output.
![enter image description here](https://i.stack.imgur.com/5RDGP.png)
Hit Finish.
Open setup project properties.
![enter image description here](https://i.stack.imgur.com/VtesJ.png)
Chose to include .NET framework.
![enter image description here](https://i.stack.imgur.com/zKVrY.png)
Build setup project
Check output
![enter image description here](https://i.stack.imgur.com/4YbgN.png)
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
Styling twitter bootstrap buttons
Basically, the buttons in Twitter Bootstrap are controlled in CSS by ".btn{}". What you have to do is go to the CSS file and find where it says "btn" and change the color settings. However, it's not as simple as just doing that since you also have to change what color the button changes into when you highlight it, etc. To do THAT, you have to look for other tags in CSS like ".btn:hover{}", etc.
Changing it requires changing of the CSS. Here is a quick link to that file:
https://github.com/twbs/bootstrap/blob/master/dist/css/bootstrap.css
Read .csv file in C
Hopefully this would get you started
See it live on http://ideone.com/l23He (using stdin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ";");
tok && *tok;
tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %s\n", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}
Output:
Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak
How to open .mov format video in HTML video Tag?
Content Type for MOV videos are video/quicktime in my case. Adding type="video/mp4" to MOV video file solved issue in my case.
<video width="400" controls Autoplay=autoplay>
<source src="D:/mov1.mov" type="video/mp4">
</video>
Retrofit 2.0 how to get deserialised error response.body
I was facing same issue. I solved it with retrofit. Let me show this...
If your error JSON structure are like
{
"error": {
"status": "The email field is required."
}
}
My ErrorRespnce.java
public class ErrorResponse {
@SerializedName("error")
@Expose
private ErrorStatus error;
public ErrorStatus getError() {
return error;
}
public void setError(ErrorStatus error) {
this.error = error;
}
}
And this my Error status class
public class ErrorStatus {
@SerializedName("status")
@Expose
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Now we need a class which can handle our json.
public class ErrorUtils {
public static ErrorResponse parseError (Response<?> response){
Converter<ResponseBody , ErrorResponse> converter = ApiClient.getClient().responseBodyConverter(ErrorResponse.class , new Annotation[0]);
ErrorResponse errorResponse;
try{
errorResponse = converter.convert(response.errorBody());
}catch (IOException e){
return new ErrorResponse();
}
return errorResponse;
}
}
Now we can check our response in retrofit api call
private void registrationRequest(String name , String email , String password , String c_password){
final Call<RegistrationResponce> registrationResponceCall = apiInterface.getRegistration(name , email , password , c_password);
registrationResponceCall.enqueue(new Callback<RegistrationResponce>() {
@Override
public void onResponse(Call<RegistrationResponce> call, Response<RegistrationResponce> response) {
if (response.code() == 200){
}else if (response.code() == 401){
ErrorResponse errorResponse = ErrorUtils.parseError(response);
Toast.makeText(MainActivity.this, ""+errorResponse.getError().getStatus(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<RegistrationResponce> call, Throwable t) {
}
});
}
That's it now you can show your Toast
How to show all of columns name on pandas dataframe?
To get all column name you can iterate over the data_all2.columns
.
columns = data_all2.columns
for col in columns:
print col
You will get all column names.
Or you can store all column names to another list variable and then print list.
Android – Listen For Incoming SMS Messages
public class SmsListener extends BroadcastReceiver{
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
Note: In your manifest file add the BroadcastReceiver-
<receiver android:name=".listener.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add this permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Get all column names of a DataTable into string array using (LINQ/Predicate)
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
Stopping fixed position scrolling at a certain point?
I liked this solution
$(window).scroll(function(){
$("#theFixed").css("margin-top",Math.max(-250,0-$(this).scrollTop()));
});
my problem was that I had to deal with a position relative container in Adobe Muse.
My solution:
$(window).scroll(function(){
if($(this).scrollTop()>425) {
$("#theRelative").css("margin-top",$(this).scrollTop()-425);
}
});
how to know status of currently running jobs
We've found and have been using this code for a good solution. This code will start a job, and monitor it, killing the job automatically if it exceeds a time limit.
/****************************************************************
--This SQL will take a list of SQL Agent jobs (names must match),
--start them so they're all running together, and then
--monitor them, not quitting until all jobs have completed.
--
--In essence, it's an SQL "watchdog" loop to start and monitor SQL Agent Jobs
--
--Code from http://cc.davelozinski.com/code/sql-watchdog-loop-start-monitor-sql-agent-jobs
--
****************************************************************/
SET NOCOUNT ON
-------- BEGIN ITEMS THAT NEED TO BE CONFIGURED --------
--The amount of time to wait before checking again
--to see if the jobs are still running.
--Should be in hh:mm:ss format.
DECLARE @WaitDelay VARCHAR(8) = '00:00:20'
--Job timeout. Eg, if the jobs are running longer than this, kill them.
DECLARE @TimeoutMinutes INT = 240
DECLARE @JobsToRunTable TABLE
(
JobName NVARCHAR(128) NOT NULL,
JobID UNIQUEIDENTIFIER NULL,
Running INT NULL
)
--Insert the names of the SQL jobs here. Last two values should always be NULL at this point.
--Names need to match exactly, so best to copy/paste from the SQL Server Agent job name.
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfFirstSQLAgentJobToRun',NULL,NULL)
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfSecondSQLAgentJobToRun',NULL,NULL)
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfXSQLAgentJobToRun',NULL,NULL)
-------- NOTHING FROM HERE DOWN SHOULD NEED TO BE CONFIGURED --------
DECLARE @ExecutionStatusTable TABLE
(
JobID UNIQUEIDENTIFIER PRIMARY KEY, -- Job ID which will be a guid
LastRunDate INT, LastRunTime INT, -- Last run date and time
NextRunDate INT, NextRunTime INT, -- Next run date and time
NextRunScheduleID INT, -- an internal schedule id
RequestedToRun INT, RequestSource INT, RequestSourceID VARCHAR(128),
Running INT, -- 0 or 1, 1 means the job is executing
CurrentStep INT, -- which step is running
CurrentRetryAttempt INT, -- retry attempt
JobState INT -- 0 = Not idle or suspended, 1 = Executing, 2 = Waiting For Thread,
-- 3 = Between Retries, 4 = Idle, 5 = Suspended,
-- 6 = WaitingForStepToFinish, 7 = PerformingCompletionActions
)
DECLARE @JobNameToRun NVARCHAR(128) = NULL
DECLARE @IsJobRunning BIT = 1
DECLARE @AreJobsRunning BIT = 1
DECLARE @job_owner sysname = SUSER_SNAME()
DECLARE @JobID UNIQUEIDENTIFIER = null
DECLARE @StartDateTime DATETIME = GETDATE()
DECLARE @CurrentDateTime DATETIME = null
DECLARE @ExecutionStatus INT = 0
DECLARE @MaxTimeExceeded BIT = 0
--Loop through and start every job
DECLARE dbCursor CURSOR FOR SELECT JobName FROM @JobsToRunTable
OPEN dbCursor FETCH NEXT FROM dbCursor INTO @JobNameToRun
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC [msdb].[dbo].sp_start_job @JobNameToRun
FETCH NEXT FROM dbCursor INTO @JobNameToRun
END
CLOSE dbCursor
DEALLOCATE dbCursor
print '*****************************************************************'
print 'Jobs started. ' + CAST(@StartDateTime as varchar)
print '*****************************************************************'
--Debug (if needed)
--SELECT * FROM @JobsToRunTable
WHILE 1=1 AND @AreJobsRunning = 1
BEGIN
--This has to be first with the delay to make sure the jobs
--have time to actually start up and are recognized as 'running'
WAITFOR DELAY @WaitDelay
--Reset for each loop iteration
SET @AreJobsRunning = 0
--Get the currently executing jobs by our user name
INSERT INTO @ExecutionStatusTable
EXECUTE [master].[dbo].xp_sqlagent_enum_jobs 1, @job_owner
--Debug (if needed)
--SELECT 'ExecutionStatusTable', * FROM @ExecutionStatusTable
--select every job to see if it's running
DECLARE dbCursor CURSOR FOR
SELECT x.[Running], x.[JobID], sj.name
FROM @ExecutionStatusTable x
INNER JOIN [msdb].[dbo].sysjobs sj ON sj.job_id = x.JobID
INNER JOIN @JobsToRunTable jtr on sj.name = jtr.JobName
OPEN dbCursor FETCH NEXT FROM dbCursor INTO @IsJobRunning, @JobID, @JobNameToRun
--Debug (if needed)
--SELECT x.[Running], x.[JobID], sj.name
-- FROM @ExecutionStatusTable x
-- INNER JOIN msdb.dbo.sysjobs sj ON sj.job_id = x.JobID
-- INNER JOIN @JobsToRunTable jtr on sj.name = jtr.JobName
WHILE @@FETCH_STATUS = 0
BEGIN
--bitwise operation to see if the loop should continue
SET @AreJobsRunning = @AreJobsRunning | @IsJobRunning
UPDATE @JobsToRunTable
SET Running = @IsJobRunning, JobID = @JobID
WHERE JobName = @JobNameToRun
--Debug (if needed)
--SELECT 'JobsToRun', * FROM @JobsToRunTable
SET @CurrentDateTime=GETDATE()
IF @IsJobRunning = 1
BEGIN -- Job is running or finishing (not idle)
IF DATEDIFF(mi, @StartDateTime, @CurrentDateTime) > @TimeoutMinutes
BEGIN
print '*****************************************************************'
print @JobNameToRun + ' exceeded timeout limit of ' + @TimeoutMinutes + ' minutes. Stopping.'
--Stop the job
EXEC [msdb].[dbo].sp_stop_job @job_name = @JobNameToRun
END
ELSE
BEGIN
print @JobNameToRun + ' running for ' + CONVERT(VARCHAR(25),DATEDIFF(mi, @StartDateTime, @CurrentDateTime)) + ' minute(s).'
END
END
IF @IsJobRunning = 0
BEGIN
--Job isn't running
print '*****************************************************************'
print @JobNameToRun + ' completed or did not run. ' + CAST(@CurrentDateTime as VARCHAR)
END
FETCH NEXT FROM dbCursor INTO @IsJobRunning, @JobID, @JobNameToRun
END -- WHILE @@FETCH_STATUS = 0
CLOSE dbCursor
DEALLOCATE dbCursor
--Clear out the table for the next loop iteration
DELETE FROM @ExecutionStatusTable
print '*****************************************************************'
END -- WHILE 1=1 AND @AreJobsRunning = 1
SET @CurrentDateTime = GETDATE()
print 'Finished at ' + CAST(@CurrentDateTime as varchar)
print CONVERT(VARCHAR(25),DATEDIFF(mi, @StartDateTime, @CurrentDateTime)) + ' minutes total run time.'
delete map[key] in go?
In the old language, to delete the entry with key k
from the map represented by m
, one wrote the statement,
m[k] = value, false
This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.
In Go 1, that syntax has gone; instead there is a new built-in function, delete
. The call
delete(m, k)
will delete the map entry retrieved by the expression m[k]
. There is no return value. Deleting a non-existent entry is a no-op.
Updating: Running go fix
will convert expressions of the form m[k] = value, false
into delete(m, k)
when it is clear that the ignored value can be safely discarded from the program and false
refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.
Adding a dictionary to another
The most obvious way is:
foreach(var kvp in NewAnimals)
Animals.Add(kvp.Key, kvp.Value);
//use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue
Since Dictionary<TKey, TValue>
explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Add
method, you can also do this:
var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;
foreach(var kvp in NewAnimals)
animalsAsCollection.Add(kvp);
It's a pity the class doesn't have anAddRange
method likeList<T>
does.
When to use pthread_exit() and when to use pthread_join() in Linux?
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void *fun_t(void *arg);
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
//pthread_exit("Bye");
while(1);
pthread_exit("Bye");
}
int main()
{
pthread_t pt;
void *res_t;
if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
perror("pthread_create");
if(sem_init(&st,0,0) != 0)
perror("sem_init");
if(sem_wait(&st) != 0)
perror("sem_wait");
printf("Sanoundry\n");
//Try commenting out join here.
if(pthread_join(pt,&res_t) == -1)
perror("pthread_join");
if(sem_destroy(&st) != 0)
perror("sem_destroy");
return 0;
}
Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.
Make sure you understand once you have created a thread, the process run along with main together at the same time.
- Without the join, main thread continue to run and return 0
- With the join, main thread would be stuck in the while loop because it waits for the thread to be done executing.
- With the join and delete the commented out pthread_exit, the thread will terminate before running the while loop and main would continue
- Practical usage of pthread_exit can be used as an if conditions or case statements to ensure 1 version of some code runs before exiting.
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
if(2-1 == 1)
pthread_exit("Bye");
else
{
printf("We have a problem. Computer is bugged");
pthread_exit("Bye"); //This is redundant since the thread will exit at the end
//of scope. But there are instances where you have a bunch
//of else if here.
}
}
I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void* fun_t (void* arg)
{
printf("I'm thread\n");
sem_post(&st);
}
int main()
{
pthread_t pt;
pthread_create(&pt,NULL,fun_t,NULL);
sem_init(&st,0,0);
sem_wait(&st);
printf("before_thread\n");
pthread_join(pt,NULL);
printf("After_thread\n");
}
Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/
Create thumbnail image
This is the code I'm using. Also works for .NET Core
> 2.0 using System.Drawing.Common
NuGet.
https://www.nuget.org/packages/System.Drawing.Common/
using System;
using System.Drawing;
class Program
{
static void Main()
{
const string input = "C:\\background1.png";
const string output = "C:\\thumbnail.png";
// Load image.
Image image = Image.FromFile(input);
// Compute thumbnail size.
Size thumbnailSize = GetThumbnailSize(image);
// Get thumbnail.
Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
thumbnailSize.Height, null, IntPtr.Zero);
// Save thumbnail.
thumbnail.Save(output);
}
static Size GetThumbnailSize(Image original)
{
// Maximum size of any dimension.
const int maxPixels = 40;
// Width and height.
int originalWidth = original.Width;
int originalHeight = original.Height;
// Return original size if image is smaller than maxPixels
if (originalWidth <= maxPixels || originalHeight <= maxPixels)
{
return new Size(originalWidth, originalHeight);
}
// Compute best factor to scale entire image based on larger dimension.
double factor;
if (originalWidth > originalHeight)
{
factor = (double)maxPixels / originalWidth;
}
else
{
factor = (double)maxPixels / originalHeight;
}
// Return thumbnail size.
return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
}
}
Source:
https://www.dotnetperls.com/getthumbnailimage
Oracle listener not running and won't start
In my case, I tried to start the listener via console:
> lsnrctl star
This command printed the following error:
TNS-12560: TNS:protocol adapter error
TNS-00583: Valid node checking: unable to parse configuration parameters
So, I performed the following actions:
- Check if Oracle
listener.ora
or sqlnet.ora
file contains special characters
- Check if Oracle
listener.ora
or sqlnet.ora` file are in wrong format or syntax
- Check if Oracle
listener.ora
or sqlnet.ora
file have some left justified parenthesis which are not accepted by oracle parser.
Have a look at these files and check the proper syntax. If possible remove/rename sqlnet.ora and try to restart the listener. Or remove/rename both listener.ora or sqlnet.ora file and recreate it properly. These will defenitely resolve the issue.
How to print without newline or space?
Or have a function like:
def Print(s):
return sys.stdout.write(str(s))
Then now:
for i in range(10): # or `xrange` for python 2 version
Print(i)
Outputs:
0123456789
How do I unbind "hover" in jQuery?
Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):
$("#myElement").unbind('mouseenter mouseleave');
As of jQuery 1.7, you are also able use $.on()
and $.off()
for event binding, so to unbind the hover event, you would use the simpler and tidier:
$('#myElement').off('hover');
The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off()
now allows you to drop both mouse events using the same shorthand.
Edit 2016:
Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:
$('#myElement').off('mouseenter mouseleave');
Does a TCP socket connection have a "keep alive"?
In JAVA Socket – TCP connections are managed on the OS level, java.net.Socket does not provide any in-built function to set timeouts for keepalive packet on a per-socket level. But we can enable keepalive option for java socket but it takes 2 hours 11 minutes (7200 sec) by default to process after a stale tcp connections. This cause connection will be availabe for very long time before purge. So we found some solution to use Java Native Interface (JNI) that call native code(c++) to configure these options.
****Windows OS****
In windows operating system keepalive_time & keepalive_intvl can be configurable but tcp_keepalive_probes cannot be change.By default, when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval to 1 second. The default system-wide value of the keep-alive timeout is controllable through the KeepAliveTime registry setting which takes a value in milliseconds.
On Windows Vista and later, the number of keep-alive probes (data retransmissions) is set to 10 and cannot be changed.
On Windows Server 2003, Windows XP, and Windows 2000, the default setting for number of keep-alive probes is 5. The number of keep-alive probes is controllable. For windows Winsock IOCTLs library is used to configure the tcp-keepalive parameters.
int WSAIoctl( SocketFD, // descriptor identifying a socket SIO_KEEPALIVE_VALS, // dwIoControlCode (LPVOID) lpvInBuffer, // pointer to tcp_keepalive struct (DWORD) cbInBuffer, // length of input buffer NULL, // output buffer 0, // size of output buffer (LPDWORD) lpcbBytesReturned, // number of bytes returned NULL, // OVERLAPPED structure NULL // completion routine );
Linux OS
Linux has built-in support for keepalive which is need to be enabling TCP/IP networking in order to use it. Programs must request keepalive control for their sockets using the setsockopt interface.
int setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen)
Each client socket will be created using java.net.Socket. File descriptor ID for each socket will retrieve using java reflection.
Maven fails to find local artifact
Catch all. When solutions mentioned here don't work(happend in my case), simply delete all contents from '.m2' folder/directory, and do mvn clean install
.
How to get cookie expiration date / creation date from javascript?
If you are using Chrome you can goto the "Resources" tab and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.
How to read from stdin with fgets()?
Assuming that you only want to read a single line, then use LINE_MAX
, which is defined in <limits.h>
:
#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...
PHP date add 5 year to current date
Modifying dates based on this post
strtotime() is really powerful and allows you to modify/transform dates easily with it’s relative expressions too:
Procedural
$dateString = '2011-05-01 09:22:34';
$t = strtotime($dateString);
$t2 = strtotime('-3 days', $t);
echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
DateTime
$dateString = '2011-05-01 09:22:34';
$dt = new DateTime($dateString);
$dt->modify('-3 days');
echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
The stuff you can throw at strtotime() is quite surprising and very human readable. Have a look at this example looking for Tuesday next week.
Procedural
$t = strtotime("Tuesday next week");
echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
DateTime
$dt = new DateTime("Tuesday next week");
echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
Note that these examples above are being returned relative to the time now.
The full list of time formats that strtotime() and the DateTime constructor takes are listed on the PHP Supported Date and Time Formats page.
Another example, suitable for your case could be: based on this post
<?php
//How to get the day 3 days from now:
$today = date("j");
$thisMonth = date("n");
$thisYear = date("Y");
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear));
//1 week from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));
//4 months from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear));
//3 years, 2 months and 35 days from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
?>
How do you create a daemon in Python?
Note the python-daemon package which solves a lot of problems behind daemons out of the box.
Among other features it enables to (from Debian package description):
- Detach the process into its own process group.
- Set process environment appropriate for running inside a chroot.
- Renounce suid and sgid privileges.
- Close all open file descriptors.
- Change the working directory, uid, gid, and umask.
- Set appropriate signal handlers.
- Open new file descriptors for stdin, stdout, and stderr.
- Manage a specified PID lock file.
- Register cleanup functions for at-exit processing.
Python method for reading keypress?
It's really late now but I made a quick script which works for Windows, Mac and Linux, simply by using each command line:
import os, platform
def close():
if platform.system() == "Windows":
print("Press any key to exit . . .")
os.system("pause>nul")
exit()
elif platform.system() == "Linux":
os.system("read -n1 -r -p \"Press any key to exit . . .\" key")
exit()
elif platform.system() == "Darwin":
print("Press any key to exit . . .")
os.system("read -n 1 -s -p \"\"")
exit()
else:
exit()
It uses only inbuilt functions, and should work for all three (although I've only tested Windows and Linux...).
How to send Request payload to REST API in java?
I tried with a rest client.
Headers :
- POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
- Host: git.eclipse.org
- User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
- Accept: application/json
- Accept-Language: null
- Accept-Encoding: gzip,deflate,sdch
- accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
- Content-Type: application/json; charset=UTF-8
- Content-Length: 73
- Connection: keep-alive
it works fine. I retrieve 200 OK with a good body.
Why do you set a status code in your request?
and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.
Can I create a One-Time-Use Function in a Script or Stored Procedure?
The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:
IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
SELECT Division =
CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND @Numerator != 0 AND @Numerator is NOT NULL THEN
@Numerator / @Denominator
ELSE
0
END
RETURN
END
GO
Exec ##fn_Divide 6,4
This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.
Excel 2013 horizontal secondary axis
You should follow the guidelines on Add a secondary horizontal axis:
Add a secondary horizontal axis
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
![enter image description here](https://i.stack.imgur.com/fysIc.png)
Click Secondary Horizontal Axis, and then click the display option that you want.
![enter image description here](https://i.stack.imgur.com/B8fRh.png)
Add a secondary vertical axis
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
![enter image description here](https://i.stack.imgur.com/t2kZU.png)
On the Format tab, in the Current Selection group, click Format Selection.
The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
How to write a foreach in SQL Server?
You seem to want to use a CURSOR
. Though most of the times it's best to use a set based solution, there are some times where a CURSOR
is the best solution. Without knowing more about your real problem, we can't help you more than that:
DECLARE @PractitionerId int
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT PractitionerId
FROM Practitioner
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
WHILE @@FETCH_STATUS = 0
BEGIN
--Do something with Id here
PRINT @PractitionerId
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
Read/Parse text file line by line in VBA
For completeness; working with the data loaded into memory;
dim hf As integer: hf = freefile
dim lines() as string, i as long
open "c:\bla\bla.bla" for input as #hf
lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf
for i = 0 to ubound(lines)
debug.? "Line"; i; "="; lines(i)
next
Moment.js - two dates difference in number of days
From the moment.js docs: format('E')
stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.
From the moment.js docs again, here is what they suggest:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Here is a JSFiddle for your particular case:
_x000D_
_x000D_
$('#test').click(function() {_x000D_
var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_
JAXB Exception: Class not known to this context
Fixed it by setting the class name to the property "classesToBeBound" of the JAXB marshaller:
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>myclass</value>
</list>
</property>
</bean>
Connect Android Studio with SVN
Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
What is the purpose of Looper and how to use it?
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
![enter image description here](https://i.stack.imgur.com/rYqsP.jpg)
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
Android: Toast in a thread
How to stop a goroutine
I know this answer has already been accepted, but I thought I'd throw my 2cents in. I like to use the tomb package. It's basically a suped up quit channel, but it does nice things like pass back any errors as well. The routine under control still has the responsibility of checking for remote kill signals. Afaik it's not possible to get an "id" of a goroutine and kill it if it's misbehaving (ie: stuck in an infinite loop).
Here's a simple example which I tested:
package main
import (
"launchpad.net/tomb"
"time"
"fmt"
)
type Proc struct {
Tomb tomb.Tomb
}
func (proc *Proc) Exec() {
defer proc.Tomb.Done() // Must call only once
for {
select {
case <-proc.Tomb.Dying():
return
default:
time.Sleep(300 * time.Millisecond)
fmt.Println("Loop the loop")
}
}
}
func main() {
proc := &Proc{}
go proc.Exec()
time.Sleep(1 * time.Second)
proc.Tomb.Kill(fmt.Errorf("Death from above"))
err := proc.Tomb.Wait() // Will return the error that killed the proc
fmt.Println(err)
}
The output should look like:
# Loop the loop
# Loop the loop
# Loop the loop
# Loop the loop
# Death from above
How to export JavaScript array info to csv (on client side)?
I added to Xavier Johns function to also include the field headers if needed, uses jQuery though. The $.each bit will need changing for a native javascript loop
function exportToCsv(filename, rows, headers = false) {
var processRow = function (row) {
row = $.map(row, function(value, index) {
return [value];
});
var finalVal = '';
for (var j = 0; j < row.length; j++) {
if(i == 0 && j == 0 && headers == true){
var ii = 0;
$.each(rows[i], function( index, value ) {
//console.log(index);
var fieldName = index === null ? '' : index.toString();
//console.log(fieldName);
var fieldResult = fieldName.replace(/"/g, '""');
//console.log(fieldResult);
if (fieldResult.search(/("|,|\n)/g) >= 0){
fieldResult = '"' + fieldResult + '"';
}
//console.log(fieldResult);
if (ii > 0){
finalVal += ',';
finalVal += fieldResult;
}else{
finalVal += fieldResult;
}
ii++;
//console.log(finalVal);
});
finalVal += '\n';
//console.log('end: '+finalVal);
}
var innerValue = row[j] === null ? '' : row[j].toString();
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
};
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0){
result = '"' + result + '"';
}
if (j > 0){
finalVal += ',';
finalVal += result;
}else{
finalVal += result;
}
}
return finalVal + '\n';
};
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += processRow(rows[i]);
}
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
}else{
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
How can I convert a Timestamp into either Date or DateTime object?
java.time
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp
class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone
is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime
as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp
without time zone, retrieve a LocalDateTime
instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd
.
I wasn’t sure what you meant by the xx
in HH:MM xx
. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
How to prepare a Unity project for git?
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
- Enable
External
option in Unity ? Preferences ? Packages ? Repository
- Switch to
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
- Switch to
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
- Save scene and project from
File
menu
Note that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
How to remove unused C/C++ symbols with GCC and ld?
For GCC, this is accomplished in two stages:
First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:
-fdata-sections -ffunction-sections
Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):
-Wl,--gc-sections
So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):
gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
(Note that -Os is an additional compiler flag that tells GCC to optimize for size)
How to get ERD diagram for an existing database?
You can generate ER diagram from PgAdmin.
- Open PgAdmin
- Right click on any table and select statement and it will show two window one is query other is graphical window so you can add the table which you want to generate the diagram.
- To save go to save as and select Graphical Query (image)
Connection string using Windows Authentication
For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.
Basically this works:
<connectionStrings>
<add name="MyConnectionString"
connectionString="data source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.
It is also working different according which provider you are using.
Integrated Security=true throws an exception when used with the OleDb provider.
How do I rename a column in a SQLite database table?
While it is true that there is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of commands:
Note: These commands have the potential to corrupt your database, so make sure you have a backup
PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;
You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.
For example:
Y:\> sqlite3 booktest
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT NULL);
sqlite> insert into BOOKS VALUES ("NULLTEST",null);
Error: BOOKS.publication_date may not be NULL
sqlite> PRAGMA writable_schema = 1;
sqlite> UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
sqlite> PRAGMA writable_schema = 0;
sqlite> .q
Y:\> sqlite3 booktest
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> insert into BOOKS VALUES ("NULLTEST",null);
sqlite> .q
REFERENCES FOLLOW:
pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.
alter table
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.
![ALTER TABLE SYNTAX](https://i.stack.imgur.com/y3xIP.png)
Embed website into my site
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
Search of table names
If you want to look in all tables in all Databases server-wide and get output you can make use of the undocumented sp_MSforeachdb procedure:
sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''%Table_Names%'''
Which passwordchar shows a black dot (•) in a winforms textbox?
One more solution to use this Unicode black circle >>
Start >> All Programs >> Accessories >> System Tools >> Character Map
Then select Arial font
and choose the Black circle
copy it and paste it into PasswordChar
property of the textbox.
That's it....
Dealing with HTTP content in HTTPS pages
The accepted answer helped me update this both to PHP as well as CORS, so I thought I would include the solution for others:
pure PHP/HTML:
<?php // (the originating page, where you want to show the image)
// set your image location in whatever manner you need
$imageLocation = "http://example.com/exampleImage.png";
// set the location of your 'imageserve' program
$imageserveLocation = "https://example.com/imageserve.php";
// we'll look at the imageLocation and if it is already https, don't do anything, but if it is http, then run it through imageserve.php
$imageURL = (strstr("https://",$imageLocation)?"": $imageserveLocation . "?image=") . $imageLocation;
?>
<!-- this is the HTML image -->
<img src="<?php echo $imageURL ?>" />
javascript/jQuery:
<img id="theImage" src="" />
<script>
var imageLocation = "http://example.com/exampleImage.png";
var imageserveLocation = "https://example.com/imageserve.php";
var imageURL = ((imageLocation.indexOf("https://") !== -1) ? "" : imageserveLocation + "?image=") + imageLocation;
// I'm using jQuery, but you can use just javascript...
$("#theImage").prop('src',imageURL);
</script>
imageserve.php
see http://stackoverflow.com/questions/8719276/cors-with-php-headers?noredirect=1&lq=1 for more on CORS
<?php
// set your secure site URL here (where you are showing the images)
$mySecureSite = "https://example.com";
// here, you can set what kinds of images you will accept
$supported_images = array('png','jpeg','jpg','gif','ico');
// this is an ultra-minimal CORS - sending trusted data to yourself
header("Access-Control-Allow-Origin: $mySecureSite");
$parts = pathinfo($_GET['image']);
$extension = $parts['extension'];
if(in_array($extension,$supported_images)) {
header("Content-Type: image/$extension");
$image = file_get_contents($_GET['image']);
echo $image;
}
Java, How to add values to Array List used as value in HashMap
String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");
Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);
Hope this helps!
what innerHTML is doing in javascript?
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
Is iterating ConcurrentHashMap values thread safe?
What does it mean?
That means that each iterator you obtain from a ConcurrentHashMap
is designed to be used by a single thread and should not be passed around. This includes the syntactic sugar that the for-each loop provides.
What happens if I try to iterate the map with two threads at the same time?
It will work as expected if each of the threads uses it's own iterator.
What happens if I put or remove a value from the map while iterating it?
It is guaranteed that things will not break if you do this (that's part of what the "concurrent" in ConcurrentHashMap
means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of it's creation. Futher changes may be reflected in the iterator, but they do not have to be.
In conclusion, a statement like
for (Object o : someConcurrentHashMap.entrySet()) {
// ...
}
will be fine (or at least safe) almost every time you see it.
Copy array items into another array
Use the concat function, like so:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
The value of newArray
will be [1, 2, 3, 4]
(arrayA
and arrayB
remain unchanged; concat
creates and returns a new array for the result).
How to remove all whitespace from a string?
From stringr library you could try this:
- Remove consecutive fill blanks
Remove fill blank
library(stringr)
2. 1.
| |
V V
str_replace_all(str_trim(" xx yy 11 22 33 "), " ", "")
How do I check that a Java String is not all whitespaces?
If you are only checking for whitespace and don't care about null then you can use org.apache.commons.lang.StringUtils.isWhitespace(String str),
StringUtils.isWhitespace(String str);
(Checks if the String contains only whitespace.)
If you also want to check for null(including whitespace) then
StringUtils.isBlank(String str);
Pythonic way to print list items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
How to save a Seaborn plot into a file
Its also possible to just create a matplotlib figure
object and then use plt.savefig(...)
:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure
Find out who is locking a file on a network share
Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.
Use the Menu "Find Handle" and then you can type a path like this
\Device\LanmanRedirector\server\share\
Test if number is odd or even
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
python request with authentication (access_token)
>>> import requests
>>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})
If the above doesnt work , try this:
>>> import requests
>>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
>>> print response.json()
how to zip a folder itself using java
Using zip4j you can simply do this
ZipFile zipfile = new ZipFile(new File("D:\\reports\\january\\filename.zip"));
zipfile.addFolder(new File("D:\\reports\\january\\"));
It will archive your folder and everything in it.
Use the .extractAll
method to get it all out:
zipfile.extractAll("D:\\destination_directory");
Find child element in AngularJS directive
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
Convert a python dict to a string and back
Convert dictionary into JSON (string)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
will get you:
{"name": "Don", "sur
Convert string into dictionary
back_to_mydict = json.loads(result)
how to set JAVA_OPTS for Tomcat in Windows?
For Windows, in case the variable value has space(" ") in it, the correct way is actually to place quotes(") before the variable name like:
set "JAVA_OPTS=-Xms512M -Xmx1024M"
What is NODE_ENV and how to use it in Express?
Typically, you'd use the NODE_ENV
variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV
is set to production
or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error
:
app.get('/error', function(req, res) {
if ('production' !== app.get('env')) {
console.log("Forcing an error!");
}
throw new Error('TestError');
});
app.use(function (req, res, next) {
res.status(501).send("Error!")
})
Note that the latter app.use()
must be last, after all other method handlers!
If you set NODE_ENV
to production
before you start your server, and then send a GET /error
request to it, you should not see the text Forcing an error!
in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).
If, instead, you set NODE_ENV
to something else before starting your server, the opposite should happen.
In Linux, set the environment variable NODE_ENV like this:
export NODE_ENV='value'
Call static methods from regular ES6 class methods
If you are planning on doing any kind of inheritance, then I would recommend this.constructor
. This simple example should illustrate why:
class ConstructorSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(this.name, n);
}
callPrint(){
this.constructor.print(this.n);
}
}
class ConstructorSub extends ConstructorSuper {
constructor(n){
this.n = n;
}
}
let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());
let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
test1.callPrint()
will log ConstructorSuper Hello ConstructorSuper!
to the
console
test2.callPrint()
will log ConstructorSub Hello ConstructorSub!
to the console
The named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:
class NamedSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(NamedSuper.name, n);
}
callPrint(){
NamedSuper.print(this.n);
}
}
class NamedSub extends NamedSuper {
constructor(n){
this.n = n;
}
}
let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());
let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
test3.callPrint()
will log NamedSuper Hello NamedSuper!
to the
console
test4.callPrint()
will log NamedSuper Hello NamedSub!
to the console
See all the above running in Babel REPL.
You can see from this that test4
still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.
Deploying just HTML, CSS webpage to Tomcat
Here's my setup: I am on Ubuntu 9.10.
Now, Here's what I did.
- Create a folder named "tomcat6-myapp" in /usr/share.
- Create a folder "myapp" under /usr/share/tomcat6-myapp.
- Copy the HTML file (that I need to deploy) to /usr/share/tomcat6-myapp/myapp. It must be named index.html.
- Go to /etc/tomcat6/Catalina/localhost.
Create an xml file "myapp.xml" (i guess it must have the same name as the name of the folder in step 2) inside /etc/tomcat6/Catalina/localhost with the following contents.
< Context path="/myapp" docBase="/usr/share/tomcat6-myapp/myapp" />
This xml is called the 'Deployment Descriptor' which Tomcat reads and automatically deploys your app named "myapp".
Now go to http://localhost:8080/myapp in your browser - the index.html gets picked up by tomcat and is shown.
I hope this helps!
Colspan all columns
According to the specification colspan="0"
should result in a table width td.
However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...
http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan
I cannot test it on older browsers, but this is part of specification since 4.0...
Sort objects in ArrayList by date?
All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.
Collections.sort(dataVector, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return ((Date)o1[0]).compareTo(((Date)o2[0]));
}
});
The pipe ' ' could not be found angular2 custom pipe
Suggesting an alternative answer here:
Making a separate module for the Pipe is not required, but is definitely an alternative. Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes
You use your custom pipe the same way you use built-in pipes.
You must include your pipe in the declarations array of the AppModule .
If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.
All you have to do is add your pipe to the declarations array, and the providers array in the module
where you want to use the Pipe.
declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]
Datagrid binding in WPF
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
What is SaaS, PaaS and IaaS? With examples
Meaning For dummies:
IAAS (Infrastructure As A Service) :
The base layer
Deals with Virtual Machines, Storage (Hard Disks), Servers, Network, Load Balancers etc
PAAS (Platform As A Service) :
SAAS (Software As A Service) :
To quickly relate consider the below Google's offerings:
IAAS :
Google Compute Engine (One can develop programs to be run on high performing google's computing infrastructure)
PAAS :
Google App Engine (One can develop applications and let them execute on top of Google app engine which take care of the execution)
SAAS :
Gmail, Google+ etc (One can use email services and extend email/google+ based applications to form newer applications)
Popularity
Company Wise Popularity
Cloud computing is dominated by
- Amazon Web Services (AWS),
- Google Compute Engine, Google App Engine
- Microsoft Azure
- There are many small and medium scale cloud operators that include IBM, Oracle etc.
Most of the popularity around these services owe to the reputation of the company and the amount of investments being made by these companies around the cloud space.
Type of Service Wise Popularity
- PAAS (Platform as a Service) is more popular among developers as they can put all their concentration on developing their apps and leave the rest of management and execution to the service provider. Many service providers also offer the flexibility to increase/decrease the CPU power depending upon the traffic loads giving developers cost effective and easy & effortless management.
- SAAS (Software as a service) is more popular among with consumers, who bother about using the application such as email, social networking etc
- IAAS (Infrastructure as a service) is more popular among users into research and high computing areas.
Failed to connect to camera service
I came up with the same problem and I'm sharing how I fixed it. It may help some people.
First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :
- Declare a permission in the app manifest. Make sure to insert the permission above the application tag.
**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**
<application ...>
...
</application>
Then, request that the user approve each permission at runtime
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// here, Permission is not granted
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
}
For more information, have a look at the API documentation here
The controller for path was not found or does not implement IController
In my case in global.asax/application_start method,
I was registering web api routes AFTER mvc routes like so:
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
Reverting the order fixed the issue
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Multidimensional Array [][] vs [,]
One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.
That is, a double[][]
can validly be:
double[][] x = new double[5][];
x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];
Because each entry in the array is a reference to an array of double
. With a jagged array, you can do an assignment to an array like you want in your second example:
x[0] = new double[13];
On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double
:
double[,] ServicePoint = new double[10,9];
ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.
UPDATE:
To clarify based on your question, the reason your #1 had a syntax error is because you had this:
double[][] ServicePoint = new double[10][9];
And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:
double[][] ServicePoint = new double[10][];
Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):
ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];
Hope that helps!
Writing an Excel file in EPPlus
If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection
.
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
package.Save();
}
Remove an entire column from a data.frame in R
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively.
For programming it is better to use the standard subsetting
functions like '[', and in particular the non-standard evaluation
of argument 'subset' can have unanticipated consequences.
How to drop a PostgreSQL database if there are active connections to it?
Here's my hack... =D
# Make sure no one can connect to this database except you!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "UPDATE pg_database SET datallowconn=false WHERE datname='<DATABASE_NAME>';"
# Drop all existing connections except for yours!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '<DATABASE_NAME>' AND pid <> pg_backend_pid();"
# Drop database! =D
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "DROP DATABASE <DATABASE_NAME>;"
I put this answer because include a command (above) to block new connections and because any attempt with the command...
REVOKE CONNECT ON DATABASE <DATABASE_NAME> FROM PUBLIC, <USERS_ETC>;
... do not works to block new connections!
Thanks to @araqnid @GoatWalker ! =D
https://stackoverflow.com/a/3185413/3223785
Trying to retrieve first 5 characters from string in bash error?
The original syntax will work with BASH but not with DASH. On debian systems you
might think you are using bash, but maybe dash instead. If /bin/dash/exist then
try temporarily renaming dash to something like no.dash, and then create soft a
link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.
Get type name without full namespace
After the C# 6.0 (including) you can use nameof expression:
using Stuff = Some.Cool.Functionality
class C {
static int Method1 (string x, int y) {}
static int Method1 (string x, string y) {}
int Method2 (int z) {}
string f<T>() => nameof(T);
}
var c = new C()
nameof(C) -> "C"
nameof(C.Method1) -> "Method1"
nameof(C.Method2) -> "Method2"
nameof(c.Method1) -> "Method1"
nameof(c.Method2) -> "Method2"
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error
nameof(Stuff) = "Stuff"
nameof(T) -> "T" // works inside of method but not in attributes on the method
nameof(f) -> “f”
nameof(f<T>) -> syntax error
nameof(f<>) -> syntax error
nameof(Method2()) -> error “This expression does not have a name”
Note! nameof
not get the underlying object's runtime Type, it is just the compile-time argument. If a method accepts an IEnumerable then nameof simply returns "IEnumerable", whereas the actual object could be "List".
How to check for an empty struct?
Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:
session := &Session{}
if (Session{}) == *session {
fmt.Println("session is empty")
}
Check this playground.
Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...
Why is using onClick() in HTML a bad practice?
You're probably talking about unobtrusive Javascript, which would look like this:
<a href="#" id="someLink">link</a>
with the logic in a central javascript file looking something like this:
$('#someLink').click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
The advantages are
- behaviour (Javascript) is separated from presentation (HTML)
- no mixing of languages
- you're using a javascript framework like jQuery that can handle most cross-browser issues for you
- You can add behaviour to a lot of HTML elements at once without code duplication
Get key and value of object in JavaScript?
If this is all the object is going to store, then best literal would be
var top_brands = {
'Adidas' : 100,
'Nike' : 50
};
Then all you need is a for...in
loop.
for (var key in top_brands){
console.log(key, top_brands[key]);
}
jquery draggable: how to limit the draggable area?
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
How to detect when WIFI Connection has been established in Android?
This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast
, NETWORK_STATE_CHANGED_ACTION
, at every network connectivity state change.
AndroidManifest:
<receiver
android:name=".WifiReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<!--protected-broadcast: Special broadcast that only the system can send-->
<!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
BroadcastReceiver class:
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
or CONNECTED
(Those states can be obtained as NetworkInfo.DetailedState objects by calling
the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
/*
* NetworkInfo object associated with the Wi-Fi network.
* It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
*/
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.isConnected()) {
// TODO: Place the work here, like retrieving the access point's SSID
/*
* WifiInfo object giving information about the access point we are connected to.
* It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
* null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
*/
WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
String ssid = wifiInfo.getSSID();
}
}
}
Permissions:
None
While, Do While, For loops in Assembly Language (emu8086)
For-loops:
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loops
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loops
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
How to get changes from another branch
go to the master branch our-team
pull all the new changes from our-team
branch
go to your branch featurex
merge the changes of our-team
branch into featurex
branch
- git merge
our-team
- or git cherry-pick
{commit-hash}
if you want to merge specific commits
push your changes with the changes of our-team
branch
Note: probably you will have to fix conflicts after merging our-team
branch into featurex
branch before pushing
how to generate web service out of wsdl
This may be very late in answering. But might be helpful to needy:
How to convert WSDL to SVC :
- Assuming you are having .wsdl file at location "E:\" for ease in access further.
- Prepare the command for each .wsdl file as: E:\YourServiceFileName.wsdl
- Permissions: Assuming you are having the Administrative rights to perform permissions. Open directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
- Right click to amd64 => Security => Edit => Add User => Everyone Or Current User => Allow all permissions => OK.
- Prepare the Commands for each file in text editor as: wsdl.exe E:\YourServiceFileName.wsdl /l:CS /server.
- Now open Visual studio command prompt from : C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x64 Native Tools Command Prompt.
- Execute above command.
Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated.
9.Move generated CS file to appropriate location.
Visual Studio Code pylint: Unable to import 'protorpc'
The visual studio default setting should be the same as the interpreter path.
Change VS code default setting: windows: File > Preferences > Settings
{
"python.pythonPath": "C:\\Users\\Anaconda3\\pythonw.exe",
"workbench.startupEditor": "newUntitledFile"
}
Find the right interpreter:
windows: Ctrl+Shift+P->select interpreter:
the path of that interpreter should be same as the version you are working on.
How to export iTerm2 Profiles
There is another way to do this.
From iTerm2 2.9.20140923 you can use Dynamic Profiles as stated in the documentation page:
Dynamic Profiles is a feature that allows you to store your profiles in a file outside the usual macOS preferences database. Profiles may be changed at runtime by editing one or more plist files (formatted as JSON, XML, or in binary). Changes are picked up immediately.
So it is possible to create a file like this one:
{
"Profiles": [{
"Name": "MYSERVER1",
"Guid": "MYSERVER1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "M",
"Tags": [
"LOCAL", "THATCOMPANY", "WORK", "NOCLOUD"
],
"Badge Text": "SRV1",
},
{
"Name": "MYOCEANSERVER1",
"Guid": "MYOCEANSERVER1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "O",
"Tags": [
"THATCOMPANY", "WORK", "DIGITALOCEAN"
],
"Badge Text": "PPOCEAN1",
},
{
"Name": "PI1",
"Guid": "PI1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "1",
"Tags": [
"LOCAL", "PERSONAL", "RASPBERRY", "SMALL"
],
"Badge Text": "LocalServer",
},
{
"Name": "VUZERO",
"Guid": "VUZERO",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "0",
"Tags": [
"LOCAL", "PERSONAL", "SMALL"
],
"Badge Text": "TeleVision",
}
]
}
in the folder ~/Library/Application\ Support/iTerm2/DynamicProfiles/
and share it across different machines.
This enables you to retain some visual differences among iterm2 installations such as font type or dimension, while synchronising remote hosts, shortcuts, commands, and even a small badge to quickly identify a session
![badge](https://i.stack.imgur.com/cKguz.png)
How do I pass multiple parameters in Objective-C?
Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray
at a certain index, you would do it using the method:
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
This method is called insertObject:atIndex:
and it is clear that an object is being inserted at a specified index.
In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray
called array
would be called as follows:
NSString *obj = @"Hello, World!";
int index = 5;
[array insertObject:obj atIndex:index];
This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.
Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber
class; this has several object creation methods, including:
+ (id)numberWithBool:(BOOL)value;
+ (id)numberWithFloat:(float)value;
+ (id)numberWithDouble:(double)value;
In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.
SSL Proxy/Charles and Android trouble
I figured the issue. Its because Charles 3.7 has some bugs for Android devices. I updated to Charles 3.8 Beta version and seems to working fine for me.
CSS to stop text wrapping under image
Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:
This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.
The span
element is an inline element, you can't change its width in CSS.
You can add the following CSS to your span so you will be able to change its width.
display: block;
Another way, which usually makes more sense, is to use a <p>
element as a parent for your <span>
.
<li id="CN2787">
<img class="fav_star" src="images/fav.png">
<p>
<span>Text, text and more text</span>
</p>
</li>
Since <p>
is a block
element, you can set its width using CSS, without having to change anything.
But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.
li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}
P.S. Instead of float:left
on the image, you can also put float:right
on li p
but in that case, you will also need text-align:left
to realign the text correctly.
P.S.S. If you went ahead with the first solution of not adding a <p>
element, your CSS should look like so:
li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}
How to call Stored Procedure in Entity Framework 6 (Code-First)?
I solved it with ExecuteSqlCommand
Put your own method like mine in DbContext as your own instances:
public void addmessage(<yourEntity> _msg)
{
var date = new SqlParameter("@date", _msg.MDate);
var subject = new SqlParameter("@subject", _msg.MSubject);
var body = new SqlParameter("@body", _msg.MBody);
var fid = new SqlParameter("@fid", _msg.FID);
this.Database.ExecuteSqlCommand("exec messageinsert @Date , @Subject , @Body , @Fid", date,subject,body,fid);
}
so you can have a method in your code-behind like this :
[WebMethod] //this method is static and i use web method because i call this method from client side
public static void AddMessage(string Date, string Subject, string Body, string Follower, string Department)
{
try
{
using (DBContext reposit = new DBContext())
{
msge <yourEntity> Newmsg = new msge();
Newmsg.MDate = Date;
Newmsg.MSubject = Subject.Trim();
Newmsg.MBody = Body.Trim();
Newmsg.FID= 5;
reposit.addmessage(Newmsg);
}
}
catch (Exception)
{
throw;
}
}
this is my SP :
Create PROCEDURE dbo.MessageInsert
@Date nchar["size"],
@Subject nchar["size"],
@Body nchar["size"],
@Fid int
AS
insert into Msg (MDate,MSubject,MBody,FID) values (@Date,@Subject,@Body,@Fid)
RETURN
hope helped you
SVN remains in conflict?
I guess the proper solution is:
(1) backup your-file/your-directory
(2) svn revert your-file/your-directory
(3) svn update your-file/your-directory
(4) Merge the backup your-file/your-directory to the updated one.
(5) svn ci -m "My work here is done"