source
sequence
text
stringlengths
99
98.5k
[ "ru.stackoverflow", "0000503243.txt" ]
Q: Yii2, не работает связь hasOne Есть проект на Yii2, веб-сервер настроен правильно (другие проекты аналогичные работают без проблем) Есть две модели Stud и Klass В первой модели делаю связь public function getKlas() { return $this->hasOne(Klass::className(), ['id' => 'klass']); } public function getKlass1() { return $this->klas->klass2; } соответственно есть id у модели Klass и поле klass в модели Stud, но получаю: PHP Notice – yii\base\ErrorException Trying to get property of non-object В чём может быть проблема? Заранее большое спасибо! A: А вы посмотрели что в $this->klas. Знания о реализованнии связей беру из Laravel, но все же. Мне кажется в $this->klas null - от сюда и ошибка.
[ "tex.stackexchange", "0000351311.txt" ]
Q: How to insert a horizontal line in align env with some text at the end of the line I'd like to have some math induction showing as below.(In an align environment \begin{align*}...\end{align*}) How can I have the "by addition" text at the end of the line? I tried with \cline but failed to do that. x = 1 y = 2 -------------- by addtion x + y = 3 z = 3 --------------------------------- by addition x + y + z = 6 Here is what I've got so far. I also wanted the equations to be centered but I found it was hard to do. \begin{align*} x = 1 & y = 2 \\ \cline{1-2} x + y = 3 & & z = 3 \\ \cline{1-3} &x + y + z = 6& \\ \end{align*} A: I created \byx{<eq1>}{<eq2>}{<via>}{<eq-sum>}, which can be nested. \documentclass[11pt]{report} \usepackage{amsmath,stackengine} \newcommand\byx[4]{% \setbox0=\hbox{$~#1\qquad#2~$}% \setbox2=\hbox{~by #3}% \Shortstack[c]{\copy0 \rule[2.3pt]{\wd0}{.5pt}\rlap{\copy2} $#4$}% \hspace{\wd2}% } \begin{document} \[ \byx{% \byx{x=1}{y=2}{addition}{x+y=3} }{z=3}{addition}{x+y+z=6} \] \end{document} Note: You can add \setstackgap{S}{<gap>} to set the vertical gap of the stack. Default gap for \Shortstack is 3pt. The value can span the positive/negative range.
[ "stackoverflow", "0063725185.txt" ]
Q: How to design a Ruler in qml I want to design a ruler as shown in the image below: Which approach is the best possible way to design a ruler with these small and big lines(scale divisions) as shown in the image. Also text and numbers will be added with the scale divisions. There is one knob which i can slide from left to right and vice versa. Can this be achieved using Slider component? A: Try using the QtQuick.Extras module it has a Gauge QML Type. For tick marks use the tickmark and minorTickmark properties from the GaugeStyle QML Type. Then add to this what you want. import QtQuick 2.15 import QtQuick.Window 2.12 import QtQuick.Extras 1.4 Window { visible: true width: 640 height: 480 color: "gray" x: (Screen.width - width) / 2 y: (Screen.height - height) / 2 Gauge { minimumValue: 0 value: 50 maximumValue: 100 anchors.centerIn: parent orientation: Qt.Horizontal } }
[ "stackoverflow", "0047032439.txt" ]
Q: Put all occurences in the String in quotes using regex in python I hava a long string were I can find something like this data() { <some data which is always different here> } I want to put all occurences in quotes. This is what I'm doing but it has no effect: string = re.sub(r'data \(\) {(.*)}', r'"/1"', string) I suppose there should be something different between curly brackets but I have no idea what... @EDIT I realized my String look like this: data() { <some white spaces> here is text <some white spaces> } A: Whitespace matters, the direction of slashes matters (thanks Wiktor, I overlooked that before) and that quantifier should probably be lazy. Also, if there are newlines within your text, you need to allow for that string = re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string) Testing it on your sample text: In [4]: string = """data() { ...: <some white spaces> here is text ...: <some white spaces> }""" In [5]: print(re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string)) " <some white spaces> here is text <some white spaces> "
[ "stackoverflow", "0036356500.txt" ]
Q: MySQl - SQL - Top 5 records per day With respect to the data set below, I'm trying to get the top 5 records per day on a MySQL database. It's a table of web page visits & my aim is to find out the 5 most visited pages. I'm comfortable getting just the top 10 in a given date range, but, have not been able to manage to get a query going for the topic in question. I did try the below select VISIT_DATE, group_concat(PAGE_ID order by NUM_VISITS desc separator ',') as pagehits from PAGEVISITS where VISIT_DATE >= '2015-07-01' and VISIT_DATE <= '2015-07-15' group by VISIT_DATE but I can't get SUM(NUM_VISITS) int here & I couldn't get group byVISIT_DATE` which makes it pretty useless. This apart, this is how far I've got select VISIT_DATE, PAGE_ID, SUM(NUM_VISITS) as pagehits from PAGEVISITS where VISIT_DATE >= '2015-01-01' and VISIT_DATE <= '2015-03-15' group by VISIT_DATE, PAGE_ID order by pagehits desc limit 5; which obviously is not top 5 per day. Also, there could be more than one page that can end up having the same number of page hits obviously & may also end up appearing as one of the top 5 which is why I tried using group concat to display all those PAGE IDs whose number of page hits is in the top 5 page hit count for that day. I'm not a seasoned SQL coder. Could I please request assistance to get this working. If I've not sounded clear anywhere, please do let me know. CREATE TABLE PAGEVISITS (`VISIT_DATE` date, `PAGE_ID` varchar(20), `SERVER_NAME` varchar(50), `NUM_VISITS` int) ; INSERT INTO PAGEVISITS (`VISIT_DATE`, `PAGE_ID`, `SERVER_NAME`, `NUM_VISITS`) VALUES ('2015-01-01','2015A12123','A',10), ('2015-01-01','2015A12123','B',10), ('2015-01-01','2015A12124','A',30), ('2015-01-01','2015A12124','B',30), ('2015-01-01','2015A12125','A',40), ('2015-01-01','2015A12125','B',40), ('2015-01-01','2015A12126','A',1), ('2015-01-01','2015A12126','B',1), ('2015-01-01','2015A12127','A',0), ('2015-01-01','2015A12127','B',1), ('2015-01-01','2015A12128','A',40), ('2015-01-01','2015A12129','A',30), ('2015-01-01','2015A12134','A',45), ('2015-01-01','2015A12126','A',56), ('2015-01-01','2015A12167','A',23), ('2015-01-01','2015A12145','A',17), ('2015-01-01','2015A121289','A',12), ('2015-01-01','2015A121289','B',5), ('2015-01-02','2015A12123','A',3), ('2015-01-02','2015A12124','A',10), ('2015-01-02','2015A12125','A',70), ('2015-01-02','2015A12126','A',10), ('2015-01-02','2015A12127','A',100), ('2015-01-02','2015A12128','A',3), ('2015-01-02','2015A12128','B',2), ('2015-01-02','2015A12129','A',10), ('2015-01-02','2015A12134','A',5), ('2015-01-02','2015A12126','A',6), ('2015-01-02','2015A12167','A',3), ('2015-01-02','2015A12145','A',170), ('2015-01-02','2015A121289','A',34), ('2015-01-03','2015A12123','A',34), ('2015-01-03','2015A12124','A',14), ('2015-01-03','2015A12125','A',37), ('2015-01-03','2015A12126','A',23), ('2015-01-03','2015A12127','A',234), ('2015-01-03','2015A12128','A',47), ('2015-01-03','2015A12129','A',67), ('2015-01-03','2015A12134','A',89), ('2015-01-03','2015A12134','B',1), ('2015-01-03','2015A12126','A',97), ('2015-01-03','2015A12167','A',35), ('2015-01-03','2015A12145','A',0), ('2015-01-03','2015A121289','A',19), ('2015-01-04','2015A12123','A',115), ('2015-01-04','2015A12124','A',149), ('2015-01-04','2015A12125','A',370), ('2015-01-04','2015A12126','A',34), ('2015-01-04','2015A12127','A',4), ('2015-01-04','2015A12128','A',70), ('2015-01-04','2015A12129','B',70), ('2015-01-04','2015A12134','A',70), ('2015-01-04','2015A12126','B',64), ('2015-01-04','2015A12167','A',33), ('2015-01-04','2015A12145','A',10); ANTICIPATED OUTPUT Fiddle here A: If this is going to be used daily, then you should consider to create a separate table and fill the data in it using procedure. There is still better way to do this(using merge). This is just for your reference. create table daily_results (`VISIT_DATE` date, `PAGE_ID` varchar(20), `SERVER_NAME` varchar(50), `NUM_VISITS` int); CREATE PROCEDURE proc_loop_test( IN startdate date, in enddate date) BEGIN WHILE(startdate < enddate) DO insert into daily_results (select * from PAGEVISITS where VISIT_DATE=startdate order by NUM_VISITS desc limit 5); SET startdate = date_add(startdate, INTERVAL 1 DAY); end WHILE; END; call it using call proc_loop_test(`2015-01-01`,`2015-03-15`); select * from daily_results;
[ "stackoverflow", "0038076276.txt" ]
Q: How to render Pretty json data inside text area React js? I am new to react js.I have a problem in rendering the pretty json data inside textarea.I don't know Which part is wrong I want my prettyjson to render inside textarea Like this "email":"[email protected]", "email":"[email protected]", ..... This is my code But I am getting Nothing inside my textarea /** * Created by arfo on 6/26/2016. */ var React =require('react'); var api = require('../utils'); var Bulkmail = React.createClass({ getInitialState:function () { return{ default:10, data:[], color:'#58FA58' } }, componentDidMount:function () { api.getemail(this.state.default).then(function (response) { this.setState({ data:response }) }.bind(this)) }, onSubmit:function (e) { e.preventDefault(); console.log(this.refs.text.value.trim()); }, onChange:function (e) { e.preventDefault(); //console.log(this.refs.text.value.trim()) var data = this.refs.text.value.trim(); if(isNaN(data)){ this.setState({ color:'#FE2E2E' }) }else{ this.setState({ color:'#58FA58' }) } }, render:function () { console.log(this.state.data); var results = this.state.data; return( <div className="bodybox"> <div className="box"> <div className="upc"> <p>Generate Bulk Email</p> <form onSubmit={this.onSubmit}> <input onChange={this.onChange} type="text" style={{border:'1px solid '+this.state.color}} ref="text" defaultValue={this.state.default} placeholder="Enter Number"/> <button>Get Data</button> </form> <div className="result"> <ul> {this.state.data.map(function (data) { return <li key={data.id}>{data.email}</li> })} </ul> </div> </div> <div className="tdown"> <p>Json Format</p> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <textarea defaultValue={this.state.data.map(function(data) { return JSON.stringify(data.email) })} > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ </textarea> </div> </div> </div> ) } }); module.exports = Bulkmail ; A: <textarea value={this.state.data.map(e=>JSON.stringify(e))} defaultValue="val" /> result {"email":"some@mail"},{"email":"some@mail"},{"email":"some@mail"} let value = this.state.data.map(e=>JSON.stringify(e).replace(/{|}/g,'')); <textarea value={value} defaultValue="val" /> result "email" : "[email protected]", "email" : "some@mail", "email" : "some@mail" let value = this.state.data.map(e=>JSON.stringify(e).replace(/{|}/g,'')).join(',\n'); <textarea value={value} defaultValue="val" /> result "email" : "[email protected]", "email" : "some@mail", "email" : "some@mail" In HTML, the value of is set via children. In React, you should use value instead.
[ "law.stackexchange", "0000023089.txt" ]
Q: Can President Trump shoot off the nukes whenever he wants to, even for no reason? According to a recent editorial in Scientific American(March 1,2017 "Take the Nukes off a Short Fuse"), the president of the United States can order missiles to be shot off without anyone else concurring. Also, are military personnel legally bound to obey this? Maybe a soldier could legally disobey such an order on the grounds that it was an illegal order or that it "shocked the conscience?" A: The Commander-in-chief powers are quite broad. The War Powers Resolution limits his ability to engage unilaterally in military action, by requiring him to report to Congress within 48 hours, and if Congress disapproves, troops must be removed after 60 days. However, this law pertains to armed forces, and would not apply to remotely-launched missiles. Additionally, it is unknown if the resolution is unconstitutional (presidents say it is). No law at all requires POTUS to obtain permission from someone else, in order to engage in a military action. Article 90 of the UCMJ states that it is a punishable offense to "willfully disobeys a lawful command of his superior commissioned officer". The manual also states that An order requir­ing the performance of a military duty or act may be inferred to be lawful and it is disobeyed at the peril of the subordinate. This inference does not apply to a patently illegal order, such as one that directs the commission of a crime. Murder of a civilian is an example. It also says The lawful­ness of an order is a question of law to be deter­mined by the military judge. "Shocking the conscience" is not a grounds allowing disobedience. One can only conjecture how a military judge would evaluate the lawfulness of a presidential order, when there is not a shred of legal evidence that such an order is in fact illegal: I conjecture that the order would be found to be lawful.
[ "stackoverflow", "0010076525.txt" ]
Q: regular expression search - find original class/struct name of a typedef'd value I'm created an hpp file and I need to forward declare classes as I cannot assume they are included at the time. I have a typedef'd class, and I want to do a find in files to find the line where this is typedef'd so I can get the original class or struct name. How can I do this? I want to search for: typedef "AnythingInBetween" name A: Try the following. ^\s*typedef\s+[a-z:<>.]+\s+thename This will work for cases where it's a typedef to a single name which matches 'thename' and everything occurs on a single line. This isn't fully respective of the C++ grammar for typedefs (a regex simply can't be) but will catch the 90% case
[ "stackoverflow", "0004244466.txt" ]
Q: How to get the next 20 items in RSS feed? I have created an RSS parser using NSXMLParser class. The feed has an item count of 20. I would like to know how to fetch the next 20 items from the feed? If I add the same url to google reader it fetches lot of items and keeps continuing as I scroll down. is there any particular way to fetch next 20 items from the RSS? consider this feed of dilbert blog for example. feed://feeds.feedburner.com/typepad/ihdT?format=xml A: It's probably worth mentioning that wordpress' built in feed generator includes a pagination feature. You can use the 'paged' argument. For example: # Most recent posts: "http://example.com/feed/atom/" # Next most recent posts: "http://example.com/feed/atom/?paged=2" I had trouble finding any wordpress documentation on this. Naturally, this is only helpful information when you're pulling from a wordpress-powered site. A: This is out of scope for the RSS standard. Some smaller sites that generate their feeds on demand might let you parameterize the number of items by appending ?maxitems=50, and maybe even let you specify the starting position. Most of the world however rely on static feeds that can be cached and propagated and will likely never provide what you want. Google Reader maintains their own database of items, from the first time someone subscribed to the given feed through them. They could conceivably make this available programmatically, but for now it's closed.
[ "stackoverflow", "0002573997.txt" ]
Q: Reduce number of points in line I'm searching for algorithms to reduce the LOD of polylines, lines (looped or not) of nodes. In simple words, I want to take hi-resolution coastline data and be able to reduce its LOD hundred- or thousandfold to render it in small-scale. I found polygon reduction algorithms (but they require triangles) and Laplacian smoothing, but that doesn't seem exactly what I need. A: I've modified the code in culebrón's answer, removing the need for the Vec2D/Line classes, instead handling the points as a list of tuples. The code is slightly less tidy, but shorter, and a bit quicker (for 900 points, the original code took 2966ms, and this version takes 500ms - still a bit slower than I'd like, but an improvement) def _vec2d_dist(p1, p2): return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 def _vec2d_sub(p1, p2): return (p1[0]-p2[0], p1[1]-p2[1]) def _vec2d_mult(p1, p2): return p1[0]*p2[0] + p1[1]*p2[1] def ramerdouglas(line, dist): """Does Ramer-Douglas-Peucker simplification of a curve with `dist` threshold. `line` is a list-of-tuples, where each tuple is a 2D coordinate Usage is like so: >>> myline = [(0.0, 0.0), (1.0, 2.0), (2.0, 1.0)] >>> simplified = ramerdouglas(myline, dist = 1.0) """ if len(line) < 3: return line (begin, end) = (line[0], line[-1]) if line[0] != line[-1] else (line[0], line[-2]) distSq = [] for curr in line[1:-1]: tmp = ( _vec2d_dist(begin, curr) - _vec2d_mult(_vec2d_sub(end, begin), _vec2d_sub(curr, begin)) ** 2 / _vec2d_dist(begin, end)) distSq.append(tmp) maxdist = max(distSq) if maxdist < dist ** 2: return [begin, end] pos = distSq.index(maxdist) return (ramerdouglas(line[:pos + 2], dist) + ramerdouglas(line[pos + 1:], dist)[1:]) A: The solution that I've found and quite probably will use, is Ramer-Douglas-Peucker algorithm. It's used in PostGIS I've published my own implementation in Python (site currently down, the following was pulled from archive.org) #!/usr/bin/python """Ramer-Douglas-Peucker line simplification demo. Dmitri Lebedev, [email protected] http://ryba4.com/python/ramer-douglas-peucker 2010-04-17""" def ramerdouglas(line, dist): """Does Ramer-Douglas-Peucker simplification of a line with `dist` threshold. `line` must be a list of Vec objects, all of the same type (either 2d or 3d).""" if len(line) < 3: return line begin, end = line[0], line[-1] distSq = [begin.distSq(curr) - ((end - begin) * (curr - begin)) ** 2 / begin.distSq(end) for curr in line[1:-1]] maxdist = max(distSq) if maxdist < dist ** 2: return [begin, end] pos = distSq.index(maxdist) return (ramerdouglas(line[:pos + 2], dist) + ramerdouglas(line[pos + 1:], dist)[1:]) class Line: """Polyline. Contains a list of points and outputs a simplified version of itself.""" def __init__(self, points): pointclass = points[0].__class__ for i in points[1:]: if i.__class__ != pointclass: raise TypeError("""All points in a Line must have the same type""") self.points = points def simplify(self, dist): if self.points[0] != self.points[-1]: points = ramerdouglas(self.points, dist) else: points = ramerdouglas( self.points[:-1], dist) + self.points[-1:] return self.__class__(points) def __repr__(self): return '{0}{1}'.format(self.__class__.__name__, tuple(self.points)) class Vec: """Generic vector class for n-dimensional vectors for any natural n.""" def __eq__(self, obj): """Equality check.""" if self.__class__ == obj.__class__: return self.coords == obj.coords return False def __repr__(self): """String representation. The string is executable as Python code and makes the same vector.""" return '{0}{1}'.format(self.__class__.__name__, self.coords) def __add__(self, obj): """Add a vector.""" if not isinstance(obj, self.__class__): raise TypeError return self.__class__(*map(sum, zip(self.coords, obj.coords))) def __neg__(self): """Reverse the vector.""" return self.__class__(*[-i for i in self.coords]) def __sub__(self, obj): """Substract object from self.""" if not isinstance(obj, self.__class__): raise TypeError return self + (- obj) def __mul__(self, obj): """If obj is scalar, scales the vector. If obj is vector returns the scalar product.""" if isinstance(obj, self.__class__): return sum([a * b for (a, b) in zip(self.coords, obj.coords)]) return self.__class__(*[i * obj for i in self.coords]) def dist(self, obj = None): """Distance to another object. Leave obj empty to get the length of vector from point 0.""" return self.distSq(obj) ** 0.5 def distSq(self, obj = None): """ Square of distance. Use this method to save calculations if you don't need to calculte an extra square root.""" if obj is None: obj = self.__class__(*[0]*len(self.coords)) elif not isinstance(obj, self.__class__): raise TypeError('Parameter must be of the same class') # simple memoization to save extra calculations if obj.coords not in self.distSqMem: self.distSqMem[obj.coords] = sum([(s - o) ** 2 for (s, o) in zip(self.coords, obj.coords)]) return self.distSqMem[obj.coords] class Vec3D(Vec): """3D vector""" def __init__(self, x, y, z): self.coords = x, y, z self.distSqMem = {} class Vec2D(Vec): """2D vector""" def __init__(self, x, y): self.coords = x, y self.distSqMem = {} if __name__ == '__main__': coast = Line([ Vec2D( 6.247872 , 11.316756 ), Vec2D( 6.338566 , 11.316756 ), Vec2D( 6.633323 , 11.205644 ), Vec2D( 6.724018 , 11.205644 ), Vec2D( 6.792039 , 11.205644 ), Vec2D( 7.154817 , 11.372311 ), Vec2D( 7.313532 , 11.400089 ), Vec2D( 7.381553 , 11.344533 ), Vec2D( 7.336206 , 11.288978 ), Vec2D( 7.200164 , 11.288978 ), Vec2D( 7.154817 , 11.261200 ), Vec2D( 7.132143 , 11.233422 ), Vec2D( 7.154817 , 11.150089 ), Vec2D( 7.268185 , 11.177867 ), Vec2D( 7.313532 , 11.122311 ), Vec2D( 7.404227 , 11.150089 ), Vec2D( 7.472248 , 11.094533 ), Vec2D( 7.767005 , 10.900089 ), Vec2D( 7.758951 , 10.864989 ), Vec2D( 7.752684 , 10.837656 ), Vec2D( 7.426900 , 10.927867 ), Vec2D( 6.519955 , 10.927867 ), Vec2D( 6.429261 , 10.900089 ), Vec2D( 6.315893 , 10.955644 ), Vec2D( 6.270545 , 10.955644 ), Vec2D( 6.247872 , 10.927867 ), Vec2D( 6.111830 , 11.011200 ), Vec2D( 6.066483 , 11.066756 ), Vec2D( 5.862420 , 11.038978 ), Vec2D( 5.817073 , 10.955644 ), Vec2D( 5.771726 , 10.900089 ), Vec2D( 5.862420 , 10.761200 ), Vec2D( 5.975788 , 10.733422 ), Vec2D( 6.157177 , 10.566756 ), Vec2D( 6.247872 , 10.511200 ), Vec2D( 6.293219 , 10.427867 ), Vec2D( 6.315893 , 10.233422 ), Vec2D( 6.315893 , 10.177867 ), Vec2D( 6.542629 , 9.844533 ), Vec2D( 6.587976 , 9.761200 ), Vec2D( 6.610650 , 9.288978 ), Vec2D( 6.542629 , 9.066756 ), Vec2D( 6.565303 , 8.900089 ), Vec2D( 6.519955 , 8.816756 ), Vec2D( 6.542629 , 8.761200 ), Vec2D( 6.565303 , 8.733422 ), Vec2D( 6.429261 , 8.427867 ), Vec2D( 6.474608 , 8.316756 ), Vec2D( 6.724018 , 8.288978 ), Vec2D( 6.882733 , 8.538978 ), Vec2D( 6.973428 , 8.594533 ), Vec2D( 6.996101 , 8.622311 ), Vec2D( 7.200164 , 8.650089 ), Vec2D( 7.290859 , 8.650089 ), Vec2D( 7.426900 , 8.483422 ), Vec2D( 7.404227 , 8.455644 ), Vec2D( 7.245511 , 8.511200 ), Vec2D( 6.996101 , 8.427867 ), Vec2D( 7.041449 , 8.372311 ), Vec2D( 7.154817 , 8.455644 ), Vec2D( 7.200164 , 8.455644 ), Vec2D( 7.245511 , 8.455644 ), Vec2D( 7.381553 , 8.316756 ), Vec2D( 7.381553 , 8.261200 ), Vec2D( 7.404227 , 8.233422 ), Vec2D( 7.494921 , 8.205644 ), Vec2D( 7.767005 , 8.288978 ), Vec2D( 7.948394 , 8.233422 ), Vec2D( 8.016415 , 8.261200 ), Vec2D( 8.197804 , 8.094533 ), Vec2D( 8.084435 , 7.816756 ), Vec2D( 8.152456 , 7.733422 ), Vec2D( 8.175130 , 7.650089 ), Vec2D( 8.175130 , 7.511200 ), Vec2D( 8.311172 , 7.427867 ), Vec2D( 8.311172 , 7.372311 ), Vec2D( 8.651276 , 7.372311 ), Vec2D( 8.923360 , 7.316756 ), Vec2D( 8.900686 , 7.261200 ), Vec2D( 8.809991 , 7.261200 ), Vec2D( 8.472735 , 7.171122 ), Vec2D( 8.333845 , 7.038978 ), Vec2D( 8.282022 , 6.981100 ), Vec2D( 8.254778 , 6.848911 ), Vec2D( 8.265824 , 6.816756 ), Vec2D( 8.239206 , 6.711211 ), Vec2D( 8.219743 , 6.612067 ), Vec2D( 8.130227 , 6.433044 ), Vec2D( 8.084435 , 6.316756 ), Vec2D( 8.107109 , 6.288978 ), Vec2D( 7.948394 , 6.177867 ), Vec2D( 7.925720 , 5.983422 ), Vec2D( 7.857699 , 5.816756 ), Vec2D( 7.835026 , 5.788978 ), Vec2D( 7.857699 , 5.511200 ), Vec2D( 7.812352 , 5.400089 ), Vec2D( 7.812352 , 5.344533 ), Vec2D( 7.812352 , 5.177867 ), Vec2D( 8.084435 , 4.733422 ), Vec2D( 8.107109 , 4.622311 ), Vec2D( 7.857699 , 4.344533 ), Vec2D( 7.630963 , 4.261200 ), Vec2D( 7.540268 , 4.177867 ), Vec2D( 7.494921 , 4.150089 ), Vec2D( 7.449574 , 4.150089 ), Vec2D( 7.404227 , 4.150089 ), Vec2D( 7.336206 , 4.094533 ), Vec2D( 7.313532 , 4.066756 ), Vec2D( 7.041449 , 4.011200 ), Vec2D( 6.905407 , 3.955644 ), Vec2D( 6.950754 , 3.900089 ), Vec2D( 7.200164 , 3.927867 ), Vec2D( 7.630963 , 3.872311 ), Vec2D( 7.721657 , 3.872311 ), Vec2D( 7.948394 , 3.788978 ), Vec2D( 7.993741 , 3.705644 ), Vec2D( 7.971067 , 3.677867 ), Vec2D( 7.925720 , 3.622311 ), Vec2D( 8.175130 , 3.705644 ), Vec2D( 8.401866 , 3.650089 ), Vec2D( 8.492561 , 3.650089 ), Vec2D( 8.605929 , 3.538978 ), Vec2D( 8.651276 , 3.566756 ), Vec2D( 8.855339 , 3.372311 ), Vec2D( 8.900686 , 3.316756 ), Vec2D( 8.900686 , 3.150089 ), Vec2D( 8.787318 , 2.900089 ), Vec2D( 8.787318 , 2.844533 ), Vec2D( 8.946033 , 2.816756 ), Vec2D( 8.991380 , 2.788978 ), Vec2D( 9.014054 , 2.705644 ), Vec2D( 8.886928 , 2.524989 ), Vec2D( 8.832665 , 2.538978 ), Vec2D( 8.809991 , 2.455644 ), Vec2D( 8.923360 , 2.538978 ), Vec2D( 9.014054 , 2.400089 ), Vec2D( 9.308811 , 2.288978 ), Vec2D( 9.399506 , 2.261200 ), Vec2D( 9.512874 , 2.122311 ), Vec2D( 9.535548 , 1.983422 ), Vec2D( 9.512874 , 1.955644 ), Vec2D( 9.467527 , 1.816756 ), Vec2D( 9.036728 , 1.816756 ), Vec2D( 8.991380 , 1.927867 ), Vec2D( 8.946033 , 1.955644 ), Vec2D( 8.900686 , 1.983422 ), Vec2D( 8.946033 , 2.122311 ), Vec2D( 8.968707 , 2.150089 ), Vec2D( 9.195443 , 1.927867 ), Vec2D( 9.354158 , 1.955644 ), Vec2D( 9.376832 , 2.038978 ), Vec2D( 9.376832 , 2.094533 ), Vec2D( 9.240790 , 2.205644 ), Vec2D( 9.195443 , 2.205644 ), Vec2D( 9.263464 , 2.150089 ), Vec2D( 9.240790 , 2.122311 ), Vec2D( 9.195443 , 2.122311 ), Vec2D( 9.104749 , 2.122311 ), Vec2D( 8.900686 , 2.316756 ), Vec2D( 8.787318 , 2.344533 ), Vec2D( 8.696623 , 2.372311 ), Vec2D( 8.651276 , 2.427867 ), Vec2D( 8.719297 , 2.455644 ), Vec2D( 8.787318 , 2.650089 ), Vec2D( 8.832665 , 2.705644 ), Vec2D( 8.605929 , 2.677867 ), Vec2D( 8.537908 , 2.788978 ), Vec2D( 8.333845 , 2.788978 ), Vec2D( 7.925720 , 2.316756 ), Vec2D( 7.925720 , 2.261200 ), Vec2D( 7.903046 , 2.233422 ), Vec2D( 7.857699 , 2.233422 ), Vec2D( 7.857699 , 2.177867 ), Vec2D( 7.789678 , 1.983422 ), Vec2D( 7.812352 , 1.788978 ), Vec2D( 7.948394 , 1.538978 ), Vec2D( 7.971067 , 1.511200 ), Vec2D( 8.129783 , 1.511200 ), Vec2D( 8.243151 , 1.594533 ), Vec2D( 8.333845 , 1.594533 ), Vec2D( 8.424540 , 1.622311 ), Vec2D( 8.515234 , 1.566756 ), Vec2D( 8.673950 , 1.400089 ), Vec2D( 8.771174 , 1.291756 ), Vec2D( 8.828938 , 1.119878 ), Vec2D( 8.762504 , 0.972544 ), Vec2D( 9.238614 , 0.759633 ), Vec2D( 9.492323 , 0.627022 ), Vec2D( 9.820891 , 0.644711 ), Vec2D( 10.376567 , 0.800622 ), Vec2D( 10.651961 , 1.085978 ), Vec2D( 10.762173 , 1.132022 ), Vec2D( 10.943045 , 1.095989 ), Vec2D( 11.256739 , 0.999878 ), Vec2D( 11.576074 , 0.761611 ), Vec2D( 11.768247 , 0.425211 ), Vec2D( 11.960165 , 0.074778 ), Vec2D( 11.953907 , 0.000000 ), Vec2D( 11.629411 , 0.258767 ), Vec2D( 11.229920 , 0.582278 ), Vec2D( 11.001633 , 0.564300 ), Vec2D( 10.868476 , 0.447478 ), Vec2D( 10.633849 , 0.541833 ), Vec2D( 10.513370 , 0.672133 ), Vec2D( 11.188700 , 0.820078 ), Vec2D( 11.194014 , 0.859656 ), Vec2D( 11.118212 , 0.905822 ), Vec2D( 10.874860 , 0.930311 ), Vec2D( 10.427319 , 0.716522 ), Vec2D( 10.023620 , 0.374211 ), Vec2D( 9.434614 , 0.360144 ), Vec2D( 8.455131 , 0.859544 ), Vec2D( 8.180481 , 0.920500 ), Vec2D( 7.902529 , 1.115078 ), Vec2D( 7.823108 , 1.269800 ), Vec2D( 7.830482 , 1.403778 ), Vec2D( 7.791937 , 1.496744 ), Vec2D( 7.767005 , 1.538978 ), Vec2D( 7.676310 , 1.622311 ), Vec2D( 7.653637 , 1.650089 ), Vec2D( 7.585616 , 1.955644 ), Vec2D( 7.562942 , 1.983422 ), Vec2D( 7.562942 , 2.233422 ), Vec2D( 7.608289 , 2.400089 ), Vec2D( 7.630963 , 2.427867 ), Vec2D( 7.608289 , 2.538978 ), Vec2D( 7.585616 , 2.566756 ), Vec2D( 7.653637 , 2.705644 ), Vec2D( 7.630963 , 2.816756 ), Vec2D( 7.336206 , 3.011200 ), Vec2D( 7.290859 , 3.011200 ), Vec2D( 7.245511 , 3.011200 ), Vec2D( 7.041449 , 2.955644 ), Vec2D( 6.928081 , 2.816756 ), Vec2D( 6.928081 , 2.733422 ), Vec2D( 6.905407 , 2.622311 ), Vec2D( 6.860060 , 2.677867 ), Vec2D( 6.814712 , 2.677867 ), Vec2D( 6.678671 , 2.677867 ), Vec2D( 6.678671 , 2.733422 ), Vec2D( 6.769365 , 2.733422 ), Vec2D( 6.814712 , 2.733422 ), Vec2D( 6.792039 , 2.788978 ), Vec2D( 6.293219 , 3.066756 ), Vec2D( 6.225198 , 3.122311 ), Vec2D( 6.202525 , 3.233422 ), Vec2D( 6.134504 , 3.344533 ), Vec2D( 5.907767 , 3.261200 ), Vec2D( 5.862420 , 3.288978 ), Vec2D( 6.043809 , 3.427867 ), Vec2D( 6.021136 , 3.483422 ), Vec2D( 5.975788 , 3.483422 ), Vec2D( 5.930441 , 3.511200 ), Vec2D( 5.953115 , 3.566756 ), Vec2D( 5.975788 , 3.594533 ), Vec2D( 5.749052 , 3.788978 ), Vec2D( 5.703705 , 3.788978 ), Vec2D( 5.635684 , 3.788978 ), Vec2D( 5.703705 , 3.844533 ), Vec2D( 5.703705 , 4.011200 ), Vec2D( 5.499642 , 4.011200 ), Vec2D( 5.862420 , 4.372311 ), Vec2D( 5.975788 , 4.427867 ), Vec2D( 6.021136 , 4.427867 ), Vec2D( 6.089156 , 4.538978 ), Vec2D( 6.111830 , 4.566756 ), Vec2D( 6.089156 , 4.650089 ), Vec2D( 5.998462 , 4.650089 ), Vec2D( 5.817073 , 4.788978 ), Vec2D( 5.771726 , 4.816756 ), Vec2D( 5.681031 , 4.816756 ), Vec2D( 5.749052 , 4.927867 ), Vec2D( 5.749052 , 5.038978 ), Vec2D( 5.839747 , 5.177867 ), Vec2D( 5.998462 , 5.233422 ), Vec2D( 6.225198 , 5.233422 ), Vec2D( 6.270545 , 5.233422 ), Vec2D( 6.383914 , 5.288978 ), Vec2D( 6.406587 , 5.372311 ), Vec2D( 6.429261 , 5.400089 ), Vec2D( 6.587976 , 5.483422 ), Vec2D( 6.670626 , 5.490000 ), Vec2D( 6.700845 , 5.564100 ), Vec2D( 6.860060 , 5.927867 ), Vec2D( 6.860060 , 6.038978 ), Vec2D( 6.950754 , 6.205644 ), Vec2D( 6.973428 , 6.316756 ), Vec2D( 7.041449 , 6.344533 ), Vec2D( 7.064122 , 6.455644 ), Vec2D( 7.116072 , 6.541989 ), Vec2D( 7.114313 , 6.603667 ), Vec2D( 7.025305 , 6.741422 ), Vec2D( 6.736924 , 6.701367 ), Vec2D( 6.641658 , 6.741467 ), Vec2D( 6.500574 , 6.761389 ), Vec2D( 6.435410 , 6.733422 ), Vec2D( 6.224291 , 6.728556 ), Vec2D( 6.191759 , 6.738989 ), Vec2D( 6.099124 , 6.755000 ), Vec2D( 6.041805 , 6.749733 ), Vec2D( 6.001672 , 6.742967 ), Vec2D( 5.905382 , 6.718300 ), Vec2D( 5.817073 , 6.677867 ), Vec2D( 5.611713 , 6.686622 ), Vec2D( 5.401366 , 6.864333 ), Vec2D( 5.386274 , 6.927867 ), Vec2D( 5.356608 , 6.981811 ), Vec2D( 5.404095 , 7.111822 ), Vec2D( 5.561958 , 7.216133 ), Vec2D( 5.660643 , 7.244722 ), Vec2D( 5.366149 , 7.489478 ), Vec2D( 5.340927 , 7.511200 ), Vec2D( 5.114998 , 7.592867 ), Vec2D( 4.870667 , 7.692033 ), Vec2D( 4.746560 , 7.781856 ), Vec2D( 4.708060 , 7.760867 ), Vec2D( 4.692225 , 7.802500 ), Vec2D( 4.607090 , 7.849044 ), Vec2D( 4.481324 , 7.879711 ), Vec2D( 4.340031 , 8.093378 ), Vec2D( 4.181171 , 8.158044 ), Vec2D( 4.116415 , 8.200800 ), Vec2D( 4.081135 , 8.195278 ), Vec2D( 4.090912 , 8.272500 ), Vec2D( 4.032232 , 8.378311 ), Vec2D( 3.779566 , 8.791278 ), Vec2D( 3.769654 , 8.849022 ), Vec2D( 3.598177 , 8.955178 ), Vec2D( 3.576828 , 9.059633 ), Vec2D( 3.527037 , 9.066756 ), Vec2D( 3.498069 , 9.082022 ), Vec2D( 3.541865 , 9.174211 ), Vec2D( 3.542409 , 9.234411 ), Vec2D( 3.576275 , 9.262711 ), Vec2D( 3.582279 , 9.287744 ), Vec2D( 3.390995 , 9.316756 ), Vec2D( 3.209606 , 9.344533 ), Vec2D( 3.100836 , 9.367511 ), Vec2D( 2.957466 , 9.370756 ), Vec2D( 2.870844 , 9.366222 ), Vec2D( 2.777211 , 9.285222 ), Vec2D( 2.744851 , 9.285900 ), Vec2D( 2.775397 , 9.294867 ), Vec2D( 2.832661 , 9.341156 ), Vec2D( 2.868114 , 9.373300 ), Vec2D( 2.869502 , 9.400089 ), Vec2D( 2.794434 , 9.420178 ), Vec2D( 2.714423 , 9.440078 ), Vec2D( 2.641124 , 9.441944 ), Vec2D( 2.572096 , 9.428378 ), Vec2D( 2.548379 , 9.418600 ), Vec2D( 2.573130 , 9.388211 ), Vec2D( 2.563126 , 9.333567 ), Vec2D( 2.535855 , 9.320067 ), Vec2D( 2.517670 , 9.282778 ), Vec2D( 2.479488 , 9.260278 ), Vec2D( 2.483125 , 9.239067 ), Vec2D( 2.464034 , 9.224278 ), Vec2D( 2.468586 , 9.180556 ), Vec2D( 2.443129 , 9.168989 ), Vec2D( 2.439084 , 9.147456 ), Vec2D( 2.448389 , 9.129344 ), Vec2D( 2.444897 , 9.109600 ), Vec2D( 2.450720 , 9.097256 ), Vec2D( 2.444897 , 9.080389 ), Vec2D( 2.447808 , 9.045822 ), Vec2D( 2.424536 , 9.024011 ), Vec2D( 2.415811 , 9.000133 ), Vec2D( 2.442457 , 8.957422 ), Vec2D( 2.429887 , 8.946567 ), Vec2D( 2.455028 , 8.894556 ), Vec2D( 2.435936 , 8.879078 ), Vec2D( 2.413136 , 8.853411 ), Vec2D( 2.410805 , 8.836944 ), Vec2D( 2.412202 , 8.822133 ), Vec2D( 2.387533 , 8.789544 ), Vec2D( 2.386608 , 8.776044 ), Vec2D( 2.398706 , 8.757278 ), Vec2D( 2.373103 , 8.739511 ), Vec2D( 2.387070 , 8.769467 ), Vec2D( 2.375434 , 8.784611 ), Vec2D( 2.358674 , 8.785922 ), Vec2D( 2.337270 , 8.793167 ), Vec2D( 2.365195 , 8.790533 ), Vec2D( 2.399169 , 8.821478 ), Vec2D( 2.396376 , 8.837933 ), Vec2D( 2.408946 , 8.879078 ), Vec2D( 2.432218 , 8.894878 ), Vec2D( 2.414995 , 8.963022 ), Vec2D( 2.390961 , 8.983722 ), Vec2D( 2.340091 , 8.969389 ), Vec2D( 2.332091 , 8.946244 ), Vec2D( 2.340091 , 8.927722 ), Vec2D( 2.332091 , 8.912289 ), Vec2D( 2.316093 , 8.904067 ), Vec2D( 2.311730 , 8.874744 ), Vec2D( 2.288975 , 8.861244 ), Vec2D( 2.247727 , 8.856233 ), Vec2D( 2.233180 , 8.861889 ), Vec2D( 2.209436 , 8.859233 ), Vec2D( 2.231003 , 8.871144 ), Vec2D( 2.265911 , 8.873200 ), Vec2D( 2.277548 , 8.869600 ), Vec2D( 2.290635 , 8.873711 ), Vec2D( 2.299360 , 8.904578 ), Vec2D( 2.268088 , 8.909622 ), Vec2D( 2.247727 , 8.925256 ), Vec2D( 2.225734 , 8.920756 ), Vec2D( 2.208747 , 8.909622 ), Vec2D( 2.203768 , 8.921811 ), Vec2D( 2.214352 , 8.931822 ), Vec2D( 2.197138 , 8.933811 ), Vec2D( 2.148725 , 8.907478 ), Vec2D( 2.134577 , 8.904844 ), Vec2D( 2.113354 , 8.917222 ), Vec2D( 2.095107 , 8.918800 ), Vec2D( 2.079961 , 8.912944 ), Vec2D( 2.060761 , 8.913356 ), Vec2D( 2.034577 , 8.902656 ), Vec2D( 1.983589 , 8.895400 ), Vec2D( 2.033997 , 8.913356 ), Vec2D( 2.062502 , 8.918700 ), Vec2D( 2.092758 , 8.929811 ), Vec2D( 2.148090 , 8.928756 ), Vec2D( 2.168397 , 8.937878 ), Vec2D( 2.146421 , 8.965533 ), Vec2D( 2.182173 , 8.943933 ), Vec2D( 2.201537 , 8.951311 ), Vec2D( 2.239138 , 8.938400 ), Vec2D( 2.267063 , 8.944989 ), Vec2D( 2.284939 , 8.925767 ), Vec2D( 2.306887 , 8.926022 ), Vec2D( 2.311086 , 8.936356 ), Vec2D( 2.296312 , 8.952489 ), Vec2D( 2.317254 , 8.981122 ), Vec2D( 2.334939 , 9.003844 ), Vec2D( 2.374500 , 9.014044 ), Vec2D( 2.386136 , 9.034778 ), Vec2D( 2.401962 , 9.044656 ), Vec2D( 2.418723 , 9.044889 ), Vec2D( 2.426287 , 9.054878 ), Vec2D( 2.411739 , 9.063522 ), Vec2D( 2.426867 , 9.099311 ), Vec2D( 2.398362 , 9.125233 ), Vec2D( 2.373339 , 9.121944 ), Vec2D( 2.403595 , 9.134289 ), Vec2D( 2.417680 , 9.165778 ), Vec2D( 2.425860 , 9.192778 ), Vec2D( 2.423783 , 9.231400 ), Vec2D( 2.400330 , 9.237022 ), Vec2D( 2.419494 , 9.243567 ), Vec2D( 2.429815 , 9.246711 ), Vec2D( 2.449495 , 9.245489 ), Vec2D( 2.457676 , 9.289856 ), Vec2D( 2.481311 , 9.298211 ), Vec2D( 2.488585 , 9.334211 ), Vec2D( 2.520255 , 9.353822 ), Vec2D( 2.520400 , 9.369944 ), Vec2D( 2.494960 , 9.432511 ), Vec2D( 2.463671 , 9.469200 ), Vec2D( 2.406950 , 9.500578 ), Vec2D( 2.240907 , 9.536433 ), Vec2D( 2.129969 , 9.569467 ), Vec2D( 2.031530 , 9.607422 ), Vec2D( 1.932328 , 9.658044 ), Vec2D( 1.835167 , 9.695656 ), Vec2D( 1.746196 , 9.760744 ), Vec2D( 1.667446 , 9.789667 ), Vec2D( 1.575400 , 9.797622 ), Vec2D( 1.562104 , 9.828722 ), Vec2D( 1.531422 , 9.846800 ), Vec2D( 1.415859 , 9.888744 ), Vec2D( 1.315206 , 9.942167 ), Vec2D( 1.175573 , 10.083667 ), Vec2D( 1.147394 , 10.090267 ), Vec2D( 1.118064 , 10.086567 ), Vec2D( 0.990883 , 9.998400 ), Vec2D( 0.778930 , 9.990856 ), Vec2D( 0.592924 , 10.033144 ), Vec2D( 0.507490 , 10.125422 ), Vec2D( 0.419562 , 10.320811 ), Vec2D( 0.375403 , 10.344533 ), Vec2D( 0.276464 , 10.431189 ), Vec2D( 0.220170 , 10.534911 ), Vec2D( 0.181271 , 10.571000 ), Vec2D( 0.153745 , 10.620156 ), Vec2D( 0.114973 , 10.653889 ), Vec2D( 0.103274 , 10.707756 ), Vec2D( 0.097914 , 10.761511 ), Vec2D( 0.076256 , 10.811522 ), Vec2D( 0.061935 , 10.867833 ), Vec2D( 0.000000 , 10.960167 ) ]) distances = (0, .05, .1, .25) # threshold sizes in kilometres import csv for d in distances: simple = coast.simplify(d) if d > 0 else coast with open('poly-{0}.csv'.format(d), 'w') as output_doc: writer = csv.writer(output_doc, dialect='excel') for pt in simple.points: writer.writerow(pt.coords) A: When I was looking at turning a Bezier curve into straight line segments, what I ended up doing was defining a maximum distance between the curve and a straight line between two points of the curve. Start with one point being one end-point, slide the other end along the curve, until sliding it any further would exceed the maximum distance. Then do it again, using the second (and so on) point, until you've covered the whole curve. You should be able to generate multiple LODs by simply increasing the distance allowed between the line segments and your poly-line.
[ "stats.stackexchange", "0000139015.txt" ]
Q: How to rank rankings? Two factors - freq and rank but freq has to has much more weight My respondents has to evaluate number of items (say, 20). Formerly they had to just check three that they liked (like/dislike) and I simply counted the most checked. I 'improved' survey by replacing check-marks on rank (1-2-3) so respondents not just put check-marks but rank (1,2,3) three attributes they like. That is, every respondent has to choose three best items and rank them. Now I'm struggling how to account this. Known "IMDB" formula based on Bayesian average seems doesn't work for me because puts too much weight on "unscored' items (unranked items considered 'not so bad' by default). In my situation, the fact that item was marked is much more important because respondents always evaluate ALL items (in contrast with IMDB films or any other rating where rating occurs by chance). A: There can be many ways of computing "rating" of attributes based on complete or incomplete ranking task. Each way implies its assumption or model, so it is difficult to say which one might be the "best". Most natural seems to convert ranks into scores and do it non-linearly. Imagine that all 1 through 20 ranks are possible. We assume rank 1 is the "best" and rank 20 is the "worst". Intuitively, the greater in the rank number the lesser is its qualitative difference with the adjacent ranks. Like in sport: "distance" between gold and silver medals is the greatest; between silver and bronze is somewhat less; between bronze and 4th place is further diminished; between 10th and 11th places is hardly distinguishable. Thinking this way, any decreasing "exponentially fading" function of rank will basically do. For example, I could recommend considering reciprocal function 1/Rank or Exponential function in the form of (backward) Savage scores. Both functions are shown below. Rank 1/Rank Savage (backward) 1 1.0000 2.5977 2 .5000 1.5977 3 .3333 1.0977 4 .2500 .7644 5 .2000 .5144 6 .1667 .3144 7 .1429 .1477 8 .1250 .0049 9 .1111 -.1201 10 .1000 -.2312 11 .0909 -.3312 12 .0833 -.4221 13 .0769 -.5055 14 .0714 -.5824 15 .0667 -.6538 16 .0625 -.7205 17 .0588 -.7830 18 .0556 -.8418 19 .0526 -.8974 20 .0500 -.9500 Savage (it's a name) scores are particularly interesting because of their properties. They have always mean 0 and variance greater as the number or data rows N (number of ranks 20, in this instance) grows. Whatever is N, the curve of fading is approximately the same. And the fading (the flattening) is slower than with 1/Rank function. Savage score is computed as $S_i = (1/N + 1/(N-1) +…+ 1/(N-R_i+1)) - 1 $ with $R_i$ being the rank. In our example ranking is backward (that is, the largest $R_i=20$ corresponds to rank=1). Since in the OP question the ranking was incomplete - only ranks 1, 2, 3 were used and ranks 4 through 20 were dismissed (say, the rating process was "interrupted") we have to assume some equal score for all the attributes not ranked by the respondent. The mean of scores for ranks 4 through 20 is the obvious candidate for the value. Another (and more risky) approach would be to impute the mean score corrected by expectation given the attributes that were selected (ranked) by the respondent. That is, if attributes A and B are often seen to be selected together then for those respondents who selected A but not B the score for B shall be higher than just the average score between scores 4 through 20. In this example with the task "select three and rank them" , ranks 4 through 20 were dismissed. In the unconstrained task "select whatever applies and rank the selected" each respondent will have his own "tail" of dismissed ranks. You might then use the respondent-specific average to impute as the score for the not chosen items. However, in the unconstrained task it is natural to assume that the importance of the not selected items is zero or absolute minimal for the respondent. Then there should be used the minimal possible score, and not the average or such as above.
[ "mathoverflow", "0000067812.txt" ]
Q: Is the Brauer group of a surface an elliptic curve? Of course not. But after reading a bit, some points make me believe it should be: Let $S$ be a nice$^{\*}$ surface defined over $Spec\ \mathbb{Z}$. The Brauer group $Br(S\otimes \bar{\mathbb{Q}})$ is an abelian divisible group, It is also a $Gal(\bar{\mathbb{Q}}/\mathbb{Q})$ module, For good primes there are reductions $Br(S)\rightarrow Br(S\otimes \mathbb{F}_q)$, These $Br(S\otimes \mathbb{F}_q)$ are finite, There is a formal Brauer group $\hat{Br}(S)$ of dimension 1, The coefficients of $\hat{Br}$, in suitable natural coordinates, relate to $|Br(S\otimes \mathbb{F}_q)|$. There are some examples where the associated L-function comes from a modular form (of weight 3). I'm not sure if this is conjectured (let alone known) in general. Since the Brauer group observes many characteristics of an abelian variety (all properties) of dimension 1 (properties 5 and 7 [weight isn't two, but it's the right space]), my vague question is: how far is it from actually being a variety? There are some easy examples of $S$ with $|Br(S\otimes \mathbb{F}_q)|$ varying between $1$ and $4(q-4)$, as $q$ varies over the primes. This is a clear point of departure from elliptic curves and varieties in general. Maybe there's a family of natural galois-module homomorphisms into certain abelian varieties defined over $\mathbb{Q}$, commuting with the reduction maps and restriction (or some other appropriate term) to formal groups? What's going on with these Brauer groups? $^\*$ say a K3 surface. Something that (1) is true for (so not a rational surface) and (4) is proven for. A: This is not a general answer to your question, but evidence of the intriguing connection between Brauer groups of surfaces and elliptic curves. Let $X$ be a K3 surface over the complex numbers $\mathbb{C}$. Then, the rank of $H^2(X,\mathbb{Z})$ is $22$, and the Hodge numbers are $h^{0,2}=h^{2,0}=1$ and $h^{1,1}=20$. If the Neron-Severi group of $X$ is as big as possible, namely if it has rank $20$, then the image of $H^2(X,\mathbb{Z})\rightarrow H^2(X,\mathcal{O}_X)$ has rank $2$ and so is a lattice. Therefore, the cokernel of this map is an elliptic curve. But, since $H^3(X,\mathbb{Z})=0$, there is an exact sequence $$H^2(X,\mathbb{Z})\rightarrow H^2(X,\mathcal{O}_X)\rightarrow H^2(X,\mathcal{O}_X^*)\rightarrow 0.$$ Therefore, $H^2(X,\mathcal{O}_X^*)$ is an elliptic curve $E$. The torsion of $H^2(X,\mathcal{O}_X^*)$ is therefore precisely the Brauer group of $X$, and these are precisely the torsion points of $E$. One can produce similar examples using abelian surfaces. For instance, if $E$ is a CM elliptic curve, then $E\times E$ is an abelian surface such that $H^2(E\times E,\mathcal{O}^*)$ is isomorphic to $E$.
[ "stackoverflow", "0026205747.txt" ]
Q: How do I increase the margin within a border using CSS3, so the border isn't so tightly wrapped? I have a a div section that's styled like this: .toppage { border-style:double; border-width:3px; } The result looks like this: Is there anything I can add to the CSS that would increase the space between the border and the elements inside it (e.g., the donate button), so that the border isn't hugging around the elements so tightly, and there's a little room to breathe? Any guidance would be greatly appreciated. Thanks! A: Try this .toppage { border-style:double; border-width:3px; padding : 10px; }
[ "stackoverflow", "0034774954.txt" ]
Q: How to extract 2D array from 4D array based on first and last indices I currently have a numpy array of shape (3, 890, 1100, 2). I would like to extract the 2d array that is at position (0, 0-890, 0-1100, 0), so I would be left with the 890x1100 2d array of the values when indices 1 and 4 are 0. In other words, I would like to access the array as if the parameters were in the order (3, 2, 890, 1100) and do something like: newArray = array[0][0] I understand that I can do this with loops, but was wondering if there is a more "python-esque" way to do it. A: Yes, there is a more pythonic way of indexing numpy arrays. Have a look at the documentation for details. In your particular case, you can achieve the desired result as follows. # Generate some data data = np.random.normal(size=(3, 890, 1100, 2)) # Slice the data subset = data[0, :, :, 0] The : denotes "all elements along this axis".
[ "stackoverflow", "0020152804.txt" ]
Q: converting EXCEL code to SAS I am fairly new to SAS. I designed an algorithm under excel and I am having a lot of trouble converting it to SAS In Excel : A B -1 1 1 . 1 2 0 1 -1 . -1 2 What it does from A to B is that it counts how many times you find the occurrence A in a row. For example (-1) is only here one time, so 1. Then 1, 1 are following each other so I have . (= not significant) followed by 2 (because you have two 1s). And so on so on. My working excel code for column B is : for the first row : IF (A1 = A2, NA(), 1) for the rest of column B (row 10 for example): IF(A10 = A11, NA(), COUNTIF($A$1:A9,"="&NA()) + COUNT ($A$1:A9) + 1 - SUMIF($A$1:A9,"<>#N/A")) The code does work, but I really can't find the equivalent in SAS for COUNTIF, SUMIF, and COUNT.... Here is my code so far data test; input sign; cards; -1 1 1 0 -1 -1 ; run; *create a lead for the equality IF proc expand data=test out=test2; convert sign= sign_lead / transformout = (lead 1); quit; Thanks for your help ! A: You need to take advantage of FIRST and LAST automatic variables. They're created when you use BY. I use NOTSORTED here since you don't actually want to change the order for all the -1s to be together (as that would defeat the purpose). This is something well covered in various papers if you google "FIRST LAST Variable SAS". data test; input sign; cards; -1 1 1 0 -1 -1 ; run; data want; set test; by sign notsorted; if first.sign then _tempcounter=0; _tempcounter+1; if last.sign then b=_tempcounter; drop _tempcounter; run; proc print data=want; run;
[ "askubuntu", "0000097213.txt" ]
Q: Application-specific key combination remapping? I'm aware of a number of ways of remapping key combinations in Ubuntu on a global basis (e.g., globally remapping Ctrl+S to send Ctrl+D or something), such as the xbindkeys application. What I need, though, is a way to do this only for a specific application. For example, something like "Remap Ctrl+S to send Ctrl+D, but only in Chrome". Is there any way to accomplish this? A: Your idea of using xbindkeys sounds good: in your .xbindkeysrc add a new keybinding: "app_specific_keys.sh" Control+s This will execute "app_specific_keys.sh" when you press ctrl+s. Now you need to define the script. It should get the active window and from that the name of the app which currently has the focus: xprop -id `xdotool getactivewindow` |awk '/WM_CLASS/{print $4}' This would do the trick: it asks xdotool for the active window, then asks xprop for all properties of the window with the given id, and then reduces the very verbose output to the name of the application (actually its class). If you run this in a gnome-terminal you would get "Gnome-terminal" Now you need to define actions for your applications: if [ $N = '"Gnome-terminal"' ]; then xdotool key --clearmodifiers ctrl+s else xdotool key --clearmodifiers ctrl+d fi So together, the script "app_specific_keys.sh" could look like this: #!/bin/bash W=`xdotool getactivewindow` S1=`xprop -id ${W} |awk '/WM_CLASS/{print $4}'` S2='"Gnome-terminal"' if [ $S1 = $S2 ]; then xdotool key --clearmodifiers ctrl+d else xdotool key --clearmodifiers ctrl+s fi This should work, but as in this question, I have to admit that it does not. Probably because one of Compiz, Unity, Global Menu does not work well with the --clearmodifiers option of xdotool. A workaround would be to add a sleep in front of your script in oder to be able to release the keys yourself: In your .xbindkeysrc change to this keybinding: "sleep 0.5; app_specific_keys.sh" Control+s As a sidenote: this will not work, if you want to change keys for programs which run in a terminal (e.g. vi or emacs in console mode). The returned application class would still be "Gnome-terminal". Hope that helps.
[ "stackoverflow", "0035913391.txt" ]
Q: Retrofit2 + SimpleXML in Kotlin: MethodException: Annotation must mark a set or get method I want to fetch XML data from API and map it to Kotlin model object by using Retrofit2 + SimpleXML in Kotlin. However, I got such as the following error message from SimpleXML. org.simpleframework.xml.core.MethodException: Annotation @org.simpleframework.xml.Element(data=false, name=, required=true, type=void) must mark a set or get method This is fetched XML data <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <response> <result code="0">Success</result> <token>XXXXXXXXXXXXXXXXXXXX</token> <uid>4294967295</uid> </response> Kotlin model object is below @Root(name = "response") public class User() { @Element public var result: String? = null @Element public var token: String? = null @Element public var uid: String? = null } and APIClient is as follows. interface MyService { @GET("/testLogin.xml") fun getUser(): Call<User> } val retrofit = Retrofit.Builder() .baseUrl(baseURL) .addConverterFactory(SimpleXmlConverterFactory.create()) .build() val call = retrofit.create(MyService::class.java).getUser() call.enqueue(object: Callback<User> { override fun onResponse(p0: Call<User>?, response: Response<User>?) { val response = response?.body() } override fun onFailure(p0: Call<User>?, t: Throwable?) { Log.e("APIClient", t?.message) } I got HTTP status code 200 and correct XML data. So I think my declaration of model object is problem. A: This is the same problem as: kotlin data class + bean validation jsr 303 You need to use Annotation use-site targets since the default for an annotation on a property is prioritized as: parameter (if declared in constructor) property (if the target site allows, but only Kotlin created annotations can do this) field (likely what happened here, which isn't what you wanted). Use get or set target to place the annotation on the getter or setter. Here it is for the getter: @Root(name = "response") public class User() { @get:Element public var result: String? = null @get:Element public var token: String? = null @get:Element public var uid: String? = null } See the linked answer for the details. A: To avoid the error in parse do one should place annotation tags @set e @get @Root(name = "response", strict = false) public class User() { @set:Element(name = "result") @get:Element(name = "result") public var result: String? = null @set:Element(name = "token") @get:Element(name = "token") @Element public var token: String? = null @set:Element(name = "uid") @get:Element(name = "uid") public var uid: String? = null }
[ "stackoverflow", "0059555189.txt" ]
Q: Need explanation about displacment and get_rect I am following a tutorial. I wrote this : import pygame import time import os import random import neat WIN_WIDTH = 600 WIN_HEIGHT = 800 Bird_imgs = [pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))), pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird2.png"))), pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird3.png")))] Base_img = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs,", "base.png"))) Pipe_img = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs,", "pipe.png"))) Bg_img = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs,", "bg.png"))) class Bird: imgs = Bird_imgs Max_Rotation = 25 Rot_Vel = 20 Animation_Time = 5 #Init def __init__(self, x, y): self.x = x self.y = y self.tilt = 0 self.tick_count = 0 self.vel = 0 self.height = self.y self.img_count = 0 self.img = self.imgs[0] #It's the image from Bird_imgs (bird1) def jump(self): self.vel = -10.5 self.tick_count = 0 self.height = self.y def move(self): self.tick_count += 1 d = self.vel*self.tick_count + 1.5*self.tick_count**2 if d >= 16: d = 16 if d < 0: d -= 2 self.y += d if d < 0 or self.y < self.height + 50: if self.tilt < self.Max_Rotation: self.tilt = self.Max_Rotation else: if self.tilt > -90: self.tilt -= self.Rot_Vel def draw(self, win): self.img_count += 1 if self.img_count < self.Animation_Time: self.img = self.imgs[0] elif self.img_count < self.Animation_Time*2: self.img = self.imgs[1] elif self.img_count < self.Animation_Time*3: self.img = self.imgs[2] elif self.img_count < self.Animation_Time*4: self.img = self.imgs[1] elif self.img_count == self.Animation_Time*4 +1: self.img = self.imgs[0] self.img_count = 0 if self.tilt <= 80: self.img = self.imgs[1] self.img_count = self.Animation_Time*2 rotated_image = pygame.transform.rotate(self.img, self.tilt) new_rectangle = rotated_image.get_rect(center=self.img.get_rect(topleft = (self.x, self.y)).center) I understood almost everything. First, we import modules. We define the resolution. Then we load images and we scale them. We create a few variables in our class. We initialize... But, This line : d = self.vel*self.tick_count + 0.5*(3)*(self.tick_count)**2 comes from a physic formula. But why 3 ? Can you tell me what does : if d < 0 or self.y < self.height + 50: if self.tilt < self.Max_Rotation: self.tilt = self.Max_Rotation else: if self.tilt > -90: self.tilt -= self.Rot_Vel do ? And why these values ? Can you explain to me these 2 lines : rotated_image = pygame.transform.rotate(self.img, self.tilt) new_rectangle = rotated_image.get_rect(center=self.img.get_rect(topleft = (self.x, self.y)).center) ? Especially the last one. Thank you. A: Your first question is why the "3" in the kinematic equation in place of "a". Well, my guess is whoever wrote your simulation felt like a value of 3 for the acceleration constant worked the best visually. It seems to me that "d" is the distance your bird falls from its height at the time of a previous jump. After every time you jump, you have to reset your height and "time" (tick_marks) and return to normal, kinematic, constant acceleration physics, and from there you can continually measure a height deviation from that point ("d"). If the "d" value is negative (ie you are still jumping upwards) or after the bird has fallen 50 pixels from the max_height setpoint, you set your tilt (angle) to a certain rotation amount. If it hasn't dropped that far yet, you are slowly tilting the bird every frame. First line rotates the image object. The 2nd line is to determine WHERE the image should be bilted. Namely, you are creating a new surface with rectangular dimensions of the same area as the previous image and the same center (ie rotating the location). I'll let you figure out which parts of the syntax refer to the actions above and why, but feel free to ask questions in the comments.
[ "stackoverflow", "0052721062.txt" ]
Q: Asp.net Textbox displayed side by side Hello guys I just started designing form with asp.net tags and would like to achieve what's on the image exactly. Thanks guy A: If i understand you right, this is the code you need: <asp:TextBox runat="server"></asp:TextBox><asp:TextBox runat="server"></asp:TextBox> and the result: Add some styles to make it pretty. Blockquote Here is the code with labels (you can also use asp labels): <div style="display: inline-grid"> <asp:TextBox runat="server"></asp:TextBox><label>textbox1</label> </div> <div style="display: inline-grid"> <asp:TextBox runat="server"></asp:TextBox><label>textbox2</label> </div> and the result: You can also put the style in the css.
[ "stackoverflow", "0000887605.txt" ]
Q: NHibernate "database" schema confusion [.\hibernate-mapping\@schema] I'm using NHibernate primarily against an MSSQL database, where I've used MSSQL schemas for the various tables. In my NH mapping (HBM) files, I've specified the schema for each table in the mapping as follows: <?xml version="1.0"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" schema="xyz"> <!-- schema specified --> <class name="Customer"> <id name="Id"> <generator class="native" /> </id> <property name="Name" /> </class> </hibernate-mapping> For my unit testing, I've been experimenting with SQLite, however my mappings fail now as NH reports that the database "xyz" cannot be found. I understand there is a difference in interpretation of schema, so what is NH's interpretation/implementation, and what is the best approach when using schema's? BTW: Searching the web using keywords like "nhibernate database schema" doen't yielded anything relevant. A: The "standard" interpretation is that a table has a three-part name: "CATALOG.SCHEMA.TABLE" : these are the names used in the standard (ISO-SQL standard?) "information_schema" views. Hibernate (presumably also NHibernate) follows this convention, you can specify catalog and schema in a class mapping, and default_catalog and default_schema in a configuration. In my own unit test environment (using Hypersonic), I massaged the Hibernate Configuration before building the SessionFactory: I myself did this to do things like setting HSQL-compatible IdentifierGenerators, but you can problably go through clearing the schema properties of the mapped classes. In general, I try to avoid specifying schemas and catalogs in applications at all. In Oracle, I generally create synonyms so users see the objects in their own namespace; in PostgreSQL, set the search_path in the database configuration; in SQL Server, put all tables into 'dbo'.
[ "stackoverflow", "0057511139.txt" ]
Q: Add a xib file to a Swift Package I want to start using modular code with the new Swift Package Manager integration with Xcode 11. The problem is that I can't seem to add any kind of UI files to my new package. I just need to add a xib file. How is this accomplished? A: Currently Swift packages only support source code so you can't add a xib file to the package. Read the What's Missing? section in the following article: Creating Swift Packages in Xcode
[ "stackoverflow", "0007409542.txt" ]
Q: dynamically write image's alt value as text with jQuery Trying to write a small function that updates a paragraph with an image's alt text. the .active class is the image being viewed. I'll launch this function on doc.ready and under a few .click events. Here's what i've got with no results: $("#title").text($('.z.active').attr('alt', '')); Thanks for your help! A: This illustrates the basics of the jQuery in question. I assume you can handle the click events. HTML: <div class="z"> <img class="active" alt="foobar" src="http://placehold.it/350x150"/> </div> <div id="title"></div> Javascript: $("#title").text($('.z .active').attr('alt')); Check it out on JSFiddle.
[ "stackoverflow", "0009232288.txt" ]
Q: Facebook friend counter What I'm trying to do is a counter of facebook friends in php, so the result of the code would be something like "You have 1342 Friends!". So this is the code im using: <?php require_once("../src/facebook.php"); $config = array(); $config[‘appId’] = 'MY_APP_ID'; $config[‘secret’] = 'MY_APP_SECRET'; $facebook = new Facebook($config); $user_id = "MY_USER_ID"; //Get current access_token $token_response = file_get_contents ("https://graph.facebook.com/oauth/access_token? client_id=$config[‘appId’] &client_secret=$config[‘secret’] &grant_type=client_credentials"); // known valid access token stored in $token_response $access_token = $token_response; $code = $_REQUEST["code"]; // If we get a code, it means that we have re-authed the user //and can get a valid access_token. if (isset($code)) { $token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&client_secret=" . $app_secret . "&code=" . $code . "&display=popup"; $response = file_get_contents($token_url); $params = null; parse_str($response, $params); $access_token = $params['access_token']; } // Query the graph - Friends Counter: $data = file_get_contents ("https://graph.facebook.com/$user_id/friends?" . $access_token ); $friends_count = count($data['data']); echo "Friends: $friends_count"; echo "<p>$data</p>"; //to test file_get_contents ?> So, the result of the echo $Friends_count its always "1". And then I test $data with an echo and it give me the list of all the friends so it is getting the content but its not counting it right... how could i fix it? I've already tried changing the $friends_count = count($data['data']); for $friends_count = count($data['name']); and $friends_count = count($data['id']); but the result is always "1". The result of the above code looks like this; Friends: 1 {"data":[{"name":"Enny Pichardo","id":"65601304"},{"name":"Francisco Roa","id":"500350497"},etc...] A: You have a JSON object; a string, not anything PHP can "count" with count(). You need to parse the JSON first: $obj=json_decode($data); $friends_count = count($obj->data); // This refers to the "data" key in the JSON Some references I quickly googled: http://php.net/manual/en/function.json-decode.php http://roshanbh.com.np/2008/10/creating-parsing-json-data-php.html
[ "stackoverflow", "0006930929.txt" ]
Q: MvcMiniProfiler will not show database profiling when using code first and repository pattern I am trying to setup database profiling with my ASP.NET MVC3 application. I have followed every blog I can find about this and the result is: In web.config: <system.data> <DbProviderFactories> <remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" /> <add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.6.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" /> </DbProviderFactories> </system.data> In Global.asax: protected void Application_Start() { Bootstrapper.Run(); MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["TemplateDB"].ConnectionString); var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory); Database.DefaultConnectionFactory = profiled; } protected void Application_BeginRequest() { if (Request.IsLocal) { MiniProfiler.Start(); } } protected void Application_EndRequest() { MiniProfiler.Stop(); } In controller: public ActionResult About() { var profiler = MiniProfiler.Current; using (profiler.Step("call database")) { ProjectResult result = projectService.Create("slug"); return View(); } } I am using the repository patterns and my EF Code first lives in another project that is referenced by the MVC application. My database class looks like: public class Database : DbContext { public Database(string connection) : base(connection) { } public DbSet<Project> Projects { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Project>().Property(p => p.Slug).IsUnicode().IsRequired().IsVariableLength().HasMaxLength(64); } public virtual void Commit() { base.SaveChanges(); } } My database factory looks like: public class DatabaseFactory : Disposable, IDatabaseFactory { private readonly string connectionString; private Database database; public DatabaseFactory(string connectionString) { Check.Argument.IsNotNullOrEmpty(connectionString, "connectionString"); this.connectionString = connectionString; } public Database Get() { return database ?? (database = new Database(connectionString)); } protected override void DisposeCore() { if (database != null) database.Dispose(); } } When I run my application the profiler will not show any database profiling at all, just the regular execution time of the controller/view. Any help is appreciated. Thanks A: Solved by installing the Nuget MiniProfiler and MiniProfiler.EF package. Add the following in the Global.asax protected void Application_Start() { MiniProfilerEF.Initialize(); } protected void Application_BeginRequest() { if (Request.IsLocal) { MiniProfiler.Start(); } } protected void Application_EndRequest() { MiniProfiler.Stop(); } And finally add the below code to the head tage below JQuery of your markup. @MvcMiniProfiler.MiniProfiler.RenderIncludes() You're set. Works like a charm.
[ "serverfault", "0000083838.txt" ]
Q: Mount a remote folder on Nautilus... where is the mount point? When I use Nautilus to perform a mount on a volume, where is the mount point located in the local filesystem? A: Check out $HOME/.gvfs - mount name will differ per host - this also assumes you connected it as a user mount.
[ "arduino.stackexchange", "0000070448.txt" ]
Q: Will an Arduino UNO operating at 16mHz communicate with UART / I2C with an STM32 operating at a different frequency? I plan to connect Arduino UNO via I2C / UART with a controller based on STM32F334K8T6, whose frequency will be about 20mHz or higher. Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them? The tire speed will be equal. (UART 115200 Baud / I2C 100kHz) A: Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them? No it doesn't. Or not much any way. It may affect the accuracy of clock generation1, which may have an affect at very high asynchronous baud rates, but other than that, no. For synchronous communication it's all synchronised to the communication protocol's clock, so processor clocks are irrelevant. 1: Baud rates are usually generated as an integer division of the system clock. Different system clocks give different results for baud rate divisor calculations, yielding marginally different baud rates. Different baud rates will have different error percentages on different system clocks. At low speeds this has no noticeable affect. At high speeds (millions of bits per second) it can cause errors to creep in.
[ "stackoverflow", "0037895991.txt" ]
Q: Questions regarding operations on NaN My SSE-FPU generates the following NaNs: When I do a any basic dual operation like ADDSD, SUBSD, MULSD or DIVSD and one of both operands is a NaN, the result has the sign of the NaN-operand and the lower 51 bits of the mantissa of the result is loaded with the lower 51 bits of the mantissa of the NaN-operand. When both operations are NaN, the result is loaded with the sign of the destination-register and the lower 51 bits of the result-mantissa is loaded with the lower 51 bits of the destination-register before the operation. So the associative law doesn't count when doing multiplications on two NaN-operands! When I do a SQRTSD on a NaN-value, the result has the sign of the NaN-operand and the lower 51 bits of the result is loaded with the lower 51 bits of the operand. When I do a multiplication of infinity with zero or infinity, I always get -NaN as a result (binary representation 0xFFF8000000000000u). If any operand is a signalling NaN, the result becomes a quiet NaN if the exception isn't masked. Is this behaviour determined anywhere in the IEEE-754-standard? A: NaN have a sign and a payload, together are called the information contained in the NaN. The whole point of NaNs is that they are "sticky" (maybe Monadic is a better term?), once we have a NaN in an expression the whole expression evaluate to NaN. Also NaNs are treated specially when evaluating predicates (like binary relations), for example if a is NaN, then it is not equal to itself. Point 1 From the IEEE 754: Propagation of the diagnostic information requires that information contained in the NaNs be preserved through arithmetic operations and floating-point format conversions. Point 2 From the IEEE 754: Every operation involving one or two input NaNs, none of them signaling, shall signal no exception but, if a floating-point result is to be delivered, shall deliver as its result a quiet NaN, which should be one of the input NaNs. No floating point operation has ever been associative. I think you were looking for the term commutative though since associativity requires at least three operands involved. Point 3 See point 4 Point 4 From IEEE 754: The invalid operations are 1. Any operation on a signaling NaN (6.2) 2. Addition or subtraction – magnitude subtraction of infinities such as, (+INFINITY) + (–INFINITY) 3. Multiplication – 0 × INFINITY 4. Division – 0/0 or INFINITY/INFINITY 5. Remainder – x REM y, where y is zero or x is infinite 6. Square root if the operand is less than zero 7. Conversion of a binary floating-point number to an integer or decimal format when overflow, infinity, or NaN precludes a faithful representation in that format and this cannot otherwise be signaled 8. Comparison by way of predicates involving < or >, without ?, when the operands are unordered (5.7, Table 4) Point 5 From IEEE 754: Every operation involving a signaling NaN or invalid operation (7.1) shall, if no trap occurs and if a floating-point result is to be delivered, deliver a quiet NaN as its result. Due to its relevance, the IEEE 754 standard can be found here.
[ "stackoverflow", "0013001710.txt" ]
Q: Having trouble with ASP.NET MVC 4 image uploading I'm trying to upload a image along with other fields. Been following examples from here and here However it seems that the image object isn't passed to the controller and i'm unable to find any error. Here's the view: @model Project.Models.ContentNode @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> <legend>News</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> @*Image upload field*@ <div class="editor-field"> <input type="file" name="file" /> </div> <div class="editor-label"> @Html.LabelFor(model => model.Body) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Body) @Html.ValidationMessageFor(model => model.Body) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> Here are the controller methods: public ActionResult Create() { var model = new ContentNode(); return View( model ); } [HttpPost] public ActionResult Create(ContentNode nyF, HttpPostedFileBase imageData) { // Get the type of content from DB var k = (from ct in _db.ContentTypes where ct.ID == 1 select ct).Single(); var curUser = (from u in _db.Users where u.Username == User.Identity.Name select u).Single(); nyF.Author = curUser; nyF.ContentType = k; nyF.dateCreated = DateTime.Now; _db.ContentNodes.Add(nyF); _db.SaveChanges(); // Process image if ((imageData != null && imageData.ContentLength > 0)) { var fileName = Path.GetFileName(imageData.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); imageData.SaveAs(path); } else { return Content("The image object wasn't received"); } return View(nyF); } I've read over the whole thing over and over and am unable to see the error. Anyone here willing to point out what I'm doing wrong? A: The name of the input file needs to match the action parameter <input type="file" name="file" /> should be <input type="file" name="imageData" /> or you change your action parameter name public ActionResult Create(ContentNode nyF, HttpPostedFileBase file)
[ "stackoverflow", "0005275098.txt" ]
Q: A CSS selector to get last visible div A tricky CSS selector question, don't know if it's even possible. Lets say this is the HTML layout: <div></div> <div></div> <div></div> <div style="display:none"></div> <div style="display:none"></div> I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example. Mind you, the number of divs on the real page can differ (even the display:none ones). A: You could select and style this with JavaScript or jQuery, but CSS alone can't do this. For example, if you have jQuery implemented on the site, you could just do: var last_visible_element = $('div:visible:last'); Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like: var last_visible_element = $('#some-wrapper div:visible:last'); A: The real answer to this question is, you can't do it. Alternatives to CSS-only answers are not correct answers to this question, but if JS solutions are acceptable to you, then you should pick one of the JS or jQuery answers here. However, as I said above, the true, correct answer is that you cannot do this in CSS reliably unless you're willing to accept the :not operator with the [style*=display:none] and other such negated selectors, which only works on inline styles, and is an overall poor solution. A: If you can use inline styles, then you can do it purely with CSS. I am using this for doing CSS on the next element when the previous one is visible: div[style='display: block;'] + table { filter: blur(3px); }
[ "stackoverflow", "0038178146.txt" ]
Q: How to create an animation in a splash screen? When we open a app we get different type of animated object or people moving around in the splash screen of an app for example like a person running while the app is loaded or the name of the app falls and a guy sits on it clicking photos. How can we create one and what type of software do we use? Can you suggest me some tutorials to follow? A: 1) use gif OR 2) use Animation https://www.youtube.com/watch?v=YPDfBwPrauI as per your requirement Another animated Splash Demo A: You can also use your own created gif images to show on the imageview at splash screen through Glide image loading and caching library. Like : ImageView imageView = (ImageView) findViewById(R.id.imageView); GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imageView); Glide.with(this).load(R.raw.gif_image).into(imageViewTarget); A: paste this xml <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/bounce_interpolator" > <scale android:duration="600" android:fromXScale="1" android:fromYScale="0.5" android:pivotX="50%" android:pivotY="0%" android:toXScale="1.0" android:toYScale="1.0" /> <alpha android:duration="600" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set> and on the splash screen Animation animation = AnimationUtils.loadAnimation(contex, R.anim.blink); animation.setInterpolator(new LinearInterpolator()); animation.setRepeatCount(Animation.INFINITE); animation.setDuration(700); and use this Animation like final ImageView splash = (ImageView) findViewById(R.id.btnrecievecall); splash.startAnimation(animation)
[ "stackoverflow", "0046504903.txt" ]
Q: How can I add text to the output returned from my select in SQL? I have this query: Select Number from CardChoice it returns Number 1 2 3 How can I add text to that so it returns Batch Batch 1 Batch 2 Batch 3 A: You can use the || operator for concatenate string Select 'Batch ' || Number as Batch from CardChoice
[ "stackoverflow", "0029128326.txt" ]
Q: What is wrong with this FX Application? I am hours trying to know why this code is wrong, it gives me an Exception, the GUI.fxml is on the root of the project. public class MyApp extends Application{ @Override public void start(Stage primaryStage) throws Exception { String location = "/GUI.fxml"; Parent root = FXMLLoader.load(getClass().getResource(location)); primaryStage.setScene(new Scene(root,300,450)); primaryStage.setTitle("Minha Janela"); primaryStage.show(); } public static void main(String[] args) { launch(args); } } Already searched a lot, no solution found yet. Exception in Application start method Exception in thread "main" java.lang.RuntimeException: Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403) at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47) at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NullPointerException: Location is required. at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2825) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2809) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2795) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2782) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2771) at g1.MyApp.start(MyApp.java:13) at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319) at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:219) at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:182) at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:179) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17) at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67) ... 1 more A: The FXML should not be in the root of the project, but in the classpath. Try relocating the fxml into a source folder. For general projects, you have a src folder. You can also create your own custom source folder also. For maven projects, you can try keeping them inside src/main/resources.
[ "stackoverflow", "0018452431.txt" ]
Q: Example of ggplot2 stat_summary_hex using alpha aesthetic mapping? I'm plotting customer churn using the ggplot2 stat_summary_hex function. stat_summary_hex(aes(x = Lon, y = Lat, z = Churn), bins=100, colour = NA, geom = "hex", fun = function(x) sum(x)) ScaleFill <- scale_fill_gradient2(low = "blue", high = "orange", na.value = NA) The stat_summary_hex is plotted over a basemap from get_map so I would like to set the alpha scale such that summary values close to 0 would have an alpha of 0. However, it looks like stat_summary_hex does not acknowledge an alpha aesthetic. Does someone have an example of stat_summary_hex with alpha mapping? A: I found a work around by setting drop = TRUE and then changing the stat_summary_hex function to return NA when the result was less than my threshold: stat_summary_hex(aes(x = Lon, y = Lat, z = Churn), bins=100, colour = NA, geom = "hex", drop = TRUE, fun = function(x) if(abs(sum(x)) > 5) {sum(x)} else {NA})
[ "mathoverflow", "0000030827.txt" ]
Q: Where does the "Hardy-Littlewood" conjecture that pi(x+y) < pi(x) + pi(y) originate? The conjecture that $\pi(x+y) \leq \pi(x) + \pi(y)$, with $\pi$ the counting function for prime numbers, is customarily attributed to Hardy and Littlewood in their 1923 paper, third in the Partitio Numerorum series on additive number theory and the circle method. For example, Richard Guy's book Unsolved Problems in Number Theory cites the paper and calls the inequality a "well-known conjecture ... due to Hardy and Littlewood". Partitio Numerorum III is one of the most widely read papers in number theory, detailing a method for writing down conjectural (but well-defined) asymptotic formulas for the density of solutions in additive number theory problems such as Goldbach, twin primes, prime $k$-tuplets, primes of the form $x^2 + 1$, etc. This formalism in the case of prime $k$-tuplets, with the notion of admissible prime constellations and an asymptotic formula for the number of tuplets, came to be known as the "Hardy-Littlewood [prime k-tuplets] conjecture" and indeed is one of several explicit conjectures in the paper. However, the matter of whether $\pi(x+y) \leq \pi(x) + \pi(y)$, for all $x$ and $y$, does not actually appear in the Hardy-Littlewood paper. They discuss the inequality only for fixed finite $x$ and for $y \to \infty$, relating the packing density of primes in intervals of length $x$ to the $k$-tuplets conjecture. (The lim-sup density statements that H & L consider were ultimately shown inconsistent with the k-tuplets conjecture by Hensley and Richards in 1973). The questions: Are there other works of Hardy or Littlewood where the inequality on $\pi(x+y)$ is discussed, or stated as a conjecture? Where does the inequality first appear in the literature as a conjecture? Is there any paper that suggests the inequality (for all finite $x$ and $y$, not the asymptotic statement considered by Hardy-Littlewood) is likely to be correct? A: I took a look at Schinzel and Sierpinski, Sur certaines hypotheses concernant les nombres premiers, Acta Arith IV (1958) 185-208, reprinted in Volume 2 of Schinzel's Selecta, pages 1113-1133. In the Selecta, there is a commentary by Jerzy Kaczorowski, who mentions "the G H Hardy and J E Littlewood conjecture implicitly formulated in [33] that $\pi(x+y)\le\pi(x)+\pi(y)$ for $x,y\ge2$." [33] is Partitio Numerorum III. Schinzel and Sierpinski (page 1127 of the Selecta) define $\rho(x)=\limsup_{y\to\infty}[\pi(y+x)-\pi(y)]$, and point to that H-L paper, pp 52-68. They then write (page 1131), "$\bf C_{12.2}.$ L'hypothese de Hardy et Littlewood suivant laquelle $\rho(x)\le\pi(x)$ pour $x$ naturels $\gt1$ equivaut a l'inegalite $\pi(x+y)\le\pi(x)+\pi(y)$ pour $x\gt1,y\gt1$." It should be said that the proof that the first inequality implies the second relies on Hypothesis H, which essentially says that if there is no simple reason why a bunch of polynomials can't all be prime, then they are, infinitely often. Schinzel and Sierpinski express no opinion as to any degree of belief in the conjecture under discussion. I don't suppose this actually answers any of the questions, although Kaczorowski's use of the word "implicitly" may be significant.
[ "stackoverflow", "0063640127.txt" ]
Q: Have a function with generic return a function with same generic For example, I want the following function to return a function that accepts any string or any number, depending on what the initial function was called with, but it only accepts strings or numbers that are equal to a: function foo<A extends string | number>(a: A) : (b: A) => boolean { return (b) => a === b; } foo("test") // creates a function that only accepts "test", want one that accepts any string. foo(3) // creates a function that only accepts 3, want one that accepts any number. How do I type this function so it works as wanted? edited to clarify what the problem is A: If you just remove the extends string it seems to do what you want function foo<A>(a: A) : (b: A) => boolean { return (b) => a === b; } Typescript Playground Link If you want to restrict your input types and still have them pass through you could do the following function foo(a:string): (b:string) => boolean function foo(a:number): (b:number) => boolean function foo(a:boolean): (b:boolean) => boolean function foo (a: string|number|boolean) : (b: string|number|boolean) => boolean { return (b) => a === b; } foo("test")("a") //expects string foo(1)(2) //expects number Playground Link
[ "stackoverflow", "0052490181.txt" ]
Q: Passing parameter from for loop to multiline sh in jenkins pipeline I have groovy jenkins pipeline step and I want to pass for loop value as parameter to multiline sh script in loop. But parameter is not getting passed. Or if theres a better way to add step in jenkins stage? for (int i = 0; i < elements.size(); i++) { sh ''' cd terraform/ terraform init terraform workspace select ${elements[i]}-${envtype} terraform plan -var-file="./configs/${elements[i]}/var.tf" ''' } A: It seems that you should use """ instead of '''. ''' is triple single quoted String and doesn't support interpolation.
[ "stackoverflow", "0029046934.txt" ]
Q: Calculate "matrix of cofactors" in R? Is there any way to calculate the matrix of cofactors in R directly? (Without multiplying it by determinant!) http://en.wikipedia.org/wiki/Minor_(linear_algebra)#Matrix_of_cofactors A: Build your own function: library(functional) M<-matrix(1:9,3,3) getCofactor = function(M, i, j) { stopifnot(length(unique(dim(M)))==1) stopifnot(all(c(i,j)<=dim(M))) det(M[-i,-j])*(-1)^(i+j) } grid = expand.grid(1:dim(M)[1], 1:dim(M)[2]) matrix(mapply(Curry(getCofactor, M=M), grid$Var1, grid$Var2), nrow=dim(M)[1])
[ "stackoverflow", "0033654225.txt" ]
Q: Cannot merge on an Eloquent collection in Laravel I need to merge either a collection or an array (it can be either) in Laravel 5.1, but I am getting the error BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::merge() When I make a collection from scratch, I can merge to it, but I cannot merge onto the result of an Eloquent query, which I thought were collections as well. But perhaps that is not true? Code that gives the error: $user=User::where('user_last_name', 'Doe')->first(); $tomerge = collect(['book' => 'desk', 'foot' => 'chair']); $newcollect = $user->merge($tomerge); If I instead did $tomerge->merge($user) it works, but that's not what I actually need. Is there a way to use merge as I want? A: To answer your question as to why it's not working... $user = User::where('user_last_name', 'Doe')->first(); This is a single instance of a model. Not a collection. An eloquent model does not have the merge method. If you want to append attributes to an Eloquent model, the simplest way is probably to use the $appends property and the appropriate accessor. For example, in your User model.. protected $appends = ['book', 'foot']; public function getBookAttribute() { return 'desk'; } public function getFootAttribute() { return 'chair'; } However, note that this will affect every instance of your User model.
[ "stackoverflow", "0027649641.txt" ]
Q: Does OpenSSL allow multiple SSL_CTX per process, one SSL_CTX used for server sessions and the other SSL_CTX for client sessions? I have a Linux process that needs to act as an SSL server (accept and service connections from other clients) but also needs to - in the same process - initiate client sessions with other SSL servers. I intend to create two separate SSL_CTX handles using two SSL_CTX_new() function calls, one invoked with server methods and the other with client methods. Is such dual-use of OpenSSL within a single process supported? My hope is that OpenSSL uses the SSL_CTX handle - and does not rely on global or static local variables - for all context information it may need to create and service new sessions. Is this a good assumption? A: Does OpenSSL allow multiple SSL_CTX per process, one SSL_CTX used for server sessions ... Yes, and this is quite common. Its common when using Server Name Indication. In the case of SNI, you have a default SSL_CTX and then a SSL_CTX for each server. You then return the default SSL_CTX or a specialized SSL_CTX in the SNI callback if the client included the server name extension in its ClientHello. SSL_CTX are referenced counted by the library, so they are not truly freed until the reference count drops to 0 in one of the SSL_CTX_free calls. Here are some related questions on SNI, if interested: Serving multiple domains in one box with SNI How to implement Server Name Indication (SNI) SSL_CTX_set_tlsext_servername_callback callback function not being called The first even provides you with the callback code. GetServerContext returns a new (or existing) context based on the server name: /* Need a new certificate for this domain */ SSL_CTX* ctx = GetServerContext(servername); if(ctx == NULL) handleFailure(); ... /* Set new context */ SSL_CTX* v = SSL_set_SSL_CTX(ssl, ctx); Does OpenSSL allow multiple SSL_CTX per process, ... other SSL_CTX for client sessions? Yes, but you usually don't use it. The client does not usually change its SSL_CTX like the server does. In the case that a client connects to multiple servers, usually you set your channel parameters with SSL_CTX_set_options and use that for every connection to every server (even different ones). Parameters would be things like protocols (TLS 1.1, TLS 1.2), cipher suites (removing anonymous cipher suites) and compression. See the discussion below surrounding SSL/TLS Client for more details. The client does need to set the server's hostname, but that's done on the SSL* using SSL_set_tlsext_host_name, and not the SSL_CTX*. Or, if you are using BIO's, it would look like this. Notice the BIO effectively wraps a SSL*, so you're not modifying the SSL_CTX*: BIO* web = BIO_new_ssl_connect(ctx); if(web == NULL) handleFailure(); res = BIO_set_conn_hostname(web, HOST_NAME ":" HOST_PORT); if(res != 1) handleFailure(); ... one invoked with server methods and the other with client methods Not needed. The only difference between them (like SSLv23_client_method and SSLv23_server_method), is a couple of function pointers for functions like connect and accept in unseen structures. Clients call connect and servers call accept. Instead, just use the generic SSLv23_method and everything will be fine. You still have to tune the context with SSL_CTX_set_options because the default context provided by SSL_CTX_new includes weak/wounded/broken protocols and ciphers. OpenSSL's wiki page SSL/TLS Client shows you how to tune a SSL_CTX object. It performs the following, and its can be used by both clients and servers: Disable SSLv2 Disable SSLv3 Disable Compression Disable anonymous protocols Use "strong" ciphers Using a custom cipher list like "HIGH: ... : !SRP:!PSK" removes many weak/wounded ciphers, and removes a bunch of cipher suites that are probably not supported at the server (so there's no reason for the client to advertise them). SRP is Thomas Wu's Secure Remote Password, and PSK is Preshared Key. IANA reserves 87 cipher suites based on them, so it saves nearly 180 bytes in the ClientHello. Is such dual-use of OpenSSL within a single process supported? Yes. My hope is that OpenSSL uses the SSL_CTX handle - and does not rely on global or static local variables Well, you're out of luck there. There are a lot of globals, some of them are dynamically allocated, and some of them are not freed. And if you're working in Java or C#, they are leaked each time the shared object is loaded/unloaded. So your Java or C# program accumulates more and more memory over time. The OpenSSL devs don't feel its worthy of their time. See, for example, Small memory leak on multithreaded server on the OpenSSL mailing list. A: From my experience: you can freely create several contexts as long as you properly initialized OpenSSL library. I have used two different contexts in the same application with no problems after having set up threading locks as described in OpenSSL man page: http://www.openssl.org/docs/crypto/threads.html. If your app doesn't use threads you won't need such setup at all.
[ "stackoverflow", "0023881049.txt" ]
Q: Calculate Running Total for Non Trading Day to handle weekend and holidays I have odd requirement of calculating multiplier for non trading day. So say for Example: If Holiday is on Wednesday then next day (Thursday) will have multiply factor of 2 (for Wed + Thursday) If Holiday is on Monday then Tuesday should have multiply factor of 4 (i.e Saturday + Sunday + Monday + Tuesday) For normal weekend, Monday should have multiple factor of 3 (i.e Sat +Sun + Mon) and for normal weekdays, multiply factor is 1 And to resolve this issue, I have created standard Date dimension, with Holiday flag (which will be 1 for weekend and public holiday) and created column named MULTIPLIER which should have value of For normal weekdays - should have multiplier value of 1 and if Holiday is on Wednesday (28th May) then on Thursday (29th May), multiplier factor will be 2 (i.e sum of IsHoliday column count for Wed + 1 for current day (i.e 1 + 1) and if holiday is on Monday (2nd June) then on 3rd June it will be Sum of IsHoliday flag (i.e 1 for Sat + 1 for Sun + 1 for Mon and summing this 3 holiday flag it will be 3 + 1 for current day so it will be 4) It would be really great, if someone can help me to resolve this mystery Note: I am using SQL Server 2012 A: CREATE Table DateTable ( [date] datetime NOT NULL ,IsHoliday int NOT NULL ); INSERT INTO DateTable VALUES ('20140101', 1) -- Just example, not real holidays ,('20140102', 0) ,('20140103', 0) ,('20140104', 0) ,('20140105', 1) ,('20140106', 1) ,('20140107', 1) ,('20140108', 0); WITH HolidayGaps AS ( SELECT [Date] ,DaysFromStart ,DaysFromStart - ROW_NUMBER() OVER (ORDER BY Date) AS Gap FROM DateTable CROSS APPLY ( SELECT DATEDIFF(day, '20140101', [Date]) AS DaysFromStart ) AS CA1 WHERE IsHoliday = 1 ) ,DayAfterHoliday AS ( SELECT DATEADD(day, 1, MAX([date])) AS [date] ,COUNT(1) AS Multiplier FROM HolidayGaps GROUP BY Gap ) SELECT * FROM DayAfterHoliday Your update statement would look something like UPDATE DateTable SET Multiplier = CASE WHEN DateTable.IsHoliday = 1 THEN 0 ELSE COALESCE(DayAfterHoliday.Multiplier, 1) END FROM DateTable LEFT JOIN DayAfterHoliday ON DayAfterHoliday.Date = DateTable.Date
[ "math.stackexchange", "0003531250.txt" ]
Q: Hecke's notation for fractional ideals I'm confused about some of the notation appearing in Hecke's Lectures on the Theory of Algebraic Numbers, in Section 54 of Chapter 7. Let $\mathfrak{d}$ be the different of $K$ (the inverse ideal to the dual lattice of $\mathcal{O}_{K}$); then for each $\omega \in K$ we may write $\mathfrak{d}\omega=\frac{\mathfrak{b}}{\mathfrak{a}}$ where $\mathfrak{a}$ and $\mathfrak{b}$ are integral ideals and $(\mathfrak{a},\mathfrak{b})=1$. Suppose $\mathfrak{a}=\mathfrak{a}_{1}\mathfrak{a}_{2}$, where $(\mathfrak{a}_1,\mathfrak{a}_{2})=1$. Then Hecke says that we may find auxiliary ideals $\mathfrak{c}_1$ and $\mathfrak{c_2}$ such that $\mathfrak{a}_{1}\mathfrak{c}_{1}=\alpha_{1}$ and $\mathfrak{a}_{2}\mathfrak{c}_{2}=\alpha_{2}$ are integers and $(\mathfrak{a},\mathfrak{c}_1 \mathfrak{c}_2)=1$. $\textbf{Question 1}$: The text states that $\alpha_1$ and $\alpha_2$ are elements of $\mathcal{O}_K$, so the equations involving $\alpha_1$ and $\alpha_2$ are shorthand for equalities of integral ideals: $\mathfrak{a}_{1}\mathfrak{c}_{1}=(\alpha_{1})$. How do we know that such a $\mathfrak{c}_1$ exists? $\textbf{Question 2}$: Shortly afterwards, Hecke says that $\beta:=\frac{\mathfrak{b}\mathfrak{c}_1 \mathfrak{c}_2}{\mathfrak{d}}$ is an element of $k$. Why is this true? Thanks. A: For your question 1 Given a non-zero ideal $I$, for non-zero $b\in I$ then $(b)=IJ$, and there is such a $b\in I$ such that $(I,J)=(1)$ Proof : one of the properties of Dedekind domains is that $I$ becomes principal $=(b\bmod I^2)$ in $R/I^2$, then $(b,I^2)=I$ and $(b)=IJ$ means $I=(IJ,I^2)=I(I,J)$ thus $(I,J)=(1)$. With $b_1\in \mathfrak{a}_1 (N(\mathfrak{a}))$ then $\mathfrak{c}_1=(b_1) (\mathfrak{a}_1 (N(\mathfrak{a})))^{-1}$ is coprime with $\mathfrak{a}_1 (N(\mathfrak{a}))$ thus with $\mathfrak{a}$, With $b_2\in \mathfrak{a}_2 (N(\mathfrak{a}))$ then $\mathfrak{c}_2=(b_2) (\mathfrak{a}_2 (N(\mathfrak{a})))^{-1}$ is coprime with $\mathfrak{a}_2 (N(\mathfrak{a}))$ thus with $\mathfrak{a}$, and hence $$( \mathfrak{a},\mathfrak{c}_1\mathfrak{c}_2)=(1),\qquad \mathfrak{a}_j\mathfrak{c}_j= (b_j/N(\mathfrak{a}))$$ For your question 2 it is because $\mathfrak{b}\mathfrak{c}_1\mathfrak{c}_2$ has the same ideal class as $\mathfrak{b}\mathfrak{a}^{-1}$
[ "stackoverflow", "0051863326.txt" ]
Q: NTFS Change Journal - File Change Tracking I'm developing a change tracking software to monitor files of a specific volume. I tried FileSystemWatcher (.NET) and AlternateDataStreams but they all have some limitations (ie. the change tracking software has to be on 24/7, alternate data streams to not work for ReadOnly files, etc.). After some investigations I thought that I could directly read the NTFS change journal. This works great if the file is moved/renamed, etc. on the same volume. For identifying the file I'm using the File Reference Number. But if the file is moved to another volume, the File Reference Number naturally changes. My question: Is there a unique ID (GUID or something else) that doesn't change even if the file is moved to another volume? A: Well...there can be a file GUID, but it's not there by default. If you have the necessary permissions, you can race through the files and assign a GUID which will be preserved across NTFS volume moves. Your stated goal is exactly why the feature exists. It uses a somewhat unwieldy API called DeviceIOControl...which is used for a gazillion purposes...but one of it's control codes is FSCTL_CREATE_OR_GET_OBJECT_ID. Check here for details. It only creates the GUID if one hasn't already been assigned...which is just how you want it to work. Of course, if the file moves to a non-NTFS volume, you're still outta luck.
[ "stackoverflow", "0053213437.txt" ]
Q: Extracting Data from HTML Span using Beautiful Soup I want to extract"1.02 Crores" and "7864" from html code and save them in different column in csv file. Code: <div class="featuresvap _graybox clearfix"><h3><span><i class="icon-inr"></i>1.02 Crores</span><small> @ <i class="icon-inr"></i><b>7864/sq.ft</b> as per carpet area</small></h3> A: Not sure about the actual data but this is just something that I threw together really quick. If you need it to navigate to a website then use import requests. you'' need to add url = 'yourwebpagehere' page = requests.get(url) and change soup to soup = BeautifulSoup(page.text, 'lxml') then remove the html variable since it would be unneeded. from bs4 import BeautifulSoup import csv html = '<div class="featuresvap _graybox clearfix"><h3><span><i class="icon-inr"></i>1.02 Crores</span><small> @ <i class="icon-inr"></i><b>7864/sq.ft</b> as per carpet area</small></h3>' soup = BeautifulSoup(html, 'lxml') findSpan = soup.find('span') findB = soup.find('b') print([findSpan.text, findB.text.replace('/sq.ft', '')]) with open('NAMEYOURFILE.csv', 'w+') as writer: csv_writer = csv.writer(writer) csv_writer.writerow(["First Column Name", "Second Column Name"]) csv_writer.writerow([findSpan, findB])
[ "ethereum.stackexchange", "0000074698.txt" ]
Q: Error While Compiling In Remix During Tutorial During a tutorial on my first compile I received this error: :1:1: Parser error: Expected import directive or contract definition. pragma solidity ^0.5.12; ^ What's that about? How do I fix it? I'm an absolute beginner with ready to make his first dapp with illustrated assets and marketing ready to go. Mentors and partners welcome. A: You need to choose the right compiler version. On the right sidebar you can see your current compiler version. The compiler version must match the number used in the pragma solidity! Expand the dropdown and choose 0.5.12 nightly. You should probably downgrade to a full commit version like 0.5.11 commit. I hope this helps!
[ "datascience.stackexchange", "0000001165.txt" ]
Q: Looking for a strong Phd Topic in Predictive Analytics in the context of Big Data I'm going to start a Computer Science phd this year and for that I need a research topic. I am interested in Predictive Analytics in the context of Big Data. I am interested by the area of Education (MOOCs, Online courses...). In that field, what are the unexplored areas that can help me choose a strong topic? Thanks. A: As a fellow CS Ph.D. defending my dissertation in a Big Data-esque topic this year (I started in 2012), the best piece of material I can give you is in a link. This is an article written by two Ph.D.s from MIT who have talked about Big Data and MOOCs. Probably, you will find this a good starting point. BTW, along this note, if you really want to come up with a valid topic (that a committee and your adviser will let you propose, research and defend) you need to read LOTS and LOTS of papers. The majority of Ph.D. students make the fatal error of thinking that some 'idea' they have is new, when it's not and has already been done. You'll have to do something truly original to earn your Ph.D. Rather than actually focus on forming an idea right now, you should do a good literature survey and the ideas will 'suggest themselves'. Good luck! It's an exciting time for you.
[ "stats.stackexchange", "0000057307.txt" ]
Q: How to derive a confidence interval from an F distribution? So, this is the question I'm working on: Suppose we observe a random sample of five measurements: 10, 13, 15, 15, 17, from a normal distribution with unknown mean $µ_1$ and unknown variance $σ_1^2$. A second random sample from another normal population with unknown mean $µ_2$ and unknown variance $σ_2^2$ yields the measurements: 13, 7, 9, 15, 11. b. Use the pivotal method (and a pivotal statistic with F distribution) to derive a 95% confidence interval for $σ_2/σ_1$. Work it out for these data. And test the null hypothesis that $σ_2 = σ_1$ at the 5% level of significance. [6] (recall that $F_{\nu_1,\nu_2,a} = 1/F_{\nu_2,\nu_1,1-a}$). So, I'm completely at a loss as to how I can use the pivotal method on the F distribution. Please help me. A: You're working the question from the wrong end. Forget the F; it doesn't come into it yet. First find a nice pivotal quantity, then worry about its distribution. Check the actual definition of a pivotal quantity here (read as far as the '[1]'). (What important piece of information did you leave out of the definition?) Now, just think about trying to estimate $\sigma_1/\sigma_2$. How might you estimate it? Would the distribution of that estimate depend on $\sigma_1/\sigma_2$? Does the estimator contain $\sigma_1$ or $\sigma_2$? How might you fix both issues at the same time to turn it into a pivot? That is, what do you do to the estimator in order to make it also a function of $\sigma_1$ and $\sigma_2$, while its distribution no longer depends on them? If you get that far, you'll get a pivot, but it won't necessarily have an F-distribution. [If that happens, the only thing left then is to understand the relationship between what you have and something that does have an F distribution.]
[ "tex.stackexchange", "0000351420.txt" ]
Q: How to write a convolution and a Fourier transform I want to write the following equation in LaTeX: \begin{equation} x(t) \ast h(t) = y(t) X(f) H(f) = Y(f) \end{equation} I want \ast to denote the convolution. I know there is also the \star command. Does it matter which one I use to represent convolution? Then I want a Fourier-transform symbol, I mean the line with a coloured and an empty circle on either side, to connect the x(t) and X(f), h(t) and H(f), y(t) and Y(f) respectively. Is there a way of doing this ? A: The \circledast symbol from amssymb package is usually used to denote the circular convolution process. \documentclass{article} \usepackage{amsmath} \usepackage{amssymb} \begin{document} \begin{align*} x(t) \circledast h(t) &= y(t) \\ X(f) H(f) &= Y(f) \end{align*} \end{document} For linear convolution, a simple * is more appropriate: \begin{align*} x(t)*h(t) &= y(t) \\ X(f) H(f) &= Y(f) \end{align*} To draw connections between parts of the equations, TikZ package can be used with its tikzmark library to mark locations to begin and end your lines. \documentclass{article} \usepackage{amsmath,amssymb,tikz} \usetikzlibrary{arrows.meta,tikzmark} \begin{document} \begin{align*} x\tikzmark{x}(t)*h\tikzmark{h}(t) &= y\tikzmark{y}(t) \\[2em] X(f) \, H(f) &= Y(f) \end{align*} \begin{tikzpicture}[overlay,remember picture, > = {Circle[open,blue]}] \draw [<->] ([yshift=-.7ex]pic cs:x) -- ++(0,-2.2em); \draw [<->] ([yshift=-.7ex]pic cs:h) -- ++(0,-2.2em); \draw [<->] ([yshift=-.7ex]pic cs:y) -- ++(0,-2.2em); \end{tikzpicture} \end{document}
[ "stackoverflow", "0042098489.txt" ]
Q: How to convert a Seq[User] so that I can pass it into A* param? I have a sequence of Users in a collection val users: Seq[User] And I want to pass it into the Queue.enqueue method that takes: def enqueue(elems : A*) I can foreach on my collection but I am sure there is a way to convert it right? Also, what is A* called again? A: A* is a varargs type. To pass a collection to such a function, you can use the special vararg-expansion syntax, like this: queue.enqueue(seq: _*) // If queue is of type Queue[User]. You can use this notation only if your collection is a Seq, or if it can be implicitly converted to a Seq.
[ "stackoverflow", "0007152714.txt" ]
Q: including enums from a c++ header file into cython What is the difference between these two pieces of cython code? cdef extern from "some_header.h": enum _some_enum: ... ctypedef _some_enum some_enum and: cdef extern enum _some_enum: ... ctypedef _some_enum some_enum Since you have to redefine the enum in the .pyd file, does it matter if you say anything about the header file? Can I include it from the header file instead of retyping it? A: It shouldn't be a problem to let Cython generate enum declarations. However, you typically want to use the header to ensure that the declarations are consistent. Cython will #include the header instead of including its own declarations. That said, it doesn't actually use the declarations in the header to generate code. You still have to write compatible declarations. You can find more information in the user guide: Interfacing with External C Code: Referencing C header files.
[ "stackoverflow", "0034655243.txt" ]
Q: InAppBrowser.open with "_system" param is opening links inside webview (only in iOS) I've been fighting against this weird problem in a Cordova app (iOS and Android) since yesterday, so I think is time to ask for a little help. I have the following code running on "deviceready" event: document.addEventListener('deviceready', function() { delete window.open; $(document).on('mousedown','a', function(e) { e.preventDefault(); if (this.hostname !== window.location.hostname) { const url = $(this).attr('href'); cordova.InAppBrowser.open(url, '_system', 'location=yes'); } }); }, false); This is working perfectly for Android. In iOS it opens the link in the system browser and when I come back to my app it is also opened there. A: Just found the solution. The problem apparently was using the "mousedown" event, switching over to "click" did the job. I also had to move the e.preventDefault call to the if block, otherwise internal links won't work. document.addEventListener('deviceready', function() { delete window.open; $(document).on('click','a', function(e) { if (this.hostname !== window.location.hostname) { e.preventDefault(); const url = $(this).attr('href'); cordova.InAppBrowser.open(url, '_system', 'location=yes'); } }); }, false);
[ "stackoverflow", "0036618601.txt" ]
Q: Confidence value of each Bounding Box I am currently working on Image classification given an image with neural network. I have successfully created the bounding boxes over the image and for each bounding box I have applied classification algorithm(W^X+B where W, B are weights and biases already learned from training data) to get a value for each of 20 classes. For one bounding box the value I got for 20 classes : 221.140961 71.6502609 185.005554 14.2860174 177.44928 -20.842535 -16.2324142 -105.940437 -397.505829 132.100311 -12.3567591 262.162872 -243.444672 -198.083984 19.3514423 1.94239163 -75.0622787 -93.7277069 -181.89653 260.002625 the class predicted is class 11 (index of class starting from 0) which has max value 262.162872. I have also come across some papers where I could find the confidence value for each bounding box is usually calculated and its value ranges from 0 to 1. How to get this confidence value for each bounding box ? Is it just the probability of class 11 with respect to all other classes? In this data how do I get it ? A: To convert the output of a neural network to probabilities, softmax is usually used: https://en.wikipedia.org/wiki/Softmax_function This ensures that very small values become near-zero probabilities and very large values become near-one probabilities. The ends of the range are relatively insensitive to how large the value is, the middle of the range is much more sensitive. It also ensures all the probabilities add up to 1. This is appropriate to multiclass classification (where the classes are disjoint). Note that an activation function (such as ReLU) is usually not applied before softmax. So a typical network is convolution -> ReLU -> ... -> convolution -> ReLU -> convolution -> softmax. P.S. Does your neural network really have one layer as you described? This doesn't usually produce good results.
[ "stackoverflow", "0017909081.txt" ]
Q: Access elements from R's Rd file? I wish to go through a package and discover who are the authors mentioned for each function's help file. I looked for a function to extract elements from R's help file, and could find one. The closest I could find is this post, from Noam Ross. Does such a function exist? (if not, I guess I'll hack Noam's code in order to parse the Rd file, and locate the specific element I'm interested in). Thanks, Tal. Potential code example: get_field_from_r_help(topic="lm", field = "Description") # # output: ‘lm’ is used to fit linear models. It can be used to carry out regression, single stratum analysis of variance and analysis of covariance (although ‘aov’ may provide a more convenient interface for these). A: This document by Duncan Murdoch on parsing Rd files will be helpful, as will this SO post. From these, you could probably try something like the following: getauthors <- function(package){ db <- tools::Rd_db(package) authors <- lapply(db,function(x) { tags <- tools:::RdTags(x) if("\\author" %in% tags){ # return a crazy list of results #out <- x[which(tmp=="\\author")] # return something a little cleaner out <- paste(unlist(x[which(tags=="\\author")]),collapse="") } else out <- NULL invisible(out) }) gsub("\n","",unlist(authors)) # further cleanup } We can then run this on a package or two: > getauthors("knitr") d:/RCompile/CRANpkg/local/3.0/knitr/man/eclipse_theme.Rd " Ramnath Vaidyanathan" d:/RCompile/CRANpkg/local/3.0/knitr/man/image_uri.Rd " Wush Wu and Yihui Xie" d:/RCompile/CRANpkg/local/3.0/knitr/man/imgur_upload.Rd " Yihui Xie, adapted from the imguR package by Aaron Statham" d:/RCompile/CRANpkg/local/3.0/knitr/man/knit2pdf.Rd " Ramnath Vaidyanathan, Alex Zvoleff and Yihui Xie" d:/RCompile/CRANpkg/local/3.0/knitr/man/knit2wp.Rd " William K. Morris and Yihui Xie" d:/RCompile/CRANpkg/local/3.0/knitr/man/knit_theme.Rd " Ramnath Vaidyanathan and Yihui Xie" d:/RCompile/CRANpkg/local/3.0/knitr/man/knitr-package.Rd " Yihui Xie <http://yihui.name>" d:/RCompile/CRANpkg/local/3.0/knitr/man/read_chunk.Rd " Yihui Xie; the idea of the second approach came from Peter Ruckdeschel (author of the SweaveListingUtils package)" d:/RCompile/CRANpkg/local/3.0/knitr/man/read_rforge.Rd " Yihui Xie and Peter Ruckdeschel" d:/RCompile/CRANpkg/local/3.0/knitr/man/rst2pdf.Rd " Alex Zvoleff and Yihui Xie" d:/RCompile/CRANpkg/local/3.0/knitr/man/spin.Rd " Yihui Xie, with the original idea from Richard FitzJohn (who named it as sowsear() which meant to make a silk purse out of a sow's ear)" And maybe tools: > getauthors("tools") D:/murdoch/recent/R64-3.0/src/library/tools/man/bibstyle.Rd " Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/checkPoFiles.Rd " Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/checkRd.Rd " Duncan Murdoch, Brian Ripley" D:/murdoch/recent/R64-3.0/src/library/tools/man/getDepList.Rd " Jeff Gentry " D:/murdoch/recent/R64-3.0/src/library/tools/man/HTMLlinks.Rd "Duncan Murdoch, Brian Ripley" D:/murdoch/recent/R64-3.0/src/library/tools/man/installFoundDepends.Rd "Jeff Gentry" D:/murdoch/recent/R64-3.0/src/library/tools/man/makeLazyLoading.Rd "Luke Tierney and Brian Ripley" D:/murdoch/recent/R64-3.0/src/library/tools/man/parse_Rd.Rd " Duncan Murdoch " D:/murdoch/recent/R64-3.0/src/library/tools/man/parseLatex.Rd "Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/Rd2HTML.Rd " Duncan Murdoch, Brian Ripley" D:/murdoch/recent/R64-3.0/src/library/tools/man/Rd2txt_options.Rd "Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/RdTextFilter.Rd " Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/SweaveTeXFilter.Rd "Duncan Murdoch" D:/murdoch/recent/R64-3.0/src/library/tools/man/texi2dvi.Rd " Originally Achim Zeileis but largely rewritten by R-core." D:/murdoch/recent/R64-3.0/src/library/tools/man/tools-package.Rd " Kurt Hornik and Friedrich Leisch Maintainer: R Core Team [email protected]" D:/murdoch/recent/R64-3.0/src/library/tools/man/vignetteDepends.Rd " Jeff Gentry " D:/murdoch/recent/R64-3.0/src/library/tools/man/vignetteEngine.Rd "Duncan Murdoch and Henrik Bengtsson." D:/murdoch/recent/R64-3.0/src/library/tools/man/writePACKAGES.Rd " Uwe Ligges and R-core." Some functions have no author field, so this just drops those when it calls unlist at the end of getauthors, but the code could be modified slightly to return NULL values for those. Also, further parsing is going to become a little bit difficult because package authors seem to use this field in very different ways. There's only one author field in devtools. There are a bunch in car, each of which contains an email address. Etc, etc. But this gets you to the available info, which you should be able to work with further. Note: My previous version of this answer provided a solution if you have the full path of an Rd file, but didn't work if you were trying to do this for an installed package. Following Tyler's advice, I've worked out a more complete solution.
[ "stackoverflow", "0044550776.txt" ]
Q: loading jquery dependent library in react I used bootstrap-datepicker in the past which has an option to have a month calendar stay static (inline) as shown here. I am now using React (and am pretty new at it), and need a date-picker again. I decided to use react-bootstrap-date-picker however react-bootstrap-datepicker does not have an inline option. I don't want to heavily hack into the css for react-bootstrap-datepicker, what is the best way to load a jQuery dependent library such as bootstrap-datepicker on react? Would this be bad practice? Here is the JS(jQuery)/HTML code for loading the bootstrap-datepicker module. <div id="datepicker" data-date="12/03/2012"></div> <input type="hidden" id="my_hidden_input"> $('#datepicker').datepicker(); $('#datepicker').on('changeDate', function() { $('#my_hidden_input').val( $('#datepicker').datepicker('getFormattedDate') ); }); UPDATE: So while this did workout in terms of rendering the bootstrap calendar, I am not able to get the event to fire when #my_hidden_input's value has been updated. I added an onChange event to detect the value change for the div in the render() function. <div id="datepicker"></div> <div id="#my_hidden_input" onChange={this.handleDate}> </div> where the handleDate() function simply fires off a console.log(1); A: The "React" way of initializing a jQuery plugin would be to do it in the componentDidMount lifecycle method. componentDidMount(){ $('#datepicker').datepicker(); $('#datepicker').on('changeDate', function() { $('#my_hidden_input').val( $('#datepicker').datepicker('getFormattedDate') ); }); } Update: Adding what @klaasman said concerning destroying or unmounting plugins. Use the componentWillUnmount lifecycle method: componentWillUnmount(){ $('#datepicker').destroy(); } Update 2: The onChange event isn't firing because you you didn't set the event to call the handleDate function. Here, you set the change event to an anonymous function: $('#datepicker').on('changeDate', function() { $('#my_hidden_input').val( $('#datepicker').datepicker('getFormattedDate') ); }); Instead, you need to supply your handleDate function like so: $('#datepicker').on('changeDate', this.handleDate);
[ "stackoverflow", "0037709064.txt" ]
Q: In Intellij IDEA how to compare 2 text files that are not part of an open project I would like to compare 2 files in intellij. Both files are not part of a specific project. Is there a way to do so? I am running Intellij 15 and 16. A: The following works for me in IntelliJ IDEA Ultimate 14.1.7 on Windows: Open the first file in the IDE (either by dragging from Windows Explorer into the window, or by File / Open). In the view menu, choose "Compare With…" In the "Select Path" dialog that appears, select the second file (either directly, or by dragging from Windows Explorer into the dialog). It then opens up in the traditional file comparison pane. If you try to edit one of the files, it presents the usual "Are you sure you want to edit a file that's not in your project" dialog, which one can accept if that's what one is trying to do. A: You can use the "compare with clipboard" feature. From https://www.jetbrains.com/help/idea/2016.1/comparing-files.html#clipboard: Comparing a File in the Editor with the Clipboard Contents Open the desired file in the editor. Right-click the editor pane and choose Compare with Clipboard on the context menu. View and manage differences in the Differences Viewer for Files.
[ "stackoverflow", "0059585650.txt" ]
Q: Update Cognito User Pool/AWS Resources I am using serverless framework to deploy AWS resources (User Pool, Identity Pool, Dynamo Tables). I know you're not allowed to make changes to a User Pool once it is already created (and similarly Dynamo indexes). I was wondering what the best practice is to update these types of resources without deleting users/data? Thankfully serverless caught the problem upon deploying Updates are not allowed for property - UserPoolName But I have heard of people dropping users by accidentally updating User Pools. Any suggestions? A: Have a look at this well documented AWS Blog on how to change attributes of Amazon Cognito user pool after creation: https://aws.amazon.com/premiumsupport/knowledge-center/cognito-change-user-pool-attributes/ In Summary: You have to re-create a new user pool with new attributes that you want, and then use a lambda function to migrate users. Sadly, this seems to be the only way.
[ "stackoverflow", "0015361521.txt" ]
Q: How do I exclude a property of all items in IEnumerable when using ShouldBeEquivalentTo? In my NUnit/FluentAssertions tests I compare the complex object returned from my system with a reference one using the following code: response.ShouldBeEquivalentTo(reference, o => o.Excluding(x => x.OrderStatus) .Excluding(x => x.Id) .Excluding(x => x.Items[0].Name) .Excluding(x => x.Items[0].Article) .Excluding(x => x.ResponseStatus)); However, this is not exactly what I intended. I'd like to exclude Name and Article for every object in Items list and not only for the 0th. How do I implement this scenario? I've looked through the documentation and din't find the solution. Am I missing something? A: There's an overload of Excluding() that provides an ISubjectInfo that you can use for more advanced selection criteria. With that overload, you can do stuff like: subject.ShouldBeEquivalentTo(expected, config => config.Excluding(ctx => ctx.PropertyPath == "Level.Level.Text"));
[ "serverfault", "0000391244.txt" ]
Q: How can I download the Amazon Linux AMI I'd like to build upon the Amazon Linux AMI. How can I download one of their AMI images using ec2-download-bundle? I tried ec2-download-bundle -b amzn-ami-us-east-1/amzn-ami-pv-2012.03.1.x86_64.manifest.xml <auth> But I don't think that is correct. A: instance-store AMIs can only be downloaded if you own them. Even if the owner makes the bundle files world readable where they are stored in S3, they are encrypted in such a way that they can only be decrypted by the owner and by Amazon (so that Amazon can run it on an instance for you). EBS boot AMIs are stored on EBS snapshots and you can only create a volume directly from the snapshot if the snapshot is public. However, in most cases you can start a new instance of a public EBS boot AMI and instantly stop it before it does much bootup. You could then detach that EBS volume from the instance, attach it to another instance and view it in almost as pristine a condition as the original AMI snapshot itself. For most public AMIs (instance-store and EBS) you can simply log in after the instance boots and look at what is on the root disk. This is the simplest way to see what is in the AMI, though the boot up process could theoretically wipe files and hide processes from you if it were malicious (obviously not necessary in the Amazon Linux AMIs). AMIs used in the AWS Marketplace have more protection in place to prevent access if the AMI provider wants to protect them, but many AWS Marketplace AMIs (including mine) let you log in to view the file system once booted.
[ "stackoverflow", "0037146402.txt" ]
Q: Remove and untrack files from repo but keep them on remote server I've done some searching but either I don't understand exactly how this works or I'm not finding what I need. I have a production server and I have my local development box. There is a directory that has been tracked by the git repo until now, which I no longer want to track. I also want to remove those files from the repo as they will not be tracked and simply make the git repo larger than it needs to be. However, my understading is that if I to a git rm --cached locally and change my .gitignore file, it will delete the files on the remote server when I pull down the updated repo, which I do not want. I want the files to remain on production, just not tracked any more and not in the repo. I would think someone has had to do this before and I'm probably missing something obvious. I hope that makes sense. Thanks! A: You understand it correctly. You can, however, make copies of these files on the production server, pull the local repo (which will erase the originals), and then restore the files from the copy. After that these files will not be tracked, so no (usual) git operations, including any further pulls, are going to overwrite or remove them. edit: Actually the author of the question proposed a much nicer solution, that is using git rm --cached on the production server, which will remove the files from index (allowing them to be removed from the repository in the next commit), but preserving them in the working tree.
[ "stackoverflow", "0005934634.txt" ]
Q: Best way to modify PDFs using iText? Scenario: Clients will be providing me with PDF-templates. I need to programmatically fill these with information. Question: What is the best way to do this? Say for example a client sends me the beautiful template seen below and I want to fill in the Price Field. The research I've done so far has led me to believe that there is no way for me to programmatically 'understand' where the Price Field is, is this correct? A workaround I've heard of is creating another template on top of the existing template. I want to make this as hassle-free as possible, is there a program that let's me create a template easily using say drag-and drop forms, with another template as a base? Then perhaps I could load the clients template, then my own created template, populate that with values and merge it all into one PDF. Is this a sensible approach? Very thankful for any thoughts or suggestions. A: This worked for me.
[ "stackoverflow", "0052806889.txt" ]
Q: plotting pandas core series.series/values not showing I am trying to plot the availability of my network per hour. So,I have a massive dataframe containing multiple variables including the availability and hour. I can clearly visualise everything I want on my plot I want to plot when I do the following: mond_data= mond_data.groupby('Hour')['Availability'].mean() The only problem is, if I bracket the whole code and plot it (I mean this (the code above).plot); I do not get any value on my x-axis that says 'Hour'.How can plot this showing the values of my x-axis (Hour). I should have 24 values as the code above bring an aaverage for the whole day for midnight to 11pm. A: Here is how I solved it. plt.plot(mon_data.index,mond_data.groupby('Hour')['Availability'].mean()) for some reason python was not plotting the index, only if called. I have not tested many cases. So additional explanation to this problem is still welcome.
[ "stackoverflow", "0027469581.txt" ]
Q: Why AsyncHTTPClient in Tornado doesn't send request immediately? In my current application I use Tornado AsyncHttpClient to make requests to a web site. The flow is complex, procesing responses from previous request results in another request. Actually, I download an article, then analyze it and download images mention in it What bothers me is that while in my log I clearly see the message indicating that .fetch() on photo URL has beeen issued, no actual HTTP request is made, as sniffed in Wireshark I tried tinkering with max_client_count and Curl/Simple HTTP client, but the bahvior is always the same - until all articles are downloaded not photo requests are actually issued. How can change this? upd. some pseudo code @VictorSergienko I am on Linux, so by default, I guess, EPoll version is used. The whole system is too complicated but it boils down to: @gen.coroutine def fetch_and_process(self, url, callback): body = yield self.async_client.fetch(url) res = yield callback(body) return res @gen.coroutine def process_articles(self,urls): wait_ids=[] for url in urls: #Enqueue but don't wait for one IOLoop.current().add_callback(self.fetch_and_process(url, self.process_article)) wait_ids.append(yield gen.Callback(key=url)) #wait for all tasks to finish yield wait_ids @gen.coroutine def process_article(self,body): photo_url=self.extract_photo_url_from_page(body) do_some_stuff() print('I gonna download that photo '+photo_url) yield self.download_photo(photo_url) @gen.coroutine def download_photo(self, photo_url): body = yield self.async_client.fetch(photo_url) with open(self.construct_filename(photo_url)) as f: f.write(body) And when it prints I gonna download that photo no actual request is made! Instead, it keeps on downloading more articles and enqueueing more photos untils all articles are downloaded, only THEN all photos are requested in a bulk A: AsyncHTTPClient has a queue, which you are filling up immediately in process_articles ("Enqueue but don't wait for one"). By the time the first article is processed its photos will go at the end of the queue after all the other articles. If you used yield self.fetch_and_process instead of add_callback in process_articles, you would alternate between articles and their photos, but you could only be downloading one thing at a time. To maintain a balance between articles and photos while still downloading more than one thing at a time, consider using the toro package for synchronization primitives. The example in http://toro.readthedocs.org/en/stable/examples/web_spider_example.html is similar to your use case.
[ "stackoverflow", "0053562415.txt" ]
Q: Update a numpy array except i-th entry I am trying to implement SGD algorithm, where there is a update formula This could be easily done by using temp = beta_old[i] beta = beta_old beta[i] = temp But I find this ugly and I am wondering if there is any more elegant way to do this (maybe by using some indexing tricks). A: You may want to use a mask: mask = np.ones(size, dtype=np.bool) mask[i] = false Then use the mask later: beta[mask] = beta_old[mask] But it may be slower than your current method.
[ "genealogy.stackexchange", "0000002077.txt" ]
Q: What kind of information is in this record? I am looking at civil records (BMD) from the late 18th-early 19th century from Morschheim the Pfalz region of (then) Bavaria, and I see several instances of images like this (top part shown): It appears that this is a list of names of some sort,but I cannot figure it out. There are several more numbered sections of groups of what appear to be names. Can someone tell me what sort of list this is? A: According to the film description at FamilySearch, these are "Eheverkündigungen, Heiratsbelege 1808-1816" (marriage proclamations, supporting documents for marriage). The image, with a 1811 date, starts with a general statement (no names) and includes a list of documents which contain the names of the parties for 2 marriages: birth certificate of Johannes Laus? death certificate of his father (not named) birth certificate of bride Anna Elisabeth Zimt? death certificate of bride's father (not named) death certificate of bride's mother (not named) marriage contract (numbering starts again) birth certificate of Johannes Ludwig Schafer death certificate of his father (not named) death certificate of his mother (not named) birth certificate of bride Anna Barbara Jung death certficate of bride's mother (not named) If a transcription of the German text is wanted, let me know.
[ "japanese.stackexchange", "0000060814.txt" ]
Q: Relative clause with both direct object and head noun as object From here: 国土交通省によると、3つの会社は走るのに必要なガソリンの量や外に出るガスの量を調べる検査を国が決めたルールと違うやり方で行っていました。そして、ルールどおりに検査したと記録していました。 According to the land ministry, three companies were operating in a way different to the rules that the nation had decided upon. The nation had chosen inspections which investigate amount of gases that are emitted and the amount of fuel that is needed for running. They also recorded that they had made inspections in accordance with the rules. This is my best effort at translation but I think something is not quite right. The part in bold is bothering me. It looks like 決める has two objects i.e. ルール and 検査. I parse 国が決めたルール as "the rules chosen by the nation". But also 検査を国が決めた as "The nation has chosen an examination". I can't join these together to make anything meaningful, hence why I wrote two separate sentences. Am I parsing this wrongly? A: 検査 is the object of 行っていました. A simplified version of this sentence is: 3つの会社は検査を行って【おこなって】いました。 The three companies were conducting examinations. 行っていました is modified by a long adverbial expression 国が決めたルールと違うやり方で ("in a way that is different from rules set by the government").
[ "sharepoint.stackexchange", "0000212878.txt" ]
Q: Column Validation Preventing Me From Copying/Updating List Items (PowerShell) There is a date list column I'm having trouble updating since there is a validation formula linked to it. =(TEXT([Week Ending],"dddd")="Saturday") The date that gets inputted for the Week Ending column must be on a Saturday. What I'm trying to do is copy some items from that same list based on a query, and certain columns (not all) will be updated with new values. The query works fine (returning the expected number of items) and I have the new date value in a format that SharePoint list accepts (MM/dd/yyyy) if I was using the SharePoint UI to update/add it. The thing is in PowerShell, it throws a "List data validation error" even though it's in the same date format used to add an item to the list manually. I really think the error has something to do with the validation formula above. Since it's using dddd and not dd like in the format used by the PowerShell. And the date I'm using to update items does fall on a Saturday, so it makes me think it's how I'm formatting it primarily. Basically, an item won't get updated with a new date because the validation formula is causing some issues even though it's in the seemingly correct format and passes the validation. A: So, it ended up being a very simple solution to this. The date I was using to update the items was a string, and I needed to convert it to a date object. There didn't need to be any changes made to the validation formula or date formatting aside from converting "MM/dd/yyy" by using this ($newItemDate was the original date string): $newItemDate = [datetime]$newItemDate
[ "stackoverflow", "0051080999.txt" ]
Q: Populate options on condition from a list of options I am trying to populate options on condition from a list of options. The HTML component I am using is: <div class="select"> <select name="credentialsName" ngModel required> <option *ngFor='let credential of credentials' *ngIf="credential.type==='MACHINE'" [value]="credential.name">{{credential.name}}</option> </select> </div> I am getting syntax error: Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * .Is there a way to show the option dropdown on condition from a option list? A: Because you cannot use Both directives on the single elements, As only one structural directive is allowed on one element at a time. In order to achieve, you can use <ng-container> <ng-container *ngFor='let credential of credentials' > <option [value]="credential.type" *ngIf="credential.type==='MACHINE'"> {{credential.type}} </option> </ng-container> Working Example
[ "stackoverflow", "0007618657.txt" ]
Q: How to check whether NFC is enabled or not in android? How can i check whether NFC is enabled or not programmatically? Is there any way to enable the NFC on the device from my program? Please help me A: NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE); NfcAdapter adapter = manager.getDefaultAdapter(); if (adapter != null && adapter.isEnabled()) { // adapter exists and is enabled. } You cannot enable the NFC programmatically. The user has to do it manually through settings or hardware button. A: I might be a little late here, but I've implemented a 'complete' example with detection of NFC capability (hardware), and Initial NFC state (enabled or disabled in settings), and Changes to the state I've also added a corresponding Beam example which uses the nfcAdapter.isNdefPushEnabled() method introduced in later Android versions to detect beam state like in 2) and 3). A: Use PackageManager and hasSystemFeature("android.hardware.nfc"), matching the <uses-feature android:name="android.hardware.nfc" android:required="false" /> element you should have in your manifest. Since 2.3.3 you can also use NfcAdapter.getDefaultAdapter() to get the adapter (if available) and call its isEnabled() method to check whether NFC is currently turned on.
[ "stackoverflow", "0025130989.txt" ]
Q: Does PHP's SQLite3Stmt class cause locking problems? I'm running PHP 5.3.3 (the latest in CentOS 6.5) as an Apache module with Prefork. I found that an SQLite3 database will lock FOREVER until Apache is restarted, if the script runs out of time or memory in a certain way. Reproducible test: // Open a connection to the database. $db = new SQLite3('/path/to/test.db'); // Get a reserved lock. $db->exec('BEGIN IMMEDIATE TRANSACTION'); // Construct a prepared statement SQLite3Stmt object. $st = $db->prepare('SELECT value FROM sometable WHERE key=:key'); // Emulate the script running off the rails while calling the prepared statement. while(true) { $st->bindValue(':key', 1); } If you run this script, it runs out of execution time and/or memory, of course. From then on, however, the database is locked by the original Apache process. No script can make another reserved lock on the database until Apache is restarted. Shouldn't PHP close the database connection when the script is terminated? Is this a bug in PHP? Would it be solved by running it as a FastCGI process? A: Internally, SQLite uses a POSIX advisory lock on the database file. The operating system will clean up this lock when the process exits. However, as long as the Apache process that has an active transaction is still running, this lock remains. If you have misbehaving scripts, you should run them in a way where aborting them kills the entire process.
[ "stackoverflow", "0034895309.txt" ]
Q: Postgis and Postgresql: type error "st_point" does not exist I followed https://trac.osgeo.org/postgis/wiki/UsersWikiPostGIS21UbuntuPGSQL93Apt guide to setup a PostGIS on Ubuntu 14.04 and despite the fact that process was very smooth by itself, the result is not so rewarding. Even while I was able to create an extension in the database with CREATE EXTENSION postgis;, still query ALTER TABLE "realties" ADD "coordinates" ST_Point; throws an ERROR: type error "st_point" does not exist. Server version is 9.4.5 (package postgresql-9.4-postgis-2.1) Can anyone possibly know how to fix this? A: PostGis only creates a generic type geometry. Objects of type geometry can be points, polygons and so on. ST_Point is not a type but a function which returns a geometry of type Point. Thus the correct syntax is: ALTER TABLE "realties" ADD "coordinates" geometry(Point); If you know which SRID you will use, is good practice to specify the srid as well, in example: ALTER TABLE "realties" ADD "coordinates" geometry(Point, 4326); If you are not sure, what kinds of geometries you will store, do not specify nothing: ALTER TABLE "realties" ADD "coordinates" geometry; PS: Postgis also offer a geography type, which is similar to geometry. For more infos: http://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography
[ "stackoverflow", "0043859273.txt" ]
Q: how to convert a phoenix API to use the --no-html flag I'm presently working on a phx / phoenix project written using Elixir. I created the project with the below command, and with the intention of the project being an API. mix phx.new kegcopr_api --app kegcopr_api --module KegCopRAPI --no-brunch However, I forgot to specify the --no-html flag when creating the project. Is it possible to convert this project to use the --no-html flag? Or do I need to create a whole new project? A: I'm not aware of any automated way to convert it. You could manually remove the html related files and folders: assets (might not be there with --no-brunch) lib/kegcopr_api/web/templates lib/kegcopr_api/web/page_controller.ex lib/kegcopr_api/web/views/page_view.ex lib/kegcopr_api/web/view/layout_view.ex and the related test files. You should also remove the phoenix_html dependency. However, presuming you've only edited a hand full of files, then create a new project and copy over the edited files to the new project.
[ "stackoverflow", "0022910177.txt" ]
Q: C++: Calling an Overload of pure virtual method in base from derived instance I have a base class that comprises an abstract method func(int, float, unsigned) and an overload to this method func(int), and a Derived class that implements the abstract method . class Base { public: virtual void func(int x, float y, unsigned z) = 0; void func(int x) { cout << "func with x only" << endl; } }; class Derived : public Base { public: void func(int x, float y, unsigned z) { cout << "func override" << endl; } }; In my code, I have an instance of the derived class that calls the overloaded method of the base func(int). int main() { Derived d; d.func(10); // <<--------- 'COMPILATION ERROR' return 0; } At compiling this piece of code, I get the following compilation error: error: no matching function for call to 'Derived::func(int&)' note: candidates are: virtual void Derived::func(int, float, unsigned int) What 's the reason for this error / why this code does not work ? A: You need to bring the base class function into the derived class' namespace. Do this by writing using Base::func; somewhere in the declaration of your child class. Note that you are overloading func, not overriding it.
[ "askubuntu", "0000644376.txt" ]
Q: An interesting case of Dual Boot Shenanigans. (dell inspiron 7000) So, my harddrive recently went bust under warranty. As such, Dell shipped me a replacement. And a USB stick containing a full windows 8 installation and repair media. In the land of OEM installs and roms, that thing is a s good as gold. All the fun began when I decided to make a second partition to install Ubuntu on. Also, keep in mind that in order to boot the USB, I had to disable Secure boot, and run it in legacy mode (an option for my computer). Contrary to what I've read on this forum, it can boot win8 without UEFI no problem. The issue was when I installed Ubuntu 14.02 off of a live USB. At first it couldn't install grub properly, then after 3 install attempts it did so successfully but fried my windows boot loader. Using the windows repair tools I managed to get the boot loader working again, but now it ignored ubuntu. I used the live USB to switch the primary boot drive to the one containing GRUB, and updated GRUB so that it could find the windows 8 boot loader image. However, apon loading the win8 image though GRUB, I get a blank bergandy screen and have to force reboot. My computer can't seem to run both Windows and Ubuntu, and I can't run UEFI because we'll, it literally doesn't exist on my computer anymore. Also, contrary to what I've read on the forum my PC can run 32 bit versions of ubuntu, even as a 64 bit machine. I have a 32 bit 12.04 boot disk that work perfectly fine. Infact, that. Disk. Seems to have been the only way to fix the boot partition problem I had earlier. Currently, i've gon over with a fresh install of windows, there is still a dormant Ubuntu, swap, and win8 loader partitions. A: I'm going to take some key points of your question out of order: I can't run UEFI because we'll, it literally doesn't exist on my computer anymore. I think you misunderstand what UEFI is. As described in more detail on Wikipedia, the Extensible Firmware Interface (EFI) and its version-2.x variant, the Unified EFI (UEFI) is a type of firmware that has largely replaced the older Basic Input/Output System (BIOS) firmware. As such, a computer will have either a BIOS or an EFI/UEFI when you buy it, and it's difficult to replace one with the other. The operations you described could not have removed your EFI. If your computer shipped with Windows 8.x, it almost certainly used UEFI, and continues to do so. Ditto for most computers introduced in mid-2011 and later, even if they shipped with Windows 7 (or Linux or nothing at all). You might be thinking of the EFI System Partition (ESP), which as the name implies, is a partition on your hard disk. As such, the ESP can be deleted. The ESP stores EFI boot loaders, so if you completely wiped and re-partitioned your disk, it might now lack an ESP. That does not eliminate the EFI/UEFI, though. in order to boot the USB, I had to disable Secure boot, and run it in legacy mode (an option for my computer). Was this the Windows USB drive or an Ubuntu USB drive? If the latter, how did you create it? Most EFIs provide a Compatibility Support Module (CSM), which is an EFI component that enables the EFI to use boot loader code designed for BIOSes. A CSM is to an EFI something like what WINE or DOSEMU is to Linux -- a way for one environment (EFI or Linux) to run code designed for another one (BIOS or DOS/Windows). Enabling the CSM (aka "legacy mode" or "BIOS mode") support in the firmware makes it possible to boot BIOS-mode media, but at the cost of added complexity -- the number of paths the boot process can take rises dramatically, as I explain in more detail on this Web page. This complexity means that the boot process becomes unpredictable when the CSM is enabled -- at least, unless you understand the idiosyncracies of your specific computer, which of course people posting on the Internet will not. My view of the CSM has become increasingly negative as I've read more and more accounts of problems it's created for people. In most cases, they end up fumbling around in the dark until they stumble across a solution. In any event, it seems odd (but not impossible) to me that a Windows 8 boot medium provided by a manufacturer would boot only in BIOS/CSM/legacy mode, since such computers almost always ship configured to boot in EFI/UEFI mode. Ubuntu boot media are another matter, since USB-writing tools may drop the EFI boot loader or otherwise make it difficult or impossible to boot in EFI mode. In either event, I think it's worth taking the time to figure out what's going on and get both Windows and Ubuntu installation media to boot in EFI mode. If that proves impossible, it's imperative that they both boot in BIOS/CSM/legacy mode. Having one installation in EFI mode and the other in BIOS mode is a recipe for frustration. The issue was when I installed Ubuntu 14.02 off of a live USB. At first it couldn't install grub properly, then after 3 install attempts it did so successfully but fried my windows boot loader. This doesn't really tell us what the state of your computer is. Please run the Boot Info Script (also available in the boot-info-script package in Ubuntu). This will produce a file called RESULTS.txt. Post it to a pastebin site and post the URL to your document here. The information from the Boot Info Script should provide a good idea of your computer's current state, which is required to provide a solution that's more than guesswork. At this point, my guess is that you've got a BIOS-mode Windows install and an EFI-mode Ubuntu install, but it might be the other way around or even something else entirely (matched-mode installs with boot problems that have some other cause). Alternatively, you could start again fresh -- figure out which boot mode you're using (BIOS or EFI) for both your Windows and Ubuntu media, adjust them until they both use the same boot mode, and re-install both OSes in the same boot mode.
[ "stackoverflow", "0006756019.txt" ]
Q: Professional Websites Built with Razor I was asked at a .NET user group if I knew of any professional web sites built with the Razor view engine for MVC that they could peruse. Interesting question, and I was not aware of any at the time. Does anybody know of a publicized list or specific web sites that have implemented Razor? Thanks. A: I was involved in building this one: http://snapshot.factiva.com. Bad news is that you need an account to be able to see it. Here's a list of public websites which includes our own SO: http://www.findmyhosts.com/top-10-asp-net-mvc-framework-websites/
[ "stackoverflow", "0056090633.txt" ]
Q: My script works the first time and does anymore not after reload on this online IDE I have a slight problem with this online code editor. When I launch my snippet, it only works one time. If I try to bring any modification to the code, it crashes for unknown reasons. https://playcode.io/313059?tabs=console&script.js&output Any clue of what is going on here? A: I just checked and I think that your code is executing while the editor is not loaded yet. Wait for the document or window to be loaded and then execute the code as following: $( document ).ready(function() { var block = document.getElementById('block'); var block_scale = window .getComputedStyle(block, null) .getPropertyValue("transform"); var matrix = block_scale.match(/\d+(?:\.\d+)?/gm); console.log(matrix[0]); });
[ "stackoverflow", "0004914223.txt" ]
Q: How can i prevent sql injection but keep " and '? How do prevent sql injection in php but still show " and '? A the moment I am using $input = strip_tags($input); $input = htmlentities($input); However the output is \" and \'. Is there anyway I can show " and ' without the slashes but keep them there so I don't get injected? A: The method you show is not a proper way to protect against SQL injection! Always use the sanitation method provided by the database library you are using, e.g. mysql_real_escape_string() if you work with the standard mysql library. The sanitation method will not alter any characters in the end result. Alternatively, use prepared statements in PDO or mysqli - those do input sanitation automatically if you bind the incoming data correctly. A: First, that code is not stripping backslashes, of course they're still there. Use stripslashes() to take out backslashes, but DON'T DO IT. If you see those slashes in the DB, and you HAVE USED mysql_real_escape_string, chances are you have magic_quotes_gpc on, and you're just adding another set of slahses. Remove those auto added first and then apply mysql_real_escape_string, they won't show this way but will still be there and make for a safe use in querying your DB.
[ "stackoverflow", "0002442141.txt" ]
Q: Uniform distribution of binary values in Matlab I have a requirement for the generation of a given number N of vectors of given size each consistent of a uniform distribution of 0s and 1s. This is what I am doing at the moment, but I noticed that the distribution is strongly peaked at half 1s and half 0s, which is no good for what I am doing: a = randint(1, sizeOfVector, [0 1]); The unifrnd function looks promising for what I need, but I can't manage to understand how to output a binary vector of that size. Is it the case that I can use the unifrnd function (and if so how would be appreciated!) or can is there any other more convenient way to obtain such a set of vectors? Any help appreciated! Note 1: just to be sure - here's what the requirement actually says: randomly choose N vectors of given size that are uniformly distributed over [0;1] Note 2: I am generating initial configurations for Cellular Automata, that's why I can have only binary values [0;1]. A: To generate 1 random vector with elements from {0, 1}: unidrnd(2,sizeOfVector,1)-1 The other variants are similar.
[ "math.stackexchange", "0000805001.txt" ]
Q: Proving that if $f$ is an increasing function on $I \subset \mathbb{R}$, then $\lim_{y \to x^{-}} f(y)$ and $\lim_{y \to x^{+}} f(y)$ exists. I am trying to prove that if $f$ is a monotone increasing function on an interval $I \subset \mathbb{R}$, then the limits $\lim_{y \to x^{-}} f(y)$ and $\lim_{y \to x^{+}} f(y)$ exists. My definition of monotone increasing is that $f$ is monotone increasing if $f(x) \leq f(y)$ given $x,y \in I$ with $x \leq y$. My approach is to look at infimum and supremum but am having difficulties. Does anyone know of a simple solution? Thank you! A: Assume $x$ is not on the boundary of $I$. Then the set $$\{f(y) : y < x\} $$ is bounded above by $f(x)$, and the set $$\{f(y) : y > x\}$$ is bounded below by $f(x)$. Therefore $$\sup \{f(y) : y < x\} \text{ and } \inf\{f(y) : y > x\}$$ exist in $\mathbb{R}$. I will show that $\lim_{y\rightarrow x^-} f(y) = \sup \{f(y) : y < x\}$. Let $\epsilon> 0$ be given, by the definition of supreme, there exist a $y_0<x$ such that $$\sup \{f(y) : y < x\} - f(y_0) \leq \epsilon,$$ and because $f$ is monotone increasing, for each $y\in [y_0, x)$, we have $$\sup \{f(y) : y < x\} - f(y) \leq \sup \{f(y) : y < x\} - f(y_0) \leq \epsilon,$$ which is precisely the definition of $\lim_{y\rightarrow x^-} f(y) = \sup \{f(y) : y < x\}$.
[ "stackoverflow", "0028264279.txt" ]
Q: undefined reference when accessing static constexpr float member This code works: struct Blob { static constexpr int a = 10; }; int main() { Blob b; auto c = b.a; } But if I change int to float I get an error: struct Blob { static constexpr float a = 10.0f; }; /tmp/main-272d80.o: In function main': main.cpp:(.text+0xe): undefined reference toBlob::a' Why can't I use a constexpr float in that way? Compiler: Ubuntu clang version 3.5.0-4ubuntu2 (tags/RELEASE_350/final) Tested on gcc version 4.9.1 (Ubuntu 4.9.1-16ubuntu6) and there were no error. EDIT: It will compile if I use -O1, -O2, -O3 or -Os but fails with -O0 A: C++11 reads A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied. Clearly the l-t-r conversion is immediately applied, and a constexpr variable of floating point type can appear in constant expressions as per [expr.const]/(2.7.1): A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression [..] an lvalue-to-rvalue conversion (4.1) unless it is applied to a glvalue of literal type that refers to a non-volatile object defined with constexpr, or that refers to a sub-object of such an object, or Seems to be a Clang bug. A: Interestingly, if we use Blob::a instead, clang does not complain: auto c = Blob::a; This should not matter for determining if the it is odr-used or not. So this looks like a clang bug which I can reproduce on clang 3.7 using no optimization only. We can tell this is an odr issue since adding a out of class definition fixes the issue (see it live): constexpr float Blob::a ; So when do you need to define a static constexpr class member? This is covered in section 9.4.2 [class.static.data] which says (emphasis mine going forward): A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer. It requires a definition if it is odr-used. Is it odr-used? No, it is not. The original C++11 wording in section 3.2 [basic.def.odr] says: An expression is potentially evaluated unless it is an unevaluated operand (Clause 5) or a subexpression thereof. A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied. a satisfies both conditions, it is a constant expression and the lvalue-to-rvalue conversion is immediately applied. Defect Report 712 has changed the wording which applies to C++11 since it is a defect report and 3.2 now says: A variable x whose name appears as a potentially-evaluated expression ex is odr-used unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.19) that does not invoke any non-trivial functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion (4.1) is applied to e, or e is a discarded-value expression The potential result that matches would be: If e is an id-expression (5.1.1), the set contains only e. it is a constant expression and the lvalue-to-rvalue conversion is applied so it is not odr-used.
[ "stackoverflow", "0020675646.txt" ]
Q: GCC 2.9 and "lvalue required as left operand of assignment" I have been playing around with void pointers and created this example: #include <stdio.h> struct intint { int a; int b; }; struct intshortshort { int a; short b; short c; }; void fill_me(struct intint **pii, void *piss) { (void*)*pii = piss; // Question about this line? } int main() { struct intint *pii = NULL; struct intshortshort iss; iss.a = iss.b = iss.c = 13; fill_me(&pii, &iss); printf("%d..%d\n", pii->a, pii->b); return 0; } Question: When I'm using gcc version 2.95.4 everything compiles and works as expected, but gcc version 4.7.3 gives me following error: void_pointer.c:16:17: error: lvalue required as left operand of assignment Is there a reason why adding (void *) to lvalue is not allowed anymore? Edit: Thank you for answers, I think I understood the problem, but the question "why it was ok in the first place?" is still interesting. A: This question isn't about the void*, is about typecast and lvalue. for example: #include <stdio.h> int main() { int n; (int)n = 100; return 0; } this code will causes same error: lvalue required as left operand of assignment. That because the = operator requires a modifiable-lvalue as its left operand. So, what is the lvalue? and what's the modifiable-lvalue? Please see wikipedia:Value.
[ "stackoverflow", "0006188353.txt" ]
Q: SUBSELECT contains an error - but sql statement continues I have the following example code: create table #tempmembers ( memberid int ) update Members set Member_EMail = NULL where Member_ID in (select member_id from #tempmembers) The subselect contains an error, since #tempmembes does not contain a column named member_id, but the sql statements run WITHOUT any errors and update no rows. If I then add just ONE row to #tempmembers: create table #tempmembers ( memberid int ) insert into #tempmembers select 1 update Members set Member_EMail = NULL where Member_ID in (select member_id from #tempmembers) it still runs without any errors - but this time ALL records in Members will be affected. Why does the SQL statement not fail completely? And if the failing subselect is evaluated to NULL - should updating all rows in Members not only occur if it had been: update Members set Member_EMail = NULL where Member_ID not in (select member_id from #tempmembers) A: It's inheriting member_id from the outer query so is equivalent to: ... (select Members.member_id from #tempmembers) This will fail as expected: ... (select #tempmembers.member_id from #tempmembers)
[ "stackoverflow", "0006294881.txt" ]
Q: Null pointer exception in iterating and unable to search a node. The delete and replace methods are the ones that have problems import javax.swing.*; import java.io.*; class MyDatabase implements Database { Node head = null, tail = null, rover = null; String ako; File myFile = new File("sample.dat"); Node n = new Node(); Node current; Node p; Node x = new Node(); public void insert(Node myNewNode) { if (head == null){ head = myNewNode; head.next = null; } else { tail = head; while(tail.next != null) tail = tail.next; tail.next = myNewNode; myNewNode.next = null; } current = head; } public boolean delete(Node nodeToDelete) { //the delete and replace methods are the ones that have problems current = head; p = head; head = null; //here, no matter what you enter, this if statement is never executed. Yes, never. even if they are equal. if(nodeToDelete.title == head.title) { head = head.next; return true; } else{ while(current != nodeToDelete) current = current.next;//Null Pointer exception here while(p.next != nodeToDelete) p = p.next;//Null Pointer exception here current = current.next; p = current; } current = head;//this is for listIterator purposes. return true; } public boolean replace(Node nodeToReplace, Node myNewNode) { //the delete and replace methods are the ones that have problems //here i tested if the head.title and nodeToReplace.title have values //the println correctly prints the value that I input current = head; String s = head.title;// for example i entered "max" String s1 = nodeToReplace.title;// i also entered "max" System.out.println(s);//prints out "max" System.out.println(s1);// prints out "max" if(s == s1) { // if statement is not executed. Note: i entered the same string. myNewNode.next = head.next; head = myNewNode; } else { while(current != null) { String s2 = current.title; if(s2 == s1) { current = new Node(myNewNode); } } } current = head; return true; } public Node search(Node nodeToSearch) { current = head; while(current != null) { if(current == nodeToSearch) { Node p = new Node(current); current = head; return p; } } return null; } public boolean saveToFile(String filename) throws Exception { Node p = new Node(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(myFile)); out.writeObject(p); out.close(); return true; } public boolean loadFromFile(String filename) throws Exception { ObjectInputStream in = new ObjectInputStream(new FileInputStream(myFile)); head = (Node) in.readObject(); return true; } public Node listIterator() { try{ if(current == head) { rover = current; current = current.next; return rover; } else { rover = current; current = current.next; Node p = new Node(rover); return p; } } catch(NullPointerException e) { current = head; return null; } } public Node listIterator2() { try{ if(current == head) { rover = current; current = current.next; return rover; } else { rover = current; current = current.next; return rover; } } catch(NullPointerException e) { current = head; return null; } } public boolean equals(Database db) { Node p; while(rover != null) { p = head; while(p != null) { if(rover != p) return false; p = p.next; } rover = rover.next; } return true; } public String whoIAm() { ako = "Michael Glenn R. Roquim Jr. !"; return ako; } } A: You trigger your own NPE: // vv-- here you set head to null, just before you dereference it to access .title head = null; //here, no matter what you enter, this if statement is never executed. Yes, never. even if they are equal. if(nodeToDelete.title == head.title) {
[ "magento.stackexchange", "0000100393.txt" ]
Q: Can I use Magento without mcrypt? My shop was moved to a server without mcrypt and for some reason mcrypt can not be installed (don't ask me why!). Looks like passwords are only encrypted with md5 with a salt (bad!) so I wonder what mcrypt is used for at all. Someone hacked Magento and was able to install it without mcrypt. Does not sound good to me but it was working for him. Now i would like to know what for encrypt is used and will the show break if I replace it with a dummy? Is there a better workaround? May get secure random from openssl and add an encryption lib? TL;DR What is mcrypt used for in Magento? Is a good workaround possible? A: MCrypt is not used for password and URL key hashing but for encrypting and decrypting sensitive data such as API passwords, e.g. stored in / retrieved from the system configuration. All MCrypt functionality is encapsulated in Varien_Crypt_Mcrypt. This class again is accessed via Mage_Core_Model_Encryption. The encryption model that should be used throughout the application is configured in the config/global/helpers/core/encryption_model node. So (in theory) there is sort of a chance to replace this one by your own encryption model – as long as it satisfies the former's interface. At first glance it looks like you need to extend Mage_Core_Model_Encryption and replace the _getCrypt method. This should return a class instance that implements the same methods as Varien_Crypt_Mcrypt – but makes use of a different encryption library.
[ "stackoverflow", "0018237477.txt" ]
Q: Send an object to another object and call first objects method I would like to send an object A as a referenced attribute to object B, and then call object A's getter method within object B. The code below gives the error: myClass.cpp:11: error: passing ‘const myClass’ as ‘this’ argument of ‘int myClass::getNum()’ discards qualifiers // Main file: class_method_test.cpp #include <iostream> #include <iomanip> #include "myClass.h" using namespace std; int main() { myClass objA = myClass( 2 ); myClass objB = myClass( 3 ); objA.calc(objB); cout << objA.getNum() << endl; objB.print(); } // myClass.h #ifndef MYCLASS_H #define MYCLASS_H #include <string> class myClass{ private: int myNum; std::string anyText; public: myClass(); myClass(int); void calc(const myClass &); int getNum(); void print(); void setText(std::string); std::string getText(); }; #endif // myClass.cpp #include <iostream> #include "myClass.h" using namespace std; myClass :: myClass() : myNum(0) {}; myClass :: myClass ( int aNum ) : myNum( aNum ) {}; void myClass :: calc( const myClass & calcObj ) { myNum += calcObj.getNum(); }; int myClass :: getNum() { return myNum; }; void myClass :: print () { cout << myNum << endl; }; void myClass :: setText(std::string newText) { anyText = newText; } string myClass :: getText() { return anyText; } A: You need to make getNum() a const method: int getNum() const; // ^^^^^ This is because calc() takes a const reference to myClass, so only const methods can be called on that reference. void calc(const myClass &); // ^^^^^ Looking at the implementation of getNum(), there is no reason for it not to be const anyway.
[ "stackoverflow", "0026435375.txt" ]
Q: Anyone who updated to SDK 5.0 having issues with splitActionBarWhenNarrow? I just updated my SDK and started my app back up (it was running fine right before the update) and now my split action bar is not splitting. I'm not sure if I'm doing something wrong, here is my setup: <activity android:uiOptions="splitActionBarWhenNarrow" ....> <meta-data android:name="android.support.UI_OPTIONS" android:value="splitActionBarWhenNarrow" /> </activity> I've tested this on a GS3 4.4 and on a Nexus 4 which also has 4.4. I'll test other devices in a bit. Thanks. EDIT: looks like the split actionbar is gone so I'll have to figure something else out. A: Looks like the split actionbar is no longer supported under L and it is recommended that you use the new Toolbar https://code.google.com/p/android/issues/detail?id=77632
[ "superuser", "0000592442.txt" ]
Q: Can I create a single ftp to access multiple network locations I have an ftp server setup using FileZilla Server and 5 application servers which each have a backup folder that is shared. On the ftp server I have setup symlinks in the root ftp directory that point to each of the backup directories. When using Windows Explorer I can navigate between each of these network locations via the symlinks, add, modify or delete as I please. However, when I connect to the same location using an ftp client, the symlink folders are visible; appserver01backups, appserver02backups, etc. but when they are opened they are listed as empty directories. Can anyone help resolve this or think of a better solution to be able to access multiple network shared folder locations from a single point of access e.g. ftp. A: Access to the networked locations were being authenticated against the service account used to run the FilZilla service. I switched this to an account that has permissions to access the networked location. Being a non-domain environment, this was duplicated accounts with the same username and password on both the ftp server and all source application servers.
[ "academia.stackexchange", "0000130863.txt" ]
Q: Co-author wants to put their current funding source in the acknowledgements section because they edited the paper In this situation there is a co-author that wants their current funding source added to the acknowledgements section because they edited the paper that others wrote. The research in the paper is something the co-author worked on as a graduate student about 5 years ago, but they have since become an assistant professor elsewhere and no longer contribute to the paper's research. The separate funding source they used several years ago to contribute to the data analysis for the paper is already listed in the acknowledgements. The paper did not need major editing, but for the sake of scope - if the paper had needed major edits would that change the answer? Never had this type of interaction before. I'm wondering if putting that acknowledgement would implicitly say that the co-author's current funding also funded the research in the paper. Maybe "Co-author was funded by Blank to edit the manuscript" is a middle ground? The source of funding in question is the co-author's country's government - although unclear if it's a research grant or co-author's salary as a professor. In either case is it acceptable to "use" this money to edit manuscripts from previous work done and funded elsewhere? First paper & graduate student, to finalize the context. A: In general, I would be pragmatic about this. If the contribution of the Assistant Professor is large enough to warrant co-authorship (which is a different story altogether, and not the question here), it should be large enough to mention their funding source. Presumably they have actually had to invest some amount of time into the manuscript to warrant co-authorship, and if they "used" their own university-funded research time or some external project time to contribute to the paper is really their own business. Clearly this does not mean that you need to pretend like the entire work was funded by your co-authors grant, but a clause in the acknowledgements such as "Prof. X acknowledges the financial support provided by XYZ" is common and completely appropriate. I'm wondering if putting that acknowledgement would implicitly say that the co-author's current funding also funded the research in the paper. Only if you word it poorly. Maybe "Co-author was funded by Blank to edit the manuscript" is a middle ground? This sounds very uncommon to me. I would only write it like that if you also explicitly list who paid for all other parts of the study (which would be highly unusual in my field). In either case is it acceptable to "use" this money to edit manuscripts from previous work done and funded elsewhere? That's a question between your co-author and their funding source, and shouldn't really be your concern. A: If you have valid reasons to be worried about the implications of such insinuations (something I'm not sure about) - you can write it a longer comment describing two phases of the work - the "research" you mentioned to which said co-author has not been part of, and the writing work. Now, I wouldn't say co-author X was only involved in writing, or only involved in editing, but perhaps something like: Lab research was conducted at [Institute name] between [start year] and [end year] and supported by [funding sources here]. Work on this submission has received additional support from [the editing co-author's funding source here]
[ "stackoverflow", "0040763718.txt" ]
Q: Kubernetes HTTPS Ingress in Google Container Engine I want to expose a HTTP service running in Google Container Engine over HTTPS only load balancer. How to define in ingress object that I want HTTPS only load balancer instead of default HTTP? Or is there a way to permanently drop HTTP protocol from created load balancer? When I add HTTPS protocol and then drop HTTP protocol, HTTP is recreated after few minutes by the platform. Ingress: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: myapp-ingress spec: backend: serviceName: myapp-service servicePort: 8080 A: In order to have HTTPs service exposed only, you can block traffic on port 80 as mentioned on this link: You can block traffic on :80 through an annotation. You might want to do this if all your clients are only going to hit the loadbalancer through https and you don't want to waste the extra GCE forwarding rule, eg: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: test annotations: kubernetes.io/ingress.allow-http: "false" spec: tls: # This assumes tls-secret exists. # To generate it run the make in this directory. - secretName: tls-secret backend: serviceName: echoheaders-https servicePort: 80
[ "stackoverflow", "0055766619.txt" ]
Q: Changing the Style of a HTML-Button within a JavaScript Function I am trying to change the style class of a button when clicking it but it is not working how it should. I need the style/icon change inside a JS function because I am doing some more stuff when the buttons gets clicked. function generate() { //// Some stuff document.getElementById('btn1').class = 'play icon fa fa-stop'; } <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <div class='container20'> <button class='play icon fa fa-play-circle-o' type='button' onclick='generate()' id="btn1">Button</button> </div> A: class not exist, there is className, so replace it by className In onclick there is function so, you need to add () in it so, replace generate to generate(). <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <div class='container20'> <button class = 'play icon fa fa-play-circle-o' type = 'button' onclick = 'generate()' id = "btn1">Button</button> </div> <div class='container80'> <script> function generate() { //// Some stuff document.getElementById('btn1').className = 'play icon fa fa-stop'; } </script> </div>
[ "stackoverflow", "0054698349.txt" ]
Q: Issue with Nested JSON in PHP I'm getting close to getting this JSON from a MySQL query right, but I'm having some difficulty. $results = []; foreach ($getbill as $row) { $category = $district; $building = $row['building']; if (!isset($results[$category])) {$results[$building] = ['category' => $building, 'values' => []]; } $results[$category] = ['category' => $building, 'values' => []]; $results[$row['building']]['students'][] = ['lastname' => $row['slast'], 'firstname' => $row['sfirst'], 'ens' => $row['selected'], 'part' => $row['instname'], 'division' => $row['sdiv'], 'festival' => $row['sfest']]; } echo json_encode(array_values($results)); The code above exports: [{"category":"Belmont Elementary School","values":[],"students":[{"lastname":"jones","firstname":"melissa","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"smith","firstname":"melissa","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"b","firstname":"b","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"b","firstname":"b","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"chocolate","firstname":"Charlie","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"Shmow","firstname":"Joe","ens":"C","part":"Childrens Voice","division":"1","festival":"w"},{"lastname":"abrams","firstname":"Alysond","ens":"C","part":"Childrens Voice","division":"1","festival":"w"}]},{"category":"Parliament Place","values":[]},{"students":[{"lastname":"Jones","firstname":"Joe","ens":"B","part":"Trombone","division":"1","festival":"w"},{"lastname":"Smith","firstname":"Ally","ens":"B","part":"Alto Sax","division":"1","festival":"w"}]}] It is grouping by School, however, the School has to be listed in the beginning, right before the student information. The finished product needs to be as follows, but I'm at a loss... {"length":8,"schools":[{"name":"Test High School","students":[{"lastname":"Smith","firstname":"Allison","ens":"Band","part":"Bb Clarinet","division":"III","festival":"West"},{"lastname":"Jones","firstname":"Derek","ens":"Band","part":"Tuba/Sousaphone","division":"III","festival":"West"},{"lastname":"Johnson","firstname":"Matthew","ens":"Band","part":"Timpani","division":"III","festival":"West"},{"lastname":"Hughley","firstname":"Elizabeth","ens":"Band","part":"French Horn","division":"II","festival":"West"}]},{"name":"Test Elementary School","students":[{"lastname":"Jones","firstname":"Emmett","ens":"Band","part":"Bb Clarinet","division":"I","festival":"West"},{"lastname":"Aaren","firstname":"Owen","ens":"Band","part":"Tuba/Sousaphone","division":"I","festival":"West"},{"lastname":"Johns","firstname":"Sonia","ens":"Band","part":"French Horn","division":"I","festival":"West"},{"lastname":"Williams","firstname":"Nathaniel","ens":"Band","part":"Bb Clarinet","division":"I","festival":"West"}]}],"bill":120} I assume that I can use a PHP variable to get the "Length" and "Bill" part correct by counting the records of the query and by multiplying by 15, but .. How do I squeeze in all of the correct JSON creation code in PHP? Updated: Original Data Below UPDATE 2: I figured it out. It was the original comment from @Raymond that put me in the right direction. Thank you. I had to get rid of one line of my query, and I had to manually 'echo' the beginning and the end (length and cost). It's working! Thank you all for your help. foreach ($getbill as $row) { if (!isset($results[$building])) { $results[$building] = ['name' => $row['building']]; } $results[$row['building']]['students'][] = ['lastname' => $row['slast'], 'firstname' => $row['sfirst'], 'ens' => $ens, 'part' => $row['instname'], 'division' => $age, 'festival' => $loc]; } A: Does this code example help you? PHP objects will be converted into a JSON Object which is the {} part. PHP array will be converted into a JSON Array which is offcource the [] part. PHP code <?php $StdClass = new StdClass(); $StdClass->length = 10; $StdClass->schools = array_values(array(1, 2)); var_dump(json_encode($StdClass)); ?> Result string(29) "{"length":10,"schools":[1,2]}" Edited because off comment: Thank you for your quick reply, but sadly, I'm having a real tough time figuring that out. Also, there are all of these 'character counts' that I can't use. Yes getting the [{..}] JSON format for schools and students it more tricky. I advice you writing custom classes and use JsonSerializable to convert your custom Objects into JSON PHP 7 code <?php class school implements JsonSerializable { private $name = null; private $students = array(); private function __construct() { } public function __destruct() { $this->name = null; $this->students = null; } // Use a static object because it will enable method chaining public static function getInstance() { return new school(); } public function setName(string $name) : school { $this->name = $name; return $this; // needed to chain } public function setStudent(Student $student) : school { $this->students[] = $student; return $this; // needed to chain } public function getName() : ?string { return $this->name; } public function getStudents() : ?array { return $this->students; } public function __get($name) : mixed { return $this->name; } public function jsonSerialize() { return array( "name" => $this->name , "students" => $this->students ); } } class student implements JsonSerializable { private $lastname = null; private $firstname = null; private function __construct() { } public function __destruct() { $this->lastname = null; $this->firstname = null; } // Use a static object because it will enable method chaining public static function getInstance() { return new student(); } public function setLastName(string $lastname) : student { $this->lastname = $lastname; return $this; // needed to chain } public function setFirstName(string $firstname) : student { $this->firstname = $firstname; return $this; // needed to chain } public function getFirstName() : ?string { return $this->firstname; } public function getLastName() : ?string { return $this->lastname; } public function jsonSerialize() { return array( "lastname" => $this->lastname , "firstname" => $this->firstname ); } } $json = new stdClass(); $json->length = 10; $json->schools = array( school::getInstance() ->setName('Test High School') ->setStudent( student::getInstance() ->setFirstname('Smith') ->setLastname('Allison') ) ->setStudent( student::getInstance() ->setFirstname('Jones') ->setLastname('Derek') ) , school::getInstance() ->setName('Test Elementary School') ->setStudent( student::getInstance() ->setFirstname('Jones') ->setLastname('Emmett') ) ); var_dump(json_encode($json)); ?> p.s to get the code working on lower PHP versions remove the PHP's return type declarations Results in this JSON format { "length": 10, "schools": [{ "name": "Test High School", "students": [{ "lastname": "Allison", "firstname": "Smith" }, { "lastname": "Derek", "firstname": "Jones" }] }, { "name": "Test Elementary School", "students": [{ "lastname": "Emmett", "firstname": "Jones" }] }] }
[ "ell.stackexchange", "0000072559.txt" ]
Q: Skull's bones or skull bones? What is the correct option of these following two? skull's bones or skull bones Please, explain me the answer, because it's something that I have often. The context: "22 skull bones (or skull's bone) + 34 vertebrae are equal to 56 bones." A: In most cases you would say skull bones, since that is a particular category of bones, just as their are foot bones, arm bones, or leg bones. For example: There are 22 skull bones. The occipital bone is the skull bone found on the lower back of the head. There are some limited cases in which you might use the possessive though. If you were describing the skull in general and wanted to comment on its bones, you might say something like: The skull's bones begin as a collection of plates that fuse together as a person matures. Perhaps more likely in this case would be a possessive phrase that is a bit old fashioned in most other circumstances. The bones of the skull begin as ...
[ "stackoverflow", "0021499561.txt" ]
Q: Is it possible to parse struct by reference in Matlab? Say I have a dynamically built struct (such as data.(casenames{c}).t25s). Accessing this dynamically quickly makes very cluttered and hard-to-read code with lots of duplication (e.g. plot(data.(casenames{c}).t14s.x,data.(casenames{c}).t14s.y);). So my question is: Can I pass a struct by reference to another variable? Something like the following: for cno = 1:length(casenames) data.(casenames{c}) = struct; ... % do some file reading and fill in .x and .y end for cno = 1:length(casenames) case = @data.(casenames{c}); % Naïve parse by ref case.z = case.x + case.y end This should then cause data.(casenames{c}).z to be assigned the value of data.(casenames{c}).x + data.(casenames{c}).y A: With basic data types, no. You can get handles to objects, so if your structs and data methods are sufficiently complex, that may be worth a thought. Otherwise, it's usually possible to simply refactor the code for clarity: for cno = 1:length(casenames) data.(casenames{c}) = struct; ... % do some file reading and fill in .x and .y end for cno = 1:length(casenames) % read-modify-write idiom data.(casenames{c}) = dosomething(data.(casenames{c})); end function case = dosomething(case) case.z = case.x + case.y; end Side note: since Matlab's "pass by value" is actually "pass by reference with copy-on-write" internally, it's possible to exploit this from MEX functions, but it's entirely unsupported and may cause unexpected behaviour.
[ "stackoverflow", "0005917151.txt" ]
Q: Best way to wire up NSMenuItems from Interface Builder? So I've spent some time checking out CocoaDev, reading the Cocoa docs on NSMenuItems, and doing some tests in Interface Builder. In my application I have an application menu ([NSApp mainMenu]) designed in Interface Builder. I see three potential paths: Put my action responders in the NSApplicationDelegate. This seems strange to me, partially because it's so far up the food chain, partially because it seems bolted on. Create a sub-view(s) that would listen for the various NSMenuItem action messages. This would seem useful but it looks like in order for it to be in the responder chain there might be some magic I couldn't figure out. Create an NSObject that listens for the specific application menu stuff, put it in the xib, and wire it up. This seems to me the best solution at the moment, because I can isolate stuff, and not depend upon the responder chain to reach a specific object. BUT I wonder if, when I get my app to a sufficient level of complexity, this may be a problem because it usurps the responder chain, which is there for perhaps a reason beyond just ease of use. Sorry for the long question. Is there a preferred approach? Thanks! A: It really depends on the architecture of your application. As a general rule, implement actions wherever they make sense. The responder chain for action messages helps you in that regard. If your application isn’t document-based, the responder chain for action messages goes like this: Whichever responder is the first responder View hierarchy Window Window controller Window delegate NSApp Application delegate I only use actions in the application delegate if they’re truly global for the entire application. Otherwise, I put them in the window controller (which is normally the window delegate as well) if they make sense for a specific window, or a view controller if they make sense for a specific view. It’s worth mentioning that view controllers (subclasses of NSViewController) aren’t automatically inserted in the responder chain. I do that manually after adding the corresponding view to a superview. For instance, in an NSViewController subclass: NSResponder *nextResponder = [[self view] nextResponder]; [[self view] setNextResponder:self]; [self setNextResponder:nextResponder]; This inserts self (an instance of a subclass of NSViewController) in the responder chain between the view and the original view’s next responder. Note that there’s nothing inherently wrong with your third approach, namely having a specific target for (a subset of) action messages. The responder chain exists to give a chance for different objects to handle action messages because some actions can be context-dependent. For example, the actions under the File menu are normally applied to the window that’s currently the main window, so it makes sense to not have a specific target and use the responder chain instead. On the other hand, the actions under the ApplicationName menu are truly global—they don’t need to go through the responder chain, so you can hook them up to a specific target.
[ "stackoverflow", "0035336017.txt" ]
Q: How do I get a Keyevent from another class? So I got 2 classes called Viewer and PaintWindow. In my case, the Viewer class acts as an controller while I use my PaintWindow class to paint things on a JPanel. Now I'm trying to put together a little game but I don't understand how to implement the KeyListener to be able to control the game. What I want is a listener listeing for a keyEvent to happen so I can decide what will happen. This is how my code looks like: Viewer: public void run() { System.out.println("Viewer Run"); cloud1 = new ImageIcon("src/images/cloud.png"); cloud2 = new ImageIcon("src/images/cloud.png"); background1 = new ImageIcon("src/images/background.png"); playerStill = new ImageIcon("src/images/still.png"); playerRight = new ImageIcon("src/images/right.png"); playerLeft = new ImageIcon("src/images/left.png"); paintWindow = new PaintWindow(background1); paintWindow.showImage(playerStill, 30, 370); paintWindow.addKeyListener(new KeyTimerListener()); paintWindow.startAlarm(); } /* * Lyssnar på vad som händer när man trycker en viss knapp */ private class KeyTimerListener implements KeyListener { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == 37){ System.out.print("Left"); } else if (keyCode == 39){ System.out.print("Right"); } else if (keyCode == 32 ){ System.out.print("JUMP"); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } } This is a part from my PaintWindow class: public void addKeyListener(KeyListener listener){ this.listener.add(listener); } private class AT extends Thread { KeyEvent keyevent; public void run() { try { Thread.sleep(1); }catch(InterruptedException e) { } for(KeyListener al : listener) { al.keyPressed(keyevent);//<----------------------------- } thread = null; } } public void startAlarm() { if(thread==null) { thread = new AT(); thread.start(); } } I get a nullpointer exception as my KeyEvent is null. Sure I could define it as being a specific key, but that doesn't really help me here. What have I missed? A: Forget about your KeyListener , since PaintWindow will receive no key event , not being a java.awt.Component . Instead, add this code in your run() method : KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(final KeyEvent e) { // we only want PRESSED events if(e.getID() == KeyEvent.KEY_PRESSED){ int keyCode = e.getKeyCode(); if(keyCode == 37){ System.out.print("Left"); } else if (keyCode == 39){ System.out.print("Right"); } else if (keyCode == 32 ){ System.out.print("JUMP"); } } return false; } }); This will listen to all key events in your application. More information in this topic : How can I listen for key presses (within Java Swing) across all components?
[ "stackoverflow", "0046484898.txt" ]
Q: Oracle Users Tables I've created some TABLES in 1 DB with the user name DEVICE. Querying the tables I see that they belong to the user DEVICE SELECT owner, table_name FROM dba_tables Then I created a user named CAR, I logged in the DB with that user and create some tables, I've tried to query the other tables with SELECT * FROM DEVICE.table_name; with the result 00942. 00000 - "table or view does not exist" and logged with the user CAR and don't see the user DEVICE in others users from SQL Developer A: you need to grant access to user CAR for the tables created by DEVICE . login using DEVICE user and grant access to the tables CAR should be able to access using sql like below GRANT SELECT , UPDATE , INSERT ON TABLE_NAME TO CAR;
[ "stackoverflow", "0031269643.txt" ]
Q: Match two arrays to get value from second array I have two arrays. $queue_ids and $subscriber_results. $queue_ids outputs: Array ( [0] => 3 [1] => 4 [2] => 5 ) $subscriber_results outputs: Array ( [0] => Array ( [id] => 3 [email] => [email protected] [subscribed] => 1436264818 ) [1] => Array ( [id] => 4 [email] => [email protected] [subscribed] => 1436265909 ) [2] => Array ( [id] => 5 [email] => [email protected] [subscribed] => 1436265919 ) ) I need to match the two arrays to get the email record for those keys in the $queue_ids array, from the $subscriber_results array. I tried using array_keys() but couldn't get it to work. Is anyone able to show me how I could do this? A: you can use in_array for this . try to use above code <?php $matched=array(); foreach($subscriber_results as $key=>$val) { if(in_array($val['id'],$queue_ids)) { $matched[]=$val['email']; } } print_r($matched); ?>
[ "stackoverflow", "0015989312.txt" ]
Q: Change Layout-background on click programmatically I can change the background of a LinearLayout via xml by writing android:background="@drawable/overview" to my LinearLayout. However I can't do that programmatically. I tried following: LinearLayout horizontal_menu = new LinearLayout(this); ... horizontal_menu.setBackgroundResource(getResources().getInteger(R.drawable.overview)); and also that source of code: horizontal_menu.setBackground(getResources().getDrawable(R.drawable.overview)); First try throws an RuntimeException at runtime, the second line seems to do nothing -> no errors, no exceptions, no changing background on clicking... --> overview.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@color/half_transparent"/> <item android:state_pressed="true" android:drawable="@color/half_transparent" /> </selector> I hope that anyone can help me! Thanks! Edit: LinearLayout content = (LinearLayout)findViewById(R.id.LinearLayout); LinearLayout horizontal_menu = new LinearLayout(this); horizontal_menu.setOrientation(LinearLayout.HORIZONTAL); horizontal_menu.setBackgroundResource(getResources().getInteger(R.drawable.overv‌​iew)); content.addView(horizontal_menu); A: Set an id for layout in your layout XML file: <LinearLayout android:id="@+id/myLinearLayout" ... and then in your Activity, get LinearLayout with findViewById() as below: LinearLayout ll = (LinearLayout) findViewById(R.id.myLinearLayout); And then set background for ll with setBackground methods: ll.setBackground(...) ll.setBackgroundDrawable(...) ll.setBackgroundResource(...)
[ "stackoverflow", "0007581361.txt" ]
Q: Invoking WCF no parameter method from Biztalk orchestration I'm new at Biztalk, I've been making some tutorials, now I have an issue I don`t' find the solution but think is kind of easy I have a WCF Service method with no parameters that returns an XML file. I want to call this method from biztalk orchestration, I have used the "Add ->Generated Item –> Consume WCF Service" wizard to generate the schemas and to be able to create a request, response port. Now I just have to send a request to this service, an XML specifying the method I want to call. But I dont want to drop an XML file whits this message in a folder, read from there, and then call service. It doesnt have parameters, so I want to generate the message in the orchestration and automatically call the service with it. How can I contruct the message from "nothing" just the schema? thanks! A: you could create a request message in your Orchestration in a Message Assignment shape. Create a message type matching the request message - e.g msgRequest. In the Construct Shape, set the outgoing message to msgRequest. Go to the schema for the request and Generate an instance of that schema. Use the load xml method to assign the xDoc variable to the msgRequest message. the expression would be something like: xDoc = new System.XmlDocument(); xDoc.LoadXml("<GeneratedRequest/>"); Message_1.body = xDoc;
[ "stackoverflow", "0000123958.txt" ]
Q: How to get/set logical directory path in python In python is it possible to get or set a logical directory (as opposed to an absolute one). For example if I have: /real/path/to/dir and I have /linked/path/to/dir linked to the same directory. using os.getcwd and os.chdir will always use the absolute path >>> import os >>> os.chdir('/linked/path/to/dir') >>> print os.getcwd() /real/path/to/dir The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time. A: The underlying operational system / shell reports real paths to python. So, there really is no way around it, since os.getcwd() is a wrapped call to C Library getcwd() function. There are some workarounds in the spirit of the one that you already know which is launching pwd. Another one would involve using os.environ['PWD']. If that environmnent variable is set you can make some getcwd function that respects it. The solution below combines both: import os from subprocess import Popen, PIPE class CwdKeeper(object): def __init__(self): self._cwd = os.environ.get("PWD") if self._cwd is None: # no environment. fall back to calling pwd on shell self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() self._os_getcwd = os.getcwd self._os_chdir = os.chdir def chdir(self, path): if not self._cwd: return self._os_chdir(path) p = os.path.normpath(os.path.join(self._cwd, path)) result = self._os_chdir(p) self._cwd = p os.environ["PWD"] = p return result def getcwd(self): if not self._cwd: return self._os_getcwd() return self._cwd cwd = CwdKeeper() print cwd.getcwd() # use only cwd.chdir and cwd.getcwd from now on. # monkeypatch os if you want: os.chdir = cwd.chdir os.getcwd = cwd.getcwd # now you can use os.chdir and os.getcwd as normal.
[ "stackoverflow", "0030925260.txt" ]
Q: When to use a Mock v. Stub, or neither? I've been reading up on Mocks and Stubs, their differences and uses. I'm still a bit confused, but I think I've got the jist of it. Now I'm wondering about applications. I can see the use in creating "fake" objects in testing scenarios where the actual objects are too complicated to haul around to test one aspect. But let's consider my application: I'm working on a computational geometry library. Our library defines points, lines, linesegments, vectors, polygons, and polyhedra, along with a bunch of other objects and all the usual geometric operations. Any given object is stored as a list of points or directions, or lower level objects. But none of these objects takes more than a few milliseconds to generate. When I'm testing this library, does it make sense to use Mocks/Stubs anywhere? Right now we just use particular test cases. We're calling them stubs, but I don't think they meet the technical definition of a stub. What do you think better vocab for that would be? "TestCases"? "Examples"? SourceCode: https://bitbucket.org/Clearspan/geometry-class-library/src Edit: Note that we're striving for immutability in all our geometry objects, so it only makes sense to test the results of operations, but not state changes to the initial objects. A: As a rule of thumb, use Mocks when you need to simulate behavior, and stubs when the only thing that matters in your test is the state of the object you're communicating with. Taking into consideration the edit you made to your post, when you need to receive an immutable object use a stub, but when you need to call operations that object exposes then go for a mock, this way you are not prone to failing tests due to errors in another class implementation. A: The fundamental difference between mock and stub is that mock can make your test fail. Stub can't. Stub is used to guarantee correct program flow. It is never part of assert. Note that mock can also be used to guarantee flow. In other words, every mock is also a stub, and stub is never a mock. Because of such overlapping responsibilities nowadays you don't see much distinction between mock and stub and framework designers go for more general terms (like fake, substitute or catch-all mock). This realization (mock - assert, stub - flow) helps us narrow down some usage scenarios. To start with the easier one... Mock As I mentioned mocks are used in asserts. When the expected behavior of your component is that it should talk to this other component - use mock. All those emailSender.SendEmail(email); endOfDayRunner.Run(); jobScheduler.ScheduleJob(jobDetails); can be only tested by asking "Did it call ScheduleJob with such and such parameters?" This is where you go for mock. Usually this will be mock's only usage scenario. Stub With stub it's a bit different. Whether to use stub or not is a design question. Once you follow regular loosely coupled, dependency injection-based design, eventually you will end up with a lot of interfaces. Now, when in test, how do return value from interface? You either stub it or use real implementation. Each approach has its pros and cons: with library-generated stubs, your tests will be less brittle but might require more up-front work (setting up stub and such) with real implementations, setup work is already done but when Angle class changes CoordinateSystem might fail... Is such behavior desirable or not? Is it? Which one to use? Both! It all depends on... Unit of work We arrived at final and the actual part of the problem. What is the scope of your unit test? What is the unit? Can CoordinateSystem be detached from its inner workings and dependencies (Angle, Point, Line) and can they be stubbed? Or more importantly, should they be? You always need to identify what your unit is. Is it CoordinateSystem alone or perhaps Angle, Line and Point play important part of it? In many, many cases, the unit will be formed by both method and its surrounding ecosystem, including domain objects, helper classes, extensions or sometimes even other methods and other classes. Naturally, you can separate them and stub all the way around but then... is it really your unit?
[ "askubuntu", "0000884965.txt" ]
Q: Can't kill processes of a user One of the users of our server managed to hang his xRDP connection somehow. Now he can't connect any longer. Each time he tries to connect, he gets a blank black screen. I figured this is due to some error in the X11rdp process he was running, so I tried to kill the process using killall X11rdp, kill -KILL, kill -s SIGCHLD, kill -9... Then I tried killing all the processes of that user using pkill -u. But they won't die. None of them. I literally have no idea what is happening. Any ideas? P.S. Of course, I executed all these commands as root. A: Run this on the processes the user has. If it has problems on a particular process it'll show you the parent process. You can then run the script on the parent process. I haven't found a process that it won't subsequently kill yet. Create the bash script with: $ gedit killprocess.sh The script: #!/bin/bash if [[ ! "$1" ]] then echo "Parameter error... exiting..." exit fi process=$1 count=0 results=0 while [[ $(ps h -fp $process) ]] do kill -9 $process str1=$(ps h -fp $process|awk '{print "["$2"]["$3"]"}') results=$? echo -ne "[$str1]Response:$results..." ret2=$(ps -ef | egrep "\s$process\s" | awk '$2 == '$process'{print "["$2"]["$3"]"}') if [ ! "$ret2" ] then break fi if [[ -f stop ]] then exit fi if [[ $((count++)) -gt 5 ]] then echo -ne "\nGiving up... exiting...\n" exit fi sleep 20 done echo -ne "\n" Make it executable: $ chmod +x killprocess.sh Run the script: $ sudo ./killprocess.sh