qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
47,239,444 | I have this JSON file that I'm trying to convert to CSV to harvest data. However the output I get is far from correct.
So far I have:
```
import csv
import json
infile = open("top40nl.json", "r")
outfile = open("top40nl.csv", "w")
writer = csv.writer(outfile)
for row in json.loads(infile.read()):
writer.writerow(row)
```
Using this type of JSON data (e.g.):
```
{
"info": "SQLite Pro Result Set",
"data": [
{
"top40_SK": "118899",
"song_title": "Sorry",
"artist": "Justin Bieber",
"year_released": "2015",
"year": "2016",
"week": "1",
"position": "1",
"prev_position": "1",
"weeks_in_top40_v1": "10",
"weeks_in_top40_v2": "10",
"highest_reached_position": "1",
"total_points": "775",
"top40url": "https://www.top40.nl/top40/2016/week-1"
},
{
"top40_SK": "118900",
"song_title": "Love yourself",
"artist": "Justin Bieber",
"year_released": "2015",
"year": "2016",
"week": "1",
"position": "2",
"prev_position": "2",
"weeks_in_top40_v1": "6",
"weeks_in_top40_v2": "6",
"highest_reached_position": "1",
"total_points": "764",
"top40url": "https://www.top40.nl/top40/2016/week-1"
}
]
}
```
All of the above worked so far, however this is my output:
`i,n,f,o`
`d,a,t,a`
Any idea how to solve this? | 2017/11/11 | [
"https://Stackoverflow.com/questions/47239444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8924542/"
] | I don't understand why you want a CSV file instead of JSON, but here's how you can extract the dicts from each of the data lists and write them to CSV. To keep the example simple, I just write the output to `sys.stdout` instead of to a disk file.
```
import json
import csv
import sys
JSON = '''\
{
"info": "SQLite Pro Result Set",
"data": [
{
"top40_SK": "118899",
"song_title": "Sorry",
"artist": "Justin Bieber",
"year_released": "2015",
"year": "2016",
"week": "1",
"position": "1",
"prev_position": "1",
"weeks_in_top40_v1": "10",
"weeks_in_top40_v2": "10",
"highest_reached_position": "1",
"total_points": "775",
"top40url": "https://www.top40.nl/top40/2016/week-1"
},
{
"top40_SK": "118900",
"song_title": "Love yourself",
"artist": "Justin Bieber",
"year_released": "2015",
"year": "2016",
"week": "1",
"position": "2",
"prev_position": "2",
"weeks_in_top40_v1": "6",
"weeks_in_top40_v2": "6",
"highest_reached_position": "1",
"total_points": "764",
"top40url": "https://www.top40.nl/top40/2016/week-1"
}
]
}
'''
data = json.loads(JSON)
keys = data["data"][0].keys()
writer = csv.DictWriter(sys.stdout, fieldnames=keys)
writer.writerow(dict(zip(keys, keys)))
for d in data["data"]:
writer.writerow(d)
```
**output**
```
top40_SK,song_title,artist,year_released,year,week,position,prev_position,weeks_in_top40_v1,weeks_in_top40_v2,highest_reached_position,total_points,top40url
118899,Sorry,Justin Bieber,2015,2016,1,1,1,10,10,1,775,https://www.top40.nl/top40/2016/week-1
118900,Love yourself,Justin Bieber,2015,2016,1,2,2,6,6,1,764,https://www.top40.nl/top40/2016/week-1
``` | *here it goes the simplest one using pandas library*
```
import pandas as pd
import json
with open('top40nl.json') as fi:
data = json.load(fi)
df = pd.DataFrame(data=data)
df.to_csv('top40nl.csv', index=False)
``` |
29,540,612 | I use a 3rd-party javascript library (I'll just refer to it as "the jslib") in my web page that, when a certain link is clicked, dynamically generates and displays an iframe on my page. I am trying to override some styles on the iframe. In some cases I can do it, but in 1 case I cannot. Take a look:

Notice that my `border` style (lower, inside styles.css line 22) is being overridden by the jslib's `border` style of "0".
Here is the jslib reference:
```
<script type="text/javascript" src="https://www.paypalobjects.com/js/external/dg.js"></script>
```
I have tried the following approaches:
* I placed the style in my css file as you see above.
* I placed my css file below the jslib's reference in my page, hoping to override those styles.
* I placed the style inside a `<style></style>` block directly in my html page.
The jslib has no css file and no inline styles. All styles are built from within the js file that I reference in my page.
Is there a way with plain css to override that border style somehow? If not, there must be some way with jquery. But if I attempt it with jquery, I wouldn't know how to hook in to the jslib. Or if I try to hook into the link click that triggers everything, jquery may try to apply the style before the iframe has been created, etc. Not sure about where to hook, how to hook, and the timing of object creation.
What is the best approach to do this? Plain old CSS would be awesome, but if that's not possible, jquery styling would be welcomed. | 2015/04/09 | [
"https://Stackoverflow.com/questions/29540612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1136267/"
] | I would go for a better specified selector like:
```
body #PPDGFrame .panel iframe {
/* Your style here */
border: 2px solid #666;
}
```
I prefer to avoid using important, you will end up in a important hell, this is due to [**selector priorities**](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity)
So what do i mean by *selector priorities* - lets make a small example:
```
<html>
<body>
<div id="wrap" class="wrap">
<div class="element"></div>
</div>
</body>
</html>
```
if you have HTML as above, then you need to select the "div.element" you can do it very simple.
```
.element { /* some style */ }
```
How did paypal do it, they inject a inline stylesheet which had a id selector which is stronger than a class selector
```
#wrap .element { /* some style */ }
```
So how to overwrite this, you simple make a "stronger" selector
```
body #wrap .element { /* some style */ }
```
I prefer to use bem syntax on my classes to use "lightest versions of selectors", read more about BEM-syntax **[here](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/)**
If you need to do stuff after the content in the Iframe has been loaded, you will need to check for a callback in "the jslib" that your using and when it returns you'll do stuff
**Why not use !important**
In my opinion i pref to use it as a debugger tool instead of a production tool, i rarely use it to overwrite some javascript set style, which i also think is wrong when you can set a class that can hold the style instead.
If you end up having 5 or 10 similar selectors with *!important* on it starts to get confusing. | Try this.
`border: 2px solid #666 !important;`
The important flag prioritizes it over all other definitions, except other `!important` definitions. |
2,159,059 | I am trying to do a string replace for entire file in PHP. My file is over 100MB so I have to go line by line and can not use `file_get_contents()`. Is there a good solution to this? | 2010/01/29 | [
"https://Stackoverflow.com/questions/2159059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232495/"
] | If you aren't required to use PHP, I would highly recommend performing stuff like this from the command line. It's by far the best tool for the job, and much easier to use.
In any case, the [`sed` (Stream Editor)](https://en.wikipedia.org/wiki/Sed) command is what you are looking for:
```
sed s/search/replace oldfilename > newfilename
```
If you need case-insensitivity:
```
sed s/search/replace/i oldfilename > newfilename
```
---
If you need this to perform dynamically within PHP, you can use `passthru()`:
```
$output = passthru("sed s/$search/$replace $oldfilename > $newfilename");
``` | something like this?
```
$infile="file";
$outfile="temp";
$f = fopen($infile,"r");
$o = fopen($outfile,"a");
$pattern="pattern";
$replace="replace";
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( strpos($pattern,"$line") !==FALSE ){
$line=str_replace($pattern,$replace,$line);
}
fwrite($o,$line);
}
}
fclose($f);
fclose($o);
rename($outfile,$infile);
``` |
11,151,782 | While including the simple HTML DOM library, I get the warnings:
Warning: file\_get\_contents() [function.file-get-contents]: php\_network\_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\simple\_html\_dom.php on line 70
Warning: file\_get\_contents(http://www.google.com/) [function.file-get-contents]: failed to open stream: php\_network\_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\simple\_html\_dom.php on line 70
The line 70 in simple\_html\_dom.php file(downloaded from <http://sourceforge.net/projects/simplehtmldom/files/latest/download>) is
```
$contents = file_get_contents($url, $use_include_path, $context, $offset);
```
Also 1 error:
Fatal error: Call to a member function find() on a non-object in C:\xampp\htdocs\domdoc2.php on line 15
where line 15 of the code(below) is
```
foreach($html->find('img') as $element)
```
The web page i was referring in my code below is google.com
Code follows:
```
<?php
include('simple_html_dom.php');
$html = new simple_html_dom();
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
?>
```
What am I doing wrong?? | 2012/06/22 | [
"https://Stackoverflow.com/questions/11151782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1458514/"
] | This is because your host was unable to resolve DNS, this happens when simplehtmldom uses file\_get\_contents instead of curl.
PHP Simple HTML DOM Parser is a great HTML parsing PHP class BUT it is slow since it uses
file\_get\_contents (which is disabled on almost all configurations) instead of cURL (4-5 times faster and with lots of options, almost every server has it).
Only file\_get\_contents is replaced so you can safely overwrite previous version and everything will work as before, only faster
Link to source code:
<http://webarto.com/static/download/simple_html_dom.rar>
```
//output should be
/intl/en_ALL/images/srpr/logo1w.png
http://www.google.com/webhp?hl=en&tab=ww
http://www.google.com/imghp?hl=en&tab=wi
http://maps.google.com/maps?hl=en&tab=wl
https://play.google.com/?hl=en&tab=w8
http://www.youtube.com/?tab=w1
http://news.google.com/nwshp?hl=en&tab=wn
https://mail.google.com/mail/?tab=wm
https://docs.google.com/?tab=wo
http://www.google.com/intl/en/options/
https://www.google.com/calendar?tab=wc
http://translate.google.com/?hl=en&tab=wT
http://www.google.com/mobile/?tab=wD
http://books.google.com/bkshp?hl=en&tab=wp
https://www.google.com/offers/home?utm_source=xsell&utm_medium=products&utm_campaign=sandbar&tab=wG#!details
https://wallet.google.com/manage/?tab=wa
http://www.google.com/shopping?hl=en&tab=wf
http://www.blogger.com/?tab=wj
http://www.google.com/reader/?hl=en&tab=wy
http://www.google.com/finance?tab=we
http://picasaweb.google.com/home?hl=en&tab=wq
http://video.google.com/?hl=en&tab=wv
http://www.google.com/intl/en/options/
https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.com/
http://www.google.com/preferences?hl=en
/preferences?hl=en
/url?sa=p&pref=ig&pval=3&q=http://www.google.com/ig%3Fhl%3Den%26source%3Diglk&usg=AFQjCNFA18XPfgb7dKnXfKz7x7g1GDH1tg
http://www.google.com/history/optout?hl=en
/advanced_search?hl=en
/language_tools?hl=en
/intl/en/ads/
/services/
https://plus.google.com/116899029375914044550
/intl/en/about.html
/intl/en/policies/
```
However if you are completely new to HTML parsing in PHP Please Consider reading : [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php/3577662#3577662) | That's not in any way related to `simple_html_dom`. Your server has no internet access and it fails to resolve `google.com`. Check the DNS settings and maybe the firewall. |
113,693 | Using OpenLayers 3, I cannot get this message to go away:
```
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myserver:8085/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:view1&maxFeatures=1&outputFormat=JSON. This can be fixed by moving the resource to the same domain or enabling CORS.
```
This is the code:
```
// Ol3 only supports Projections "EPSG:4326" and "EPSG:3857". For every other projection you need proj4js
proj4.defs("EPSG:2236", "+proj=tmerc +lat_0=24.33333333333333 +lon_0=-81 +k=0.999941177 +x_0=200000.0001016002 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs");
// Leases Layer
var myLayer = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:2236',
url: 'http://myserver:8085/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:view1&maxFeatures=1&outputFormat=JSON',
crossOrigin: null
})
});
// View
var view = new ol.View({
projection: 'EPSG:2236',
center: [0, 0],
zoom: 4
});
// Map
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [myLayer],
view: view
});
```
I have tried setting the crossOrigin setting to:
```
crossOrigin: null
crossOrigin: 'null'
crossOrigin: 'anonymous'
```
I only see the zoom in/out control but the layer is not rendered.
---
I went with simon's option 3 below. I enabled CORS in GeoServer by copying the necessary jetty-servlets jar files and enabling it in the \WEB-INF\web.xml:
```
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
<init-param>
<param-name>allowedOrigins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<filter-pattern>/*</filter-pattern>
</filter-mapping>
```
After I did that, I tested the page again and receive the same error:
```
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myserver:8085/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:view1&maxFeatures=1&outputFormat=JSON. This can be fixed by moving the resource to the same domain or enabling CORS.
```
Looks like I am still missing something. Do I have to do anything from the OpenLayers Side?
---
I ended up getting rid of Jetty and uninstalling GeoServer completely. The problem is when you install the geoserver windows installer, it installs a version of jetty that is 4 years old! (Jetty version 6.1.8) Even though I had copied the jar files for CORS, it is only supported in Jetty 7+.
I found out that you can install a WAR file. I decided to use Tomcat since that is what GeoServer is mostly tested on according to this note from the GeoServer website:
Note GeoServer has been mostly tested using Tomcat, and therefore these instructions may not work with other container applications.
These are the instructions for installing the WAR file:
<http://docs.geoserver.org/stable/en/user/installation/war.html>
This is a nice how-to video also:
<https://www.youtube.com/watch?v=YEOA8WWWVCw>
After you complete the install, you then enable CORS:
<http://enable-cors.org/server_tomcat.html> | 2014/09/12 | [
"https://gis.stackexchange.com/questions/113693",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/36275/"
] | I ran into CORS errors whilst using GetFeatureInfo requests to get info from a WMS geoserver layer in my OpenLayers map.
Answer as of May 2020:
<https://docs.geoserver.org/latest/en/user/production/container.html#enable-cors> | The crossOrigin-setting does only (?) exist for ol.source.TileImage. (<http://openlayers.org/en/master/apidoc/ol.source.TileImage.html> - untick "Stable only" in the upper right corner). ol.source.GeoJSON doesn't have a crossOrigin setting, because you can't access JSON via a cross-site requests.
You have different ways around this:
1. use a web proxy for ajax calls if you don't have access to the server, where the json comes from. (Search for example for ajax proxy)
2. you could use jsonp if you have access to the server. This normally is the prefered solution but i don't know if it does work with geojson and you might have to overwrite the loader function (<http://en.wikipedia.org/wiki/JSONP> -- [How to get JSON from Geoserver using AJAX request](https://gis.stackexchange.com/questions/34892/how-to-get-json-from-geoserver-using-ajax-request) -- <http://openlayers.org/en/master/examples/vector-osm.js> <- an example for using a custom loader function)
3. enable cross-origin requests on the server. (<http://en.wikipedia.org/wiki/Cross-origin_resource_sharing>)
4. if the data is static, download it and put it on your own server (just mentioning for completness)
similar problem, but not geo related: <https://stackoverflow.com/questions/5549068/json-how-do-i-make-cross-domain-json-call> |
41,234,446 | I have a scala program that runs for a while and then terminates. I'd like to provide a library to this program that, behind the scenes, schedules an asynchronous task to run every `N` seconds. I'd also like the program to terminate when the `main` entrypoint's work is finished without needing to explicitly tell the background work to shut down (since it's inside a library).
As best I can tell the idiomatic way to do polling or scheduled work in Scala is with Akka's `ActorSystem.scheduler.schedule`, but using an ActorSystem makes the program hang after `main` waiting for the actors. I then tried and failed to add another actor that `join`s on the main thread, seemingly because ["Anything that blocks a thread is not advised within Akka"](https://stackoverflow.com/questions/25789989/thread-sleep-inside-scala-actors)
I could introduce a custom dispatcher; I could kludge something together with a polling `isAlive` check, or adding a similar check inside each worker; or I could give up on Akka and just use raw Threads.
This seems like a not-too-unusual thing to want to do, so I'd like to use idiomatic Scala if there's a clear best way. | 2016/12/20 | [
"https://Stackoverflow.com/questions/41234446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3562538/"
] | Okay, so if you have a one-dimensional hash table and an array for the priority of keys, then you can use an algorithm like this to select the first one available:
```
function grab(hash, keyPriority) {
var value;
keyPriority.some(function (key) {
if (hash.hasOwnProperty(key)) { // check if the property exists
value = hash[key];
return true; // break out of loop
}
});
return value;
}
```
usage:
```
grab({ c: 3, d: 4 }, ['a', 'b', 'c', 'd']) // 3
```
You can modify this to work by truthy values, or undefined/null by changing `hash.hasOwnProperty(key)` to `hash[key]` or `hash[key] != null` respectively. | If you are fine with using a bit of `JQuery` then the following code snippet should do the job I guess.
```
$.each(JSONObj, function(key, value){
if (!(value === "" || value === null)){
myValue = value;
return false; //to break the loop once a valid value is found
}
});
```
This will assign the first valid value to your variable `myValue` and will also exit the loop once a valid value is found. |
1,367,025 | Could you please help - as I have a weird situation that when I enter a number 22222.09482 in cell then I see a different number 22222.0948199999 in the formula bar. Below is the snapshot of the problem.

I see the same behavior when I enter the following numbers:
```
22222.09482
33333.09482
44444.09482
55555.09482
```
but when I enter 11111.09482 and 66666.09482, 77777.09482.. until 99999.09482 then they shows correctly. I am not sure is this related to rounding ? I didn't setup any rounding profiles. Could you please help me in resolving the issue. | 2018/10/15 | [
"https://superuser.com/questions/1367025",
"https://superuser.com",
"https://superuser.com/users/954171/"
] | As I'm sure you know, computers internally work only using zeros and ones (a.k.a. bits) and have a fixed number of bits to represent a value (usually 64 bits nowadays). That means that the number of different values that can be represented is 2 to the 64th power. That's a huge number, sure, but the number of *possible* values is finite, so not all numbers can be represented. When it encounters a number it can't represent exactly, it automatically gets replaced by the closest one that it *can* represent. That is what you're seeing. | Computers do their math in binary, and almost always use floating point for non-integer values. The only fractional values which can be represented precisely in floating point must be a sum of some combination of fractional powers of 2 (1/2, 1/4, 1/8, 1/16, 1/32,...) terminating at the designed-in precision limit (usually 53 bits). These values don't always have a tidy or exact representation in decimal, and conversely, not all fractional values you can represent exactly in decimal will have an exact representation in binary. For example: 0.1. It can't be represented as a sum of fractional powers of 2 that does not go on forever.
When you enter a decimal value into your spreadsheet, it will be converted and stored in binary, and cases such as you described, will become the closest approximation that can be represented in binary. When displayed, it is converted back to decimal, again requiring an approximation, which might not convert back to exactly the same representation you entered.
Why 53 bits (give or take)? Because the typical standard for storing "double precision" floating point uses 64 bits, in which there is a mantissa (also called significand), a sign indicator, and an exponent. The exponent is usually allocated 10 bits, the sign takes one, leaving 53 for the mantissa. This is for storage. Calculations are usually done using 80 bits and rounded back.
There are situations where computers will work in base 10, especially when working with monetary values where rounding artifacts are not acceptable. |
17,462 | I've only done a small amount of reading on the middle ages, and on the history of Western philosophy, but from what I can glean education and religion were tightly coupled during the period, so most thought coming from that time came from religious thinkers.
It *seems* to me that secular thought started to come to the fore-front again during the late early-modern period, toward the enlightenment, but, if it ever existed during the middle ages it was mostly hidden away, or thinly veiled.
So, were there prominent secularists during the middle ages in which is now modern day Europe? Who were they? | 2014/12/09 | [
"https://history.stackexchange.com/questions/17462",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/4886/"
] | The most prominent voice for secular thinking in medieval Europe was undoubtedly Franciscan friar [Roger Bacon](http://en.wikipedia.org/wiki/Roger_Bacon) (1214-1292). Even though Bacon was a monk, the experimental work he did led many people to start thinking and believing in natural phenomenon, whereas previously the trend was consider everything the "work of God". In this way he was the first great modern voice for reason over faith and presaged the [Enlightenment](http://en.wikipedia.org/wiki/Age_of_Enlightenment).
Continuing in the vein of Bacon were such thinkers as [Nicholas of Cusa](http://en.wikipedia.org/wiki/Nicholas_of_Cusa) and [Rene Descartes](http://en.wikipedia.org/wiki/Ren%C3%A9_Descartes) who were also men of faith, but who emphasized natural phenomena and reason in their writings, thus promoting a secular view of the world.
In terms of secularist agitation, advocating the removal of the church from authority over daily life and separation of church and state, this was rare in the middle ages because it would have been considered heresy, a capital offense. A typical example of such a person was [Reginald Pecock](http://en.wikipedia.org/wiki/Reginald_Pecock) (circa 1395–1461) who was convicted of heresy and narrowly avoided being burned at the stake.
There are a number of philosophers who avoided heresy charges by simply never mentioning the church and focusing entirely on secular subjects, as though the church did not exist. An example is [Niccolo Machiavelli](http://en.wikipedia.org/wiki/Niccol%C3%B2_Machiavelli) (1469 – 1527), who was never charged with heresy, but nevertheless the church banned all of his books. Another such philosopher was [Mirandola](http://en.wikipedia.org/wiki/Giovanni_Pico_della_Mirandola), who was arrested and escaped execution for heresy only through the influence of powerful Italian nobles. | I cannot think of any examples in mediaeval Western Europe. However, the Persian philosopher Muḥammad ibn Zakariyā ar-Rāzī (died 925) taught that all religions (Christianity, Islam etc.) were taught by false prophets who received their revelations from evil spirits. The Greek philosopher Georgios Gemistos Plethon (died ca. 1452) wanted to abolish Christianity and revive the religion of the ancient Hellenes. |
22,303,828 | I am trying to create components and implement them into my JFrame from different classes within my program.
I have created a JTabbedPane, and each tab represents a class. All of the components for each tab are placed in their respective tabs.
```
//creates the JTabbedPane, and the panels. object creation.
//panelx corisponds to the tab number as well. tabbs are counted from left to right.
tabpane1 = new JTabbedPane();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JLabel searchlabel1 = new JLabel("hey");
JLabel searchlabel2 = new JLabel("hi");
panel1.add(searchlabel1);
panel1.add(searchlabel2);
//SearchFlight searchflightComp = new SearchFlight();
tabpane1.addTab("Search Flight", panel1);
tabpane1.addTab("Select Flight", panel2);
tabpane1.addTab("Flight Price", new JLabel("This is tab 1ffff"));
tabpane1.addTab("Book Ticket", new JLabel("This is tab 1fff"));
tabpane1.addTab("Book Ticket", new JLabel("This is tab fs1"));
tabpane1.addTab("Payment", new JLabel("This is tabgf 1"));
tabpane1.addTab("Booking Summary", new JLabel("This is tabgf 1"));
//added the JTabbedPane to JFrame.
frame.getContentPane().add(tabpane1);
```
this works. I am only really working with the first tab right now to get the feel for how it works ect. But I dont even know how to begin. Would I create the a panel in the other class and then return it? or extend the JFrame?
thanks guys! | 2014/03/10 | [
"https://Stackoverflow.com/questions/22303828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026473/"
] | **The basic question is "why are you calling `GetVersionExW` in the first place?" The answer to that question determines what you should do instead.**
The deprecation warning is there to give developers a heads-up about the appcompat behavior change that started in Windows 8.1. See [Windows and Windows Server compatibility cookbook: Windows 8, Windows 8.1, and Windows Server 2012](https://learn.microsoft.com/en-us/windows/win32/w8cookbook/windows-8-and-windows-server-8-compatibility-cookbook-portal). *In short, that function doesn't return what you think it returns by default.*
Historically, badly written OS version checks are the primary source of appcompat bugs for Windows OS upgrades. There've been a number of different approaches to trying to mitigate this problem (the AppVerifier version lie, the `VerifyVersionInfo` API, etc.), and this is the most aggressive to date.
The `VersionHelpers.h` mentioned in the comments are in the Windows 8.1 SDK that comes with Visual Studio 2013. They are not a new API; they are just utility code that makes use of the `VerifyVersionInfo` API introduced back in Windows 2000. These functions are for doing "You must be this high to ride this ride" style checks which are the class of version checks that are most often badly written. The code is pretty simple. For example, the `IsWindowsVistaSP2OrGreater` test is:
```
VERSIONHELPERAPI
IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
{
OSVERSIONINFOEXW osvi = {};
osvi.dwOSVersionInfoSize = sizeof(osvi);
DWORDLONG const dwlConditionMask = VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0, VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
osvi.dwMajorVersion = wMajorVersion;
osvi.dwMinorVersion = wMinorVersion;
osvi.wServicePackMajor = wServicePackMajor;
return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
}
VERSIONHELPERAPI
IsWindowsVistaSP2OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 2);
}
```
You don't need to use `VersionHelpers.h` as you could just do this kind of code yourself, but they are convenient if you are already using the VS 2013 compiler. For games, I have an article [What's in a version number?](https://walbourn.github.io/whats-in-a-version-number/) which uses `VerifyVersionInfo` to do the kind of reasonable checks one should for game deployment.
>
> Note if you are using VS 2013 with the `v120_xp` platform toolset to target Windows XP, you'll actually be using the Windows 7.1A SDK and `#include <VersionHelpers.h>` won't work. You can of course use `VerifyVersionInfo` directly.
>
>
>
The other major use of `GetVersionExW` is diagnostic logs and telemetry. In this case, one option is to continue to use that API and make sure you have the right manifest entries in your application to ensure reasonably accurate results. See [Manifest Madness](https://walbourn.github.io/manifest-madness/) for details on what you do here to achieve this. The main thing to keep in mind is that unless you routinely update your code, you will eventually stop getting fully accurate information in a future version of the OS.
>
> Note that it is recommended you put the `<compatibility>` section in an embedded manifest whether or not you care about the results of `GetVersionEx` as general best practice. This allows the OS to automatically apply future appcompat fixes based on knowing how the app was originally tested.
>
>
>
For diagnostic logs, another approach that might be a bit more robust is to grab the version number out of a system DLL like `kernel32.dll` using `GetFileVersionInfoW`. This approach has a major caveat: *Do not try parsing, doing comparisons, or making code assumptions based on the file version you obtain this way; just write it out somewhere*. Otherwise you risk recreating the same bad OS version check problem that is better solved with `VerifyVersionInfo`. This option is not available to Windows Store apps, Windows phone apps, etc. but should work for Win32 desktop apps.
```
#include <Windows.h>
#include <cstdint>
#include <memory>
#pragma comment(lib, "version.lib" )
bool GetOSVersionString( WCHAR* version, size_t maxlen )
{
WCHAR path[ _MAX_PATH ] = {};
if ( !GetSystemDirectoryW( path, _MAX_PATH ) )
return false;
wcscat_s( path, L"\\kernel32.dll" );
//
// Based on example code from this article
// http://support.microsoft.com/kb/167597
//
DWORD handle;
#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
DWORD len = GetFileVersionInfoSizeExW( FILE_VER_GET_NEUTRAL, path, &handle );
#else
DWORD len = GetFileVersionInfoSizeW( path, &handle );
#endif
if ( !len )
return false;
std::unique_ptr<uint8_t> buff( new (std::nothrow) uint8_t[ len ] );
if ( !buff )
return false;
#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if ( !GetFileVersionInfoExW( FILE_VER_GET_NEUTRAL, path, 0, len, buff.get() ) )
#else
if ( !GetFileVersionInfoW( path, 0, len, buff.get() ) )
#endif
return false;
VS_FIXEDFILEINFO *vInfo = nullptr;
UINT infoSize;
if ( !VerQueryValueW( buff.get(), L"\\", reinterpret_cast<LPVOID*>( &vInfo ), &infoSize ) )
return false;
if ( !infoSize )
return false;
swprintf_s( version, maxlen, L"%u.%u.%u.%u",
HIWORD( vInfo->dwFileVersionMS ),
LOWORD(vInfo->dwFileVersionMS),
HIWORD(vInfo->dwFileVersionLS),
LOWORD(vInfo->dwFileVersionLS) );
return true;
}
```
If there is some other reason you are calling `GetVersionExW`, you probably shouldn't be calling it. Checking for a component that might be missing shouldn't be tied to a version check. For example, if your application requires Media Foundation, you should set a "You must be this high to ride this ride check" like the VersionHelpers.h `IsWindowsVistaOrGreater` for deployment, but at runtime you should use explicit linking via `LoadLibrary` or `LoadLibaryEx` to report an error or use a fallback if `MFPLAT.DLL` is not found.
>
> Explicit linking is not an option for Windows Store apps. Windows 8.x solves this
> particular problem by having a stub `MFPLAT.DLL` and `MFStartUp` will return E\_NOTIMPL.
> See ["Who moved my [Windows Media] Cheese"?](https://walbourn.github.io/who-moved-my-windows-media-cheese/)
>
>
>
Another example: if your application wants to use Direct3D 11.2 if it is available and otherwise uses DirectX 11.0, you'd use set a `IsWindowsVistaSP2OrGreater` minimum bar for deployment perhaps using the [D3D11InstallHelper](https://github.com/walbourn/directx-sdk-samples/tree/master/InstallHelpers/D3D11InstallHelper). Then at runtime, you'd create the DirectX 11.0 device and if it fails, you'd report an error. If you obtain a `ID3D11Device`, then you'd `QueryInterface` for a `ID3D11Device2` which if it succeeds means you are using an OS that supports DirectX 11.2. See [Anatomy of Direct3D 11 Create Device](https://walbourn.github.io/anatomy-of-direct3d-11-create-device/).
If this hypothetical Direct3D application supports Windows XP, you'd use a deployment bar of `IsWindowsXPSP2OrGreater` or `IsWindowsXPSP3OrGreater`, and then at run time use explicit linking to try to find the `D3D11.DLL`. If it wasn't present, you'd fall back to using Direct3D 9--since we set the minimum bar, we know that DirectX 9.0c or later is always present.
**They key point here is that in most cases, you should not use `GetVersionEx`.**
>
> Note that with **Windows 10**, `VerifyVersionInfo` and getting the file version stamp via `GetFileVersionInfo` for kernel32.lib are now subject to the same manifest based behavior as `GetVersionEx` (i.e. without the manifest GUID for Windows 10, it returns results as if the OS version were 6.2 rather than 10.0).
>
>
>
>
> For universal Windows apps on Windows 10, you can a new WinRT API [AnalyticsInfo](https://learn.microsoft.com/en-us/uwp/api/Windows.System.Profile.AnalyticsInfo) to get a version stamp string for diagnostic logs and telemetry.
>
>
> | you can disable this warning and use GetVersionEx anyway by adding:
```
#pragma warning(disable : 4996)
``` |
7,267,116 | There is an object, which can be initialized by id or by name.
How it should be handled?
```
class user
{
function __construct($id_or_name)
{
if ( is_numeric($id_or_name) )
{
$this->id = $id_or_name;
$this->populate_by_id($this->id)
}
else
{
$this->name = $id_or_name;
$this->populate_by_name($this->name)
}
}
...
}
$user1 = new user('Max');
$user2 = new user(123);
```
Is it ok for general practice? | 2011/09/01 | [
"https://Stackoverflow.com/questions/7267116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159982/"
] | IMHO, it's terrible. Introuce two static "fabric methods", one receive `string`, other - `integer`. And construct your object differently:
```
class user
{
//you might want make it private
function __construct($id_or_name)
{
//common logic
}
static function construct_by_name($name){
$result = new self();
$result->name = $name; //note you are in the same class, so you may directly assign private variables
$result ->populate_by_name($result ->name);
return $result;
}
static function construct_by_id($id){
$result = new self();
$result->id= $id; //note you are in the same class, so you may directly assign private variables
$result ->populate_by_id($result ->id);
return $result;
}
}
``` | So a user can't be named 123? Do you catch that in your registration form? ;-) Since it's not clear, as an objective reader of that code, to see what the constructor does, I would change it.
Why don't you use a basic constructor which does less, and call the appropriate method (either `retreive_by_id()` or `retreive_by_name()` to retreive the user? |
33,107,790 | From hours I am trying to find the root cause for one of tricky customer issue. Help is appreciated.
None of the clicks events in client Chrome browser is firing.
But when we call the JavaScript method from console it fires!
[](https://i.stack.imgur.com/sVzS0.png)
In the attached image you can see, how I triggered the event
Tried removing "data-bind" attribute and added simple "onClick", still does not work. none of the buttons in web site working :(
Here is code
```
<div class="row butrow p0 pb20 pt10">
<div class="col-md-12 text-left ">
<div class="form-group">
<div class="col-md-6 text-left pl0">
<input type="button" style="display: inline;" class="resbut" value="@SchedulingSystem.Clear" id="btnClear" data-bind="click:AppointmentView.ClickClear"/>
<input type="button" style="display: none;" class="resbut" value="@SchedulingSystem.SkipNAdd" id="btnSkipNAdd" data-bind="click:AppointmentView.ClickSkipNAdd"/>
</div>
<div class="col-md-6 text-right">
<input type="button" data-bind="click:AppointmentView.SelectSearchCustomer" value="@SchedulingSystem.Select" class="subbut" id="btnSelectSearchCustomer"/>
<button id="btnSearchCustomer" type="button" data-bind="click:AppointmentView.SearchCustomer" class=" resbut"> @SchedulingSystem.Search_Customer</button>
<input type="button" style="display: none;" class="resbut" value="@SchedulingSystem.AddNewCustomer" id="btnAddNewCustomer" data-bind="click:AppointmentView.ClickAddNewCustomer"/>
</div>
</div>
</div>
```
None of them are getting fired.
**In IE and FireFox all buttons working as expected, issue is only on chrome**
**Solution**
Laptop was touch screen based!!
1.Type below in chrome browser :
chrome://flags/#touch-events
2.In the enable touch events section ,please select "Disable" from the drop down.
3.Click on "Relaunch Now" | 2015/10/13 | [
"https://Stackoverflow.com/questions/33107790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407094/"
] | **Answer**
Since the user laptop was "**HP Elitebook 840**",it was touch screen enabled.
**So solution was disabling the touch screen**
1.Type below in chrome browser :
chrome://flags/#touch-events
2.In the enable touch events section ,please select "Disable" from the drop down.
3.Click on "Relaunch Now" | I will jump to an empty pool here and do a wild guess as you did not provide any piece of code, check that those links don't have `pointer-events: none;` set in the css. That will prevent any click handler from being executed. |
50,544,907 | I read that anything between triple quotes inside print is treated literal so tried messing things a little bit. Now I am not able to get above statement working. I searched internet but could not find anything.
statement:
```
print("""Hello World's"s""""")
```
Output I am getting:
```
Hello World's"s
```
Expected output:
```
Hello World's"s""
``` | 2018/05/26 | [
"https://Stackoverflow.com/questions/50544907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2570189/"
] | `print("""Hello World's"s""""")` is seen as `print("""Hello World's"s""" "")` because when python find `"""` it automatically ends the previous string beginning with a triple double-quote.
Try this:
```
>>> print("a"'b')
ab
```
So basically your '"""Hello World's"s"""""' is just `<str1>Hello World's"s</str1><str2></str2>` with str2 an empty string. | Maybe this is what you are looking for?
```
print("\"\"Hello World's's\"\"")
```
Output:
```
""Hello World's's""
``` |
167,807 | **A strange concept which I came up with after realizing that vampires, werewolves and zombies are basically created by an infection from a virus. This has lead me to brainstorm how I could make a monster formed by an already existing disease. A monster that would be human or animal and possess attributes of the disease they were infected by.**
I am aware that this is unlikely in the real world, but I am curious as to how this different origin would affect the monsters. Cancer is a very tempting option because it is naturally occurring in our bodies everyday. This lead to an interesting vampire variant that draws from its cancer properties.
What interests me is the cause and effect of the disease and the resulting monster. **What would it look like? How would it work? How does it behave?** Wether or not this is possible is not a concern since we already have the X-men that defy biology, so I will not have much competition in realism. | 2020/02/07 | [
"https://worldbuilding.stackexchange.com/questions/167807",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/-1/"
] | Monsters draw on our fears
==========================
Various monster stories are rooted in key fears in the human psyche (at least partially). Zombies are often the fear of outsider hordes destroying our way of life. Werewolves can be the fear of not truly knowing someone, of the possibility that danger lurks under their skin, just waiting for the right time to be unleashed (anyone with alcoholic or abusive partners or family can understand that one).
What is cancer the fear of? It’s the fear of inevitability, it’s the fear of aging, it’s the fear of your own body turning against you. It can happen to anyone over time, or quickly if they’re affected by some toxin (or radiation). What else fulfills this purpose? Sin and corruption!
A cancer monster in a fantasy world would come from the Propensity Towards Evil, seeded in every human in different amounts. Over time, even small evil deeds add up, and when they cross a certain threshold, the Evil that was latent in you comes to life, and begins to warp your body and mind further and further towards Evil. You grow horns, your eyes turn red, and your once-noble goals are forgotten. It happens to the noblest and the wickedest, the strongest and the weakest. | I heard about a tumor whose cells started to differentiate into developed features like the starts of eyes and a nose.
I can't find the specific case study, but in general they are apparently called "teratomas."
Important notes: cancer is not caused by one specific thing. There are a million different ways to develop cancer, stemming from mutations oftentimes in the genes coding for proteins involved in cell cycle regulation. Cancer is unrestricted growth of cells, and often has stem-cell like characteristics.
Taking things to the extreme, as is your job as the writer here, it is not impossible (but has and will? never happen in real life) that a single cancer cell gives rise to a tumor that is totipotent, or at least pleuripotent (meaning the cell can divide and subsequently differentiate into all the necessary tissues for an organism to function).
Here's a neat idea, but plant cells are generally totipotent (given the right laboratory conditions including hormones etc., you can make an entire plant from any old living plant cell) and plants also get cancer. That's where I would start!
Best of luck, and hit me up if you want more details, but note I know very little about plant bio compared to animals/bacteria/fungi. |
43,326 | I am learning Cell Fracturing following [this video](https://www.youtube.com/watch?v=xWIxOenYPYo).
But just like Mr Jee in the comments section, my model breaks as soon as I play the animation in Games Engine.

The author of the video talks in his answer about linking the fragments together with Rigid Body Constraints set as "breakable", but I am having a hard time understanding how to constrain objects together, I tried selecting one then the rest and looked for "copy from active" but didn't find it, or joining the blocks, that didn't work either.
Here's the setup in Game engine:
[](https://i.stack.imgur.com/BnkHs.png)
I know I could also just trick and use the shape that's on the right until the object touches the ground, but I'd like to do it in physics as much as I can.
I installed "[Bullet Constraints Tool](http://blenderartists.org/forum/showthread.php?275823-WIP-Bullet-Constraints-Tools-0-3-7)" and played around with it, but it didn't change anything.

The idea is to know what steps to follow to make an object shatter when it hits another object, ideally with Cell Fracture (comments about other ways to do this are also welcome).
**.blend file**
[](https://blend-exchange.giantcowfilms.com/b/1047/) | 2015/12/19 | [
"https://blender.stackexchange.com/questions/43326",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/18166/"
] | Why is it exploding?
--------------------
The model explodes, because the game engine (BGE) detects an impulse from all objects against other and so every body is repelled. The impulses are calculated by BGE because the intersection of of all parts' collision bounds at the start point (here: frame 40) is interpreted as an impact. [Read more about collision detection](https://en.wikipedia.org/wiki/Collision_detection)
What's the solution?
--------------------
Use a larger margin at the cell fracture options [](https://i.stack.imgur.com/2v3im.gif)
Additionally choosing the right collision shape might also help. In most cases `Convex hull` is just fine. [](https://i.stack.imgur.com/uruQd.gif) | the breaking constraint is only availible in upbge fork of blender
<https://upbge.org/> |
39,795,750 | I have a tab delimited data frame with a final column containing nested information that is '|' delimited. Note that all rows maintain this nested parenthetical structure preceded by 'REP='
```
col1 col2 col3 col4
ID1 text text text...REP=(info1|info2|info3)
ID2 text text text...REP=(info1|info2|info3)
```
I would like to process this last column such that all info inside the parenthetical is a new column:
```
col1 col2 col3 col4 newcol newcol2 newcol3
ID1 text text text info1 info2 info3
ID2 text text text info1 info2 info3
```
I would think that an AWK command would be useful but am having trouble structuring this appropriately. Any help would be much appreciated. | 2016/09/30 | [
"https://Stackoverflow.com/questions/39795750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5437137/"
] | `perl` one liner, doesn't modify the header though
```
$ cat ip.txt
col1 col2 col3 col4
ID1 text text text REP=(info1|info2|info3)
ID2 text text text REP=(info1|info2|info3)
$ perl -pe 's/\s*REP=\(([^)]+)\)/"\t".$1=~tr#|#\t#r/e' ip.txt
col1 col2 col3 col4
ID1 text text text info1 info2 info3
ID2 text text text info1 info2 info3
```
* `\s*REP=\(([^)]+)\)` zero or more whitespaces, followed by `REP(` followed by capture group to extract characters other than `)` and finally a `)`
* `e` modifier allows to use Perl code in replacement section
* `$1=~tr#|#\t#r` change `|` to tabs from the captured group, which is then concatenated to string containing a tab | This does leave a tab at the end, but that can be fixed with an extra gsub.
```
awk 'NR==1 {print $0,"col4\tnewcol\tnewcol2\tnewcol3")} NR>1 {gsub(/...REP=\(|\||\)/, "\t");print}' input.txt
``` |
18,008 | My son has an impression tablet 10 and has forgot the lock pattern. How can we reset it without knowing the code? | 2012/01/08 | [
"https://android.stackexchange.com/questions/18008",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/11403/"
] | Unfortunately you're probably going to have to do a factory reset, which will wipe all the data on the device (it should leave the SD card alone if there is one, though).
You may be able to do this from recovery mode, which you get into by holding some of the buttons on the device while it boots up. I don't know what buttons the devices has though.
Another method is to install the [Android SDK](http://developer.android.com/sdk/index.html) and the tablet's drivers on your computer, connect the device, and do something like the following from a command prompt (the path may vary):
```
cd C:\Program Files\Android\android-sdk\platform-tools
adb shell wipe data
```
**Edit:** From looking online it appears that there is no button combination to get into recovery, though `adb reboot recovery` might work. If you're going to install the SDK though you might as well just use the wipe command I posted above. | Assuming one doesn't have a Google account (or doesn't have access to it) and one doesn't care about loosing the data, a factory reset will help.
For that
1. Turn off the device.
2. Press Volume Up + Power Button for at least 15 seconds.
3. Release the buttons and a recovery menu will pop-up.
4. Select "Wipe data/factory reset".
Just tested with a Huawei and it worked fine. |
182,893 | Which one would sound better?
***Terrified, John locked the door and switched off the lights.***
OR
***Terrified John locked the door and switched off the lights.*** | 2014/07/08 | [
"https://english.stackexchange.com/questions/182893",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/61887/"
] | The first one is best, because *John* is a name and *terrified* is an adjective describing John. If you don't add a comma, then you're naming him *Terrified John*.
If you need a grammatical explanation (the rule), then I'll let the other people explain. | >
> Poor John locked the door and switched off the lights.
>
>
>
is a similar looking sentence, with the adjective *poor* modifying John. It is in the attributive position (just before the noun). It does not carry the same sense as 'John was poor / hard up'.
Usually, an article would be needed:
>
> The old caretaker locked the door and switched off the lights.
>
>
>
The proper noun renders the article incorrect here.
But
>
> Terrified, John locked the door and switched off the lights.
>
>
>
uses a different construction; here, the adjective (which need not be participial) is used in an *absolute* (essentially stand-alone, ie not tightly bound to the noun being modified) construction. It is really a condensed form of two loosely related statements:
>
> John was terrified. He locked the door and switched off the lights.
>
>
>
The comma is needed with such constructions; a certain bulk is also required:
>
> Terrified, John locked the door and switched off the lights.
>
>
> \*/?Wild/Mad, John locked the door and switched off the lights.
>
>
> Mad with the owners, John locked the door and switched off the lights.
>
>
> Cold and tired, John locked the door and switched off the lights.
>
>
> \*Cold, John locked the door and switched off the lights.
>
>
> |
8,430,404 | I've been seeing a lot of articles and references about how to use this patterns for my first (please keep this in mind) serious project with ASP.NET MVC 3 and EF.
The project is not so big (13 tables) and it's basically a CRUD maintenance: organisations that have some users; users that can belong to a group and can create some work areas and templates... Nothing complicated. The point is that this will be the first of a project series and I'd like to create a base to work with.
My questions are:
Which of the previous patterns is the best? Does it depend of the project size?
My models would be these:
* [Unit of work](http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application)
* [Dependency Injection](http://www.codeproject.com/kb/aspnet/diwithmvc3.aspx)
Do you think they are good enough and appropriate for my project?
I appreciate all your comments. | 2011/12/08 | [
"https://Stackoverflow.com/questions/8430404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040177/"
] | You might want to check out [S#arp Lite](https://github.com/codai/Sharp-Lite) which has many good examples of how to implement the things you want and can serve as a very good base on which to build something quickly. | None of the mentioned patterns are mutually exclusive. You should use the patterns that make sense based on what you are trying to accomplish, not attempt to shoehorn your application design into someone elses idea of how it should work. Sometimes trying to bend your scenario to fit a particular design pattern / practice is the worst thing you can do.
Want to make sure good unit test coverage / do TDD / ensure loose coupling? Then Dependency injection is your friend, as is the Unit of Work pattern. This is definitely a good idea for creating a maintainable, scalable application, but you can go too far with it for a small-scale application.
Need a centralized caching strategy for your data source? Then use the repository pattern. Or an ORM like NHibernate, which might do it for you. |
34,437 | Is there any word to refer to the practice of experts in a given field aiming at maintaining their position as experts, rather than producing anything that could possibly challenge their position?
I would like to describe this concisely, if possible in one *-ism* word, rather than as "experts' self-serving practice".
Is there any existing word for this? If not, could you suggest a neologism? | 2011/07/15 | [
"https://english.stackexchange.com/questions/34437",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/9225/"
] | The word *entrenchment* or its variations come to mind (from the OED):
>
> **Entrenched** - *adjective* (of attitudes, idea, etc.,) firmly established and not easily modified.
>
>
> **Entrenchment** - *noun* entrenching; being entrenched.
>
>
>
As in,
>
> The group's research was intended to entrench its current position instead of offer new data to the field.
>
>
>
It makes me think of a person or group fortifying themselves against change, similar to when a person "digs in their heels" and won't budge on an issue.
A similar phrase that could send you down the right path might be "maintaining the status quo," which can connote a resistance to change or growth.
As for a neologism, something like anti-progressivism comes to mind, although "Progressivism" also refers to the political movement. | **Protectionism** for a professional body.
**Cronyism** for personal relations |
117,179 | It is possible to monitor for all events that happens on Ethereum network or Binance Smart Chain network (BSC). I know that would be a lot of data however I would like later to filter that data.
If yes, thank can it be achieved with help of Web3j library or maybe there is another better one.
What about of past data? It is possible to list all events connected with some smart contract in past?
Thanks for advice | 2021/12/23 | [
"https://ethereum.stackexchange.com/questions/117179",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/89597/"
] | I'm assuming from the question you want to know if there is a way to fund a contract so it performs as expected, because when it runs out of funds the program stops?
Disclaimer: I am part of Chainlink Keepers team. There is a contract we created called "balance monitor" that works on EVM chains. Cryptphil is correct, the contract can't run continuously, so we solved this using the automation service (Chainlink Keepers).
You deploy the balance monitor contract, fund it, and configure it to monitor the contract(s) that you want to fund, funding thresholds, and amounts to top up. You then register an Upkeep with Chainlink Keepers, point it to your deployed balance monitor contract, and fund the Upkeep.
What this will do is check off-chain whether your contract(s) are underfunded, and if so, the node in the network assigned to the upkeep at that time will transmit the funding transaction to the balance monitor contract on-chain.
Link to the contract for you to use, code is also open source on Github.
<https://docs.chain.link/docs/chainlink-keepers/utility-contracts/> | If you mean something like that your contract should always send Ether after some time period, then no, this is not possible.
Because this would mean that your contract has to continuously run and, e.g., check for the blocktime which would cost you "infinite" gas and there would be no way to pack one execution of it in one block.
The way you could implement this behavior is to trigger your contract externally by some process you've implemented for your desired logic. |
37,857,327 | I am using [Apache RequestConfig](https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.html) to configure some timeouts on my `HttpClient`.
```
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(timeout) // Can I leave this out..
.build();
CloseableHttpClient httpClient = HttpClients.custom()
//.setConnectionManager(connectionManager) // ..if I don't use this
.setDefaultRequestConfig(config)
.build();
```
Does it make any sense to call `setConnectionRequestTimeout(timeout)` even I don't have a custom Connection Manager / Pool set up?
As far as I understand, `setConnectionRequestTimeout(timeout)` is used to set the time to wait for a connection from the connection manager/pool.
Note that I am not setting a Connection Manager on the `httpClient` (see commented line). | 2016/06/16 | [
"https://Stackoverflow.com/questions/37857327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073945/"
] | `connectionRequestTimeout` happens when you have a pool of connections and they are all busy, not allowing the connection manager to give you a connection to make the request.
So, The answer to your question of:
>
> Does it make any sense to call setConnectionRequestTimeout(timeout)
> even I don't have a custom Connection Manager / Pool set up?
>
>
>
is YES.
This is because the [default implementation](https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html) has an internal connection pool.
So, yes it makes sense to specify a connection request timeout. Actually it is a good, safe practice. | Isuru's answer is mostly correct. The default connection manager is a `PoolingHttpClientConnectionManager`.
However, by default it will only have one connection in it's pool.
If you are using your `HttpClient` synchronously from the same thread you should never encounter a situation where the `ConnectionRequestTimeout` will take effect.
If you are using the `HttpClient` from multiple threads then you might want to set it, but you would probably also want to increase the pool size, among other things.
For single-threaded httpclient use it is safe to leave it out. |
15,793,602 | I'm working with Amazon SimpleDB and attempting the creation of a DB using the following tutorial . Basically it throws an error i.e. Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost. The full stacktrace is as below:
>
> Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost
> java.lang.ClassCastException: java.lang.String cannot be cast to org.apache.http.HttpHost
> at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:416)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
> at com.xerox.amazonws.common.AWSQueryConnection.makeRequest(AWSQueryConnection.java:474)
> at com.xerox.amazonws.sdb.SimpleDB.makeRequestInt(SimpleDB.java:231)
> at com.xerox.amazonws.sdb.SimpleDB.createDomain(SimpleDB.java:155)
> at com.amazonsimpledb.SDBexample1.main(SDBexample1.java:19)
>
>
>
My code is as below (note i have substituted the AWS access id and secret key with the actual values):
```
public static void main(String[] args) {
String awsAccessId = "My aws access id";
String awsSecretKey = "my aws secret key";
SimpleDB sdb = new SimpleDB(awsAccessId, awsSecretKey, true);
try {
Domain domain = sdb.createDomain("cars");
System.out.println(domain);
} catch (com.xerox.amazonws.sdb.SDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
Any ideas as to why the above mentioned error is occurs.
I appreciate any assistance. | 2013/04/03 | [
"https://Stackoverflow.com/questions/15793602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565545/"
] | It seems you are using the [Typica](http://code.google.com/p/typica/) client library, which is pretty much unmaintained since mid 2011, see e.g. the [rare commmits](http://code.google.com/p/typica/source/list) and the [steady growing unresolved issues](http://code.google.com/p/typica/issues/list), where the latest one appears to be exactly yours in fact, see [ClassCastException using Apache HttpClient 4.2](http://code.google.com/p/typica/issues/detail?id=135):
* According to the reporter, things *appear to be functional once we downgrade back to Apache HttpClient 4.1*, so that might be a temporary workaround eventually.
Either way I highly recommend to switch to the official [AWS SDK for Java](http://aws.amazon.com/sdkforjava/) (or one of the other language [SDKs](http://aws.amazon.com/tools/)), which isn't only supported and maintained on a regular fashion, but also closely tracks all AWS API changes (admittedly this isn't that critical for [Amazon SimpleDB](http://aws.amazon.com/simpledb/), which is basically frozen technology wise, but you'll have a much easier time using the plethora of [AWS Products & Services](http://aws.amazon.com/products-solutions/) later on).
* In addition you could benefit from the [AWS Toolkit for Eclipse](http://aws.amazon.com/eclipse/) in case you are using that IDE.
The SDK includes a couple of samples (also available via the Eclipse Toolkit wizard), amongst those one for SimpleDB - here's a condensed code excerpt regarding your example:
```
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(
awsAccessId, awsSecretKey);
AmazonSimpleDB sdb = new AmazonSimpleDBClient(basicAWSCredentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
sdb.setRegion(usWest2);
try {
// Create a domain
String myDomain = "MyStore";
System.out.println("Creating domain called " + myDomain + ".\n");
sdb.createDomain(new CreateDomainRequest(myDomain));
// ...
// Delete a domain
System.out.println("Deleting " + myDomain + " domain.\n");
sdb.deleteDomain(new DeleteDomainRequest(myDomain));
} catch (AmazonServiceException ase) {
// ...
} catch (AmazonClientException ace) {
// ...
}
``` | Please try to create instance of SimpleDB with server and port and let me know if it works.
```
public SimpleDB objSimpleDB = null;
private String awsAccessKeyId = "access key";
private String awsSecretAccessKey = "secret key";
private boolean isSecure= true;
private String server = "sdb.amazonaws.com";
private int port=443;
try{
SimpleDB objSimpleDB = new SimpleDB(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port);
Domain domain = objSimpleDB .createDomain("cars");
} catch (com.xerox.amazonws.sdb.SDBException e) {
//handle error
}
``` |
37,481 | HD pictures has 1920x1080 = 2073600 pixels = 2025 kilopixel = 1.98 megapixel.
Does this mean that we can take HD pictures with a 2 MP camera? If not, why not? | 2013/04/03 | [
"https://photo.stackexchange.com/questions/37481",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/19142/"
] | No, because of the Bayer filter. You would actually need around 11 megapixels.
**What a Bayer filter is**
Colour camera sensors use Bayer filters to capture the various colours. The Bayer filter effectively halves the resolution of the sensor for each colour (though green is left with slightly more in a checker-board pattern).
Each pixel on the sensor can *only* capture *either* red, green or blue light, but not all three colours. A software algorithm needs to interpolate the data later to re-construct the full resolution photograph in full colour.

**Demosaicing**
This interpolation process (called *demosaicing*) will visually restore a lot of the effective lost resolution, making it look pretty sharp again, but it can only do so by taking fairly intelligent guesses. It's not the same as if you had been able to capture the image at full resolution in the first place.
For example, while demosaicing is fairly good at claiming back lost sharpness from the Bayer filter, any fine detail such as hair, comb-like patterns or fine stripes are likely to suffer from *aliasing*, which can show up as colourful interference patterns:
 ([source](https://www.sciencedirect.com/science/article/pii/S0923596511000415))
*(These images show very poor demosaicing algorithms for the sake of illustration. Modern cameras - even cellphones - use much smarter ones.)*
Modern demosaicing algorithms are pretty smart and can minimise the effect of aliasing, but it still cannot retain the fine detail. A distant picket fence shot on a 1920x1080 colour sensor will retain less effective resolution than an RGB 1920x1080 image that is computer-generated or scaled down from a larger sensor or scanned on a scanner.
**How this affects the resolution**
(and how I came up with the "11 megapixels" figure)
The effective resolution of the resulting image after demosaicing doesn't *look* like it is half the resolution claimed by the sensor, because of the gains made by smart demosaicing routines, and the fact that the green channel, which correlates well with luminance, has more resolution than the other colours.
But it still would need to be shrunk by 50% to remove any loss due to interpolation. If you really wanted to ensure that your picture was "full resolution", without any loss of detail due to interpolation, you would need to have a colour sensor with double the resolution you want, in both the horizontal and vertical direction, and then resample the resulting image to 50%.
In order to capture full effective resolution of 1920x1080, a colour camera sensor (with a Bayer filter, which includes 99% of colour camera sensors) would need to have a resolution of double that: 3840x2160. That's over 8.2 megapixels. Due to cropping on the sensor (again due to the camera's demosaicing method) you'd effectively need around 8.8 megapixels to be sure.
And that's if your sensor had a perfect 16:9 aspect ratio. If your sensor has a 3:2 aspect ratio, you'd need around 10.7 megapixels to capture a 3840x2160 image, including discarded areas on the top and bottom to make up for the aspect ratio, and a small border to account for any demosaicing crop.
**Sensors without Bayer filters**
While 99% of colour camera sensors use Bayer filters, there are some that use an alternative pixel layout, but the principle is the same.
There are also some colour sensors that don't need a colour filter at all, such as the [Fovean X3 sensor](https://en.wikipedia.org/wiki/Foveon_X3_sensor), but these are still exceptionally rare and have their own issues. Manufacturers also tend to lie about their pixel count (in order to be competitive with sensors using a Bayer filter, where the pixel count always sounds a lot more impressive than it really is due to the above described filter).
Another alternative that is employed by some expensive professional video cameras is to have three entirely separate sensors, one for each of red, green and blue, and use a light splitter to throw the same image on all three of them. Obviously this cannot exist in a DSLR or compact camera or any normal type of consumer stills camera. But it can explain why pixel counts on the sensors of professional video cameras can't be compared to those on DSLRs.
**But video uses chroma-subsampling anyway!**
(For technical minds only)
Even though video (and sometimes JPEG) uses chroma sub-sampling, it still needs the luminance channel to retain full resolution. In an image from a Bayer sensor, the luminance channel still needs to be calculated using a process of interpolation, even though with a good demosaicing algorithm, it can appear to approach full resolution due to the high correlation between luminance and the green channel in most content. | There are three common high-definition video modes:
Video Mode: Frame size (WxH): Pixels in image (resolution) Scanning Type
1. 720p 1,280x720 921,600 (almost 1MP) Progressive
2. 1080i 1,920x1,080 2,073,600 (>2MP) Interlaced
3. 1080p 1,920x1,080 2,073,600 (>2MP) Progressive
it depends on what usage are you planning. if you want to project your video on a large screen (e.g. projector), then use a higher video mode of at least 1080p which of course requires a higher resolution (means more mega pixels) for smooth projection of the image. Take note also of when using a higher resolution mean a more space consumption on a memory card and would require a higher specs of your PC for the video editing. But if you're planning for a small screen projection, (Laptop, PC) a 720p would do.
Special Note on Scanning Type
Progressive - is a way of displaying, storing, or transmitting moving images in which all the lines of each frame are drawn in sequence. The main advantage with progressive scan is that motion appears smoother and more realistic.
Interlaced - commonly used in analog aged of tv and crt, is a technique of doubling the perceived frame rate introduced with the signal without consuming extra bandwidth. The main problem of it is the interline twitter. For instance, a person on television wearing a shirt with fine dark and light stripes may appear on a video monitor as if the stripes on the shirt are "twittering". This aliasing effect shows up when the subject contains vertical detail that approaches the horizontal resolution of the video format. |
587,918 | So this problem is actually mistaken, the condition should really be that a group of order $n$ with $\gcd(n,\varphi(n))=1$, **not** just being odd square free. Since there exists a group of order 21 which is not abelian, thanks to @NickyHekster. Sorry for the fallacy conclusion. So I posted a new one with the complete problem here:
[Any group of order $n$ satisfying $\gcd (n, \varphi(n)) =1$ is cyclic](https://math.stackexchange.com/questions/588522/any-group-of-order-n-satisfies-gcd-n-varphin-1-is-cyclic) | 2013/12/01 | [
"https://math.stackexchange.com/questions/587918",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/112564/"
] | To find the section, use the Sylow theorems.
You have found $\pi : G \to H \simeq \mathbb Z / p \mathbb Z$, an epimorphism. Now in $G$, since $|G| = p\_1\cdots p\_s$, without loss of generality assume $|H| = p\_s$. By Lagrange's theorem there exists $x \in G$ with $K \overset{def}=\langle x \rangle \simeq \mathbb Z / p \mathbb Z$.
Using the Sylow theorems, $K$ is a Sylow $p$-subgroup since $|G|$ is squarefree. We wish to show that $K \le G$ is the unique subgroup of $G$ of order $p$. Call the number of such subgroups $n\_p$. Since $n\_p$ divides $|G|/|K| = p\_s$ and $n\_p = 1 \pmod{p\_s}$, $n\_p = 1$. That is, $K$ is unique. Any isomorphism $H \to K$ gives rise to a section $H \hookrightarrow G$. Using the expansion of my suggestion by Giorgio Mossa, you're done.
Added : For those who worry that this argument is wrong, it is not. This is because the problem does not lie here. Using this section, one gets a normal subgroup $N \trianglelefteq G$ and a subgroup $H \le G$ such that $NH = G$ and $N \cap H = \{e\}$, i.e. one gets a *semi-direct product*. Therefore the most general result one can get is a decomposition
$$
G \simeq (\cdots(( H\_1 \rtimes H\_2 ) \rtimes H\_3 ) \rtimes \dots \rtimes H\_s
$$
where $|H\_i| = p\_i$, using induction on $i$ up to $s$ where $|G| = p\_1 \cdots p\_s$.
Hope that helps, | Here are some hint that can help you in proving the part b).
When you have a surjective homomorphism
$$\pi \colon G \to H$$
and want to show that $G \cong H \times N$ for $N=\ker \pi$ a standard technique
is to find a morphisms $i \colon H \to G$ such that $\pi \circ i=1\_H$, that's the section which Patrick Da Silva was referring to.
If you find such a map then clearly
* $i$ must be injective, since $\pi\circ i=1\_H$ and $\ker i \subseteq \ker \pi\circ i= 0$;
* there's a subgroup $H'=\text{Im } i < G$ isomorphic to $H$, because $i$ is injective;
* the intersection $H' \cap N=(0)$, because $\pi \circ i=1\_H$ there cannot be any element in $\text{Im }i$ which is element of $N$
from that you should easily get that $G$ is a semidirect product of $H$ and $N$, to have a direct product you just need to prove that $H'$ is a normal subgroup of $G$ (*hint:* $H'$ have order $p$ for some prime that divide the order of $G$, and is the maximal power of $p$ dividing it).
The last part is to prove that $N$ is an abelian group, in order to prove that $G$ is abelian (hint: induction).
Hope this helps. |
27,072 | >
> It's about time she went home
>
>
>
Mein Versuch ist :
>
> Es ist Zeit, dass sie nach Hause gegangen ist.
>
>
> | 2015/12/09 | [
"https://german.stackexchange.com/questions/27072",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/3480/"
] | >
> It's about time she went home
>
>
>
Wenn ich diese Aussage korrekt interpretiere (und Sprachinformationsressourcen wie [diese Seite](http://idioms.thefreedictionary.com/about+time) scheinen mir da zuzustimmen), dann bedeutet die obige Aussage *nicht* zwangsläufig, dass sie bereits nach Hause gegangen ist, sondern dass sie nach Hause gehen sollte (bzw. dies bereits früher hätte tun sollen).
Daher ist eine idiomatische Übersetzung meiner Meinung nach:
>
> Es ist [an der] Zeit für sie, nach Hause zu gehen.
>
>
>
oder
>
> Es ist [an der] Zeit, dass sie nach Hause geht.
>
>
>
Varianten:
* Alternativ funktioniert statt *Es ist [an der] Zeit* auch *Es wird Zeit*.
* Wenn klar ist, wer gemeint ist, würde ich in der ersten Version *für sie* eher weglassen. (z.B.: *Sie sieht sehr müde aus. Es wird Zeit, nach Hause zu gehen.*)
* Die Person, auf die man sich bezieht, könnte man eventuell auch mit *bei ihr* ausdrücken. (z.B: *Sie sieht sehr müde aus. Bei ihr ist es an der Zeit, nach Hause zu gehen.*) | >
> Es wurde Zeit, dass sie nach Hause gegangen ist.
>
>
>
oder etwas stärker
>
> Es wurde *aber auch* Zeit, dass sie nach Hause gegangen ist.
>
>
>
Edit: Diese Antwort ist falsch, da der Subjunktiv im zweiten Halbsatz nicht beachtet wird, siehe andere Antworten für korrekte Übersetzungsvorschläge. |
33,205,164 | Using Camel and its rabbitMQ module, how would I define an endpoint URL to a durable topic subscription? What options need to be set? what are corresponding options for what in camel JMS would be clientId and durableSubscriptionName? | 2015/10/19 | [
"https://Stackoverflow.com/questions/33205164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612418/"
] | You need to use `ng-class` for this. There are two ways of writing a ternary in Angular.
Prior to version 1.1.5
```
<td ng-cloak data-ng-class="player.standing ? 'null' : 'strikethrough'">{{ player.name }}</td>
```
Version 1.1.5 and later:
```
<td ng-cloak data-ng-class="player.standing && 'null' || 'strikethrough'">{{ player.name }}</td>
```
Add the CSS style for `.strikethrough` and everything is good to go.
```
.strikethrough {
text-decoration: line-through;
}
```
You can see it working at this plunker: <http://plnkr.co/edit/MYnXLwCC7XI1MrvcI5ti?p=preview> | For Angular 7 you can use ngClass which adds or removes css classes on HTML elements.
.html
```
<td [ngClass]="player.standing ? 'null' : 'strikethrough'"> {{ player.name }} </td>
```
.css
```
.strikethrough {
text-decoration: line-through;
}
```
Read more on `ngClass` [here](https://angular.io/api/common/NgClass) |
115,022 | Suppose we have $v$ and $u$, both are independent and exponentially distributed random variables with parameters $\mu$ and $\lambda$, respectively.
How can we calculate the pdf of $v-u$? | 2012/02/29 | [
"https://math.stackexchange.com/questions/115022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/26008/"
] | The right answer depends very much on what your mathematical background is. I will assume that you have seen some calculus of several variables, and not much beyond that. Instead of using your $u$ and $v$, I will use $X$ and $Y$.
The density function of $X$ is $\lambda e^{-\lambda x}$ (for $x \ge 0$), and $0$ elsewhere. There is a similar expression for the density function of $Y$. By independence, the **joint** density function of $X$ and $Y$ is
$$\lambda\mu e^{-\lambda x}e^{-\mu y}$$
in the first quadrant, and $0$ elsewhere.
Let $Z=Y-X$. We want to find the density function of $Z$. First we will find the cumulative distribution function $F\_Z(z)$ of $Z$, that is, the probability that $Z\le z$.
So we want the probability that $Y-X \le z$. The geometry is a little different when $z$ is positive than when $z$ is negative. I will do $z$ positive, and you can take care of negative $z$.
Consider $z$ fixed and positive, and **draw** the line $y-x=z$. We want to find the probability that the ordered pair $(X,Y)$ ends up below that line or on it. The only relevant region is in the first quadrant. So let $D$ be the part of the first quadrant that lies below or on the line $y=x+z$. Then
$$P(Z \le z)=\iint\_D \lambda\mu e^{-\lambda x}e^{-\mu y}\,dx\,dy.$$
We will evaluate this integral, by using an iterated integral. First we will integrate with respect to $y$, and then with respect to $x$. Note that $y$ travels from $0$ to $x+z$, and then $x$ travels from $0$ to infinity. Thus
$$P(Z\le x)=\int\_0^\infty \lambda e^{-\lambda x}\left(\int\_{y=0}^{x+z} \mu e^{-\mu y}\,dy\right)dx.$$
The inner integral turns out to be $1-e^{-\mu(x+z)}$. So now we need to find
$$\int\_0^\infty \left(\lambda e^{-\lambda x}-\lambda e^{-\mu z} e^{-(\lambda+\mu)x}\right)dx.$$
The first part is easy, it is $1$. The second part is fairly routine. We end up with
$$P(Z \le z)=1-\frac{\lambda}{\lambda+\mu}e^{-\mu z}.$$
For the density function $f\_Z(z)$ of $Z$, differentiate the cumulative distribution function. We get
$$f\_Z(z)=\frac{\lambda\mu}{\lambda+\mu} e^{-\mu z} \quad\text{for $z \ge 0$.}$$
Please note that we only dealt with positive $z$. A very similar argument will get you $f\_Z(z)$ at negative values of $z$. The main difference is that the final integration is from $x=-z$ on. | There is an alternative way to get the result by applying the the Law of Total Probability:
$$
P[W] = \int\_Z P[W \mid Z = z]f\_Z(z)dz
$$
As others have done, let $X \sim \exp(\lambda)$ and $Y \sim \exp(\mu)$. What follows is the only slightly unintuitive step: instead of directly calculating the PDF of $Y-X$, first calculate the CDF: $ P[X-Y \leq t]$ (we can then differentiate at the end).
$$
P[Y - X \leq t] = P[Y \leq t+X]
$$
This is where we'll apply total probability to get
$$
= \int\_0^\infty P[Y \leq t+X \mid X=x]f\_X(x) dx
$$
$$
= \int\_0^\infty P[Y \leq t+x]f\_X(x) dx
= \int\_0^\infty F\_Y(t+x) f\_X(x) dx
$$
Note substituting the CDF here is only valid if $t \geq 0$,
$$
= \int\_0^\infty (1- e^{-\mu(t+x)}) \lambda e^{-\lambda x} dx
= \lambda \int\_0^\infty e^{-\lambda x} dx - \lambda e^{-\mu t} \int\_0^\infty e^{-(\lambda+\mu)x} dx
$$
$$
= \lambda \left[ \frac{e^{-\lambda x}}{-\lambda} \right]^\infty\_0 - \lambda e^{-\mu t} \left[ \frac{e^{-(\lambda+\mu)x}}{-(\lambda+\mu)} \right]^\infty\_0
=1 - \frac{\lambda e^{-\mu t}}{\lambda+\mu}
$$
Differentiating this last expression gives us the PDF:
$$
f\_{Y-X}(t) = \frac{\lambda \mu e^{-\mu t}}{\lambda+\mu} \quad \text{for $t \geq 0$}
$$ |
19,857,213 | I started using Gradle build system a few days ago and got the script to work as I wanted, here it is:
```
buildscript {
repositories {
mavenCentral()
}
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 17
buildToolsVersion '18.0.1'
productFlavors {
flavor1 {
packageName "flavor1"
}
flavor2 {
packageName "flavor2"
}
flavor3 {
packageName "flavor3"
}
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
signingConfigs {
release {
storeFile file("test.keystore")
storePassword "*****"
keyAlias "****"
keyPassword "*****"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
}
}
```
As you can see there is nothing fancy here just building 3 flavours of the app and signing them with the same key. I just run gradle assembleRelease and after 20 seconds I have my apks in build folder. But the problem is that there are other files generated that I don't want for example appname-release-unaligned.apk.
I know that this file is needed before apk can be signed but would like to add a task to delete these files in my gradle script?
Also if it's possible I would like to remove all other (shell I say artefact files) generated during build. Essentially I would like to run something like gradle clean but leave the build apk files. How do I do this?
BONUS:If anyone has pointers on how can I optimise this script and enable zip align and proguard (without custom rules just default obfuscation is ok) that would also help me since I am very new to gradle and none of the tutorials I followed explains these steps. | 2013/11/08 | [
"https://Stackoverflow.com/questions/19857213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2161029/"
] | **UPDATE February 2018**.
This block will cause a build error using Android Gradle plugin 3.0 or above. See 'deepSymmetry's comment below.
The "fix" is to **delete the block altogether** and the plugin's default behavior will automatically clean up the intermediate temporary apks (ex: app-debug-unaligned.apk).
---
Pretty old topic but here is modern solution for deleting unnecessary 'unaligned' file. This is quite handy especially on CI servers to save some space.
That's a shame that plugin does not provide hook for 'zipAlign' task so we'll need to hook on 'assemble' task which goes after 'zipAlign'.
Works with last gradle plugin 1.2.0 (gradle-2.4) but should be valid for 1.+
```
// delete unaligned files
android.applicationVariants.all { variant ->
variant.assemble.doLast {
variant.outputs.each { output ->
println "aligned " + output.outputFile
println "unaligned " + output.packageApplication.outputFile
File unaligned = output.packageApplication.outputFile;
File aligned = output.outputFile
if (!unaligned.getName().equalsIgnoreCase(aligned.getName())) {
println "deleting " + unaligned.getName()
unaligned.delete()
}
}
}
}
```
And another one if your prefer to check zipAlignEnable flag but in this case you'll be tied to "unaligned" constant in filename because release builds with zipAlignEnabled=true AND without signingConfig skip 'zipAlign' task and produce only one file: 'app-release-unsigned.apk'.
```
// delete unaligned files
android.applicationVariants.all { variant ->
variant.assemble.doLast {
variant.outputs.each { output ->
println "aligned " + output.outputFile
println "unaligned " + output.packageApplication.outputFile
File file = output.packageApplication.outputFile;
if (variant.buildType.zipAlignEnabled && file.getName().contains("unaligned")) {
println "deleting " + file.getName()
file.delete()
}
}
}
}
```
I am using the first one in case anyone cares. | I can at least answer your bonus-question:
```
buildTypes {
release {
runProguard true
signingConfig signingConfigs.release
}
}
```
If you have specific proguard-rules, just enter this line to your `defaultConfig` or to your product flavors:
```
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
```
The first proguard rule is the generla one from your Android SDK, the second one is from your module-directory.
ZipAlign is enabled by default if you build you project with the build variant `release`. |
42,572,571 | I have the following Web services.
```html
@WebService(targetNamespace="T24WebServicesImpl")
@XmlSeeAlso( {
MYCUSTOMERType.class,
Object[].class } )
@HandlerChain(file = "./handler-chain.xml")
public class T24WebServicesImpl extends TwsController {
@WebMethod
public void myCustomer(
.......
}
}
handler-chain.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxrs:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<jaxrs:handler-chain>
<jaxrs:handler>
<jaxrs:handler-class>com.temenos.tws.Handler</jaxrs:handler-class>
</jaxrs:handler>
</jaxrs:handler-chain>
</jaxrs:handler-chains>
```
When executing the service, the Handler class is not being invoked.Kindly advise why? | 2017/03/03 | [
"https://Stackoverflow.com/questions/42572571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4101458/"
] | Yes you can do it with the built-in .NET Core IOC container, using [Scrutor](https://github.com/khellang/scrutor) extension methods. It has got some nice assembly scanning functionalities.
Try this:
```
services.Scan(scan => scan
.FromAssemblies(typeof(yourassembly).GetTypeInfo().Assembly)
.AddClasses()
.AsImplementedInterfaces()
.WithScopedLifetime());
```
It applies on the built-in IOC container, though it's not itself a built-in package ([Scrutor package on Nuget](https://www.nuget.org/packages/Scrutor/)): | You can easily implement your own method to register all assembly types for a given assembly or set of assemblies... the code would be along the lines of:
```
foreach (var implementationType in assemblies.SelectMany(assembly => assembly.GetTypes()).Where(type => !type.GetTypeInfo().IsAbstract))
{
foreach(var interfaceType in implementationType.GetInterfaces())
{
services.AddSingleton(interfaceType, implementationType);
}
}
```
The code selects all non-abstract types from `assemblies` and retrieves all interfaces for each type creating a `Singleton` registration for each interface/implementation pair.
---
I prefer to register all instances of an explicit interface (i.e., `ICommandHandler` or similar), so I add extension methods along the lines of `AddCommandHandlers` shown below for the few types I want *any* instance of to be registered...
```
public static void AddCommandHandlers(this IServiceCollection services, params Assembly[] assemblies)
{
var serviceType = typeof(ICommandHandler);
foreach (var implementationType in assemblies.SelectMany(assembly => assembly.GetTypes()).Where(type => serviceType.IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract))
{
services.AddSingleton(serviceType, implementationType);
}
}
```
Adding a call similar to `services.AddCommandHandlers(DomainAssembly.Reference);` in `ConfigureServices`...
I prefer this approach, because registering all interfaces for all types will add a lot of cruft registrations to your IoC container... typically not a huge deal, but cleaner in my opinion. |
33,830,509 | I have Spark application which contains the following segment:
```
val repartitioned = rdd.repartition(16)
val filtered: RDD[(MyKey, myData)] = MyUtils.filter(repartitioned, startDate, endDate)
val mapped: RDD[(DateTime, myData)] = filtered.map(kv=(kv._1.processingTime, kv._2))
val reduced: RDD[(DateTime, myData)] = mapped.reduceByKey(_+_)
```
When I run this with some logging this is what I see:
```
repartitioned ======> [List(2536, 2529, 2526, 2520, 2519, 2514, 2512, 2508, 2504, 2501, 2496, 2490, 2551, 2547, 2543, 2537)]
filtered ======> [List(2081, 2063, 2043, 2040, 2063, 2050, 2081, 2076, 2042, 2066, 2032, 2001, 2031, 2101, 2050, 2068)]
mapped ======> [List(2081, 2063, 2043, 2040, 2063, 2050, 2081, 2076, 2042, 2066, 2032, 2001, 2031, 2101, 2050, 2068)]
reduced ======> [List(0, 0, 0, 0, 0, 0, 922, 0, 0, 0, 0, 0, 0, 0, 0, 0)]
```
My logging is done using these two lines:
```
val sizes: RDD[Int] = rdd.mapPartitions(iter => Array(iter.size).iterator, true)
log.info(s"rdd ======> [${sizes.collect().toList}]")
```
My question is why does my data end up in one partition after the reduceByKey? After the filter it can be seen that the data is evenly distributed, but the reduceByKey results in data in only one partition. | 2015/11/20 | [
"https://Stackoverflow.com/questions/33830509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974387/"
] | You need to set up the passProps property on the navigator. There are a few recent examples on stack overflow, specifically [here](https://stackoverflow.com/questions/33763709/passprops-equivalent-for-navigator/33767091#33767091) and [here](https://stackoverflow.com/questions/33825524/navigator-with-args).
```
<Navigator
initialRoute={{name: 'Main', component: Main, index: 0}}
renderScene={(route, navigator) => {
return React.createElement(<YourComponent />, { ...this.props, ...route.passProps, navigator, route } );
}} />
```
or
```
<Navigator
initialRoute={{name: 'Main', component: Main, index: 0}}
renderScene={(route, navigator) => {
<route.component {...route.passProps} navigator={navigator} route={route} />
}
}
/>
```
If you are looking for the most basic of setups just to understand the functionality, I have set up a project [here](https://rnplay.org/apps/cSM_uw) that you can reference, and pasted the code below.
```
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
Image,
TouchableHighlight, TouchableOpacity
} = React;
class Two extends React.Component {
render(){
return(
<View style={{marginTop:100}}>
<Text style={{fontSize:20}}>Hello From second component</Text>
<Text>id: {this.props.id}</Text>
<Text>name: {this.props.name}</Text>
<Text>name: {this.props.myVar}</Text>
</View>
)
}
}
class Main extends React.Component {
gotoNext(myVar) {
this.props.navigator.push({
component: Two,
passProps: {
id: 'page_user_infos',
name: 'page_user_infos',
myVar: myVar,
}
})
}
render() {
return(
<View style={{flex: 4, flexDirection: 'column', marginTop:100}}>
<TouchableHighlight style={{ height:40, borderWidth:1, marginBottom:10, backgroundColor: '#ddd'}} name='Pole' onPress={ () => this.gotoNext('This is a property that is being passed') }>
<Text style={{textAlign:'center'}}>Go to next page</Text>
</TouchableHighlight>
</View>
)
}
}
class App extends React.Component {
render() {
return (
<Navigator
style={{flex:1}}
initialRoute={{name: 'Main', component: Main, index: 0}}
renderScene={(route, navigator) => {
if (route.component) {
return React.createElement(route.component, { ...this.props, ...route.passProps, navigator, route } );
}
}}
navigationBar={
<Navigator.NavigationBar routeMapper={NavigationBarRouteMapper} />
} />
);
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<TouchableHighlight style={{marginTop: 10}} onPress={() => {
if (index > 0) {
navigator.pop();
}
}}>
<Text>Back</Text>
</TouchableHighlight>
)} else {
return null}
},
RightButton(route, navigator, index, navState) {
return null;
},
Title(route, navigator, index, navState) {
return null
}
};
var styles = StyleSheet.create({
});
AppRegistry.registerComponent('App', () => App);
``` | Sometimes the pass prop doesn't work (at least for me) So what I do is I pass it in the route object itself
```
nav.push({
id: 'MainPage',
name: 'LALA',
token: tok
});
```
so to access it in the next scene I use
```
var token = this.props.navigator.navigationContext.currentRoute.token;
```
although kind of a complicated "access" but it is fool proof pass props might work or might not also in this way you can pass the properties in the route object itself thus saving you from the hassle of sending it in a different way.
This might not be the right way but I find it a tad bit more convenient. |
15,706,944 | I'm looking at code that looks like
```
try {
// Lots of things here.
// More than I'd like to individually hover over every time I see this
}
catch (Exception e) {
// doesn't matter
}
```
For any particular method in the try block, I can find what checked exceptions it throws. Is there any way to highlight all lines that could throw some checked exception?
In general, I guess I could perhaps remove the catch block, changing the method signature to throw Exception, at which point, I can see all lines in the method that throw an exception (Nevermind: see the update).
In this case, that won't even work nicely, because the code is in a JSP.
Note: if it matters, I'm using MyEclipse standard.
Update: Mark occurrences is on, but simply does nothing in this case. I asked the question because I thought that something about the context made this expected behavior, but it looks like it's a weird edge case or bug. | 2013/03/29 | [
"https://Stackoverflow.com/questions/15706944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802500/"
] | In eclipse, if you enable "highlight occurrences" and select `Exception`, it would highlight all lines that are throwing a (checked) exception that is being caught by the catch block. | You can read the class' reference manual to figure out what exception a particular method can throw. Keep in mind java has two kinds of exception: checked and unchecked. With unchecked exception, the method doesn't have to declare it can throw the exception (for example RuntimeException)
I'd also recommend you use some IDE such as Eclipse, it will instantly tell you if a line can throw exception and you're not handling it -- you can then wrap it with try-catch or have the method throw it just by single mouse click. |
36,078,874 | I placed the buttons below scroll view and enable vertical scrolling.After scrolling,the buttons are visible,If I click buttons doesn’t work.
1.This Image shows the "story Board" which contains "table view" inside "scroll view" and the "buttons" placed below "scroll view" "Buttons" shown in "blue colour".
scroll view specification in story board (0,83,568,237)
Table view specification in story board (2,4,564,229)
[](https://i.imgur.com/TmXU4m5.png)
2.This Image shows the "view" without scrolling.
[](https://i.imgur.com/DugvyIf.png)
3.This Image represents the "vertical scrolling" with towards "up" direction.
My Piece of code For "vertical Scrolling"
```
[_scroller setScrollEnabled:YES];
[_scroller setContentSize:CGSizeMake(_scroller.bounds.size.width, _scroller.bounds.size.height*3)];
```
My piece of code for displaying "scrollview" ,"tableview","Buttons" similarly in iPad and iPhone:
```
[_tblview setFrame:CGRectMake(0,80,self.view.frame.size.height,self.view.frame.size.width)];
[_scroller setFrame:CGRectMake(0,80,self.view.frame.size.height,self.view.frame.size.width)];
[_btnSave setFrame:CGRectMake(0,self.view.frame.size.width-50,50,25)];
[_btnSubmit setFrame:CGRectMake(55,self.view.frame.size.width-50,50,25)];
[_btnCancel setFrame:CGRectMake(110,self.view.frame.size.width-50,50,25)];
```
[](https://i.imgur.com/uKL2WRM.png)
4.This Image represents the "vertical scrolling" towards down direction.It shows three "buttons" save,submit,cancel.after scrolling towards down,If I click any of these buttons.None of the action occurs.It's the issue.
[](https://i.imgur.com/OGQzaZv.png)
What might be the issue.I have to alter the "buttons" CGRectmake or reduce the size of scroll view and table view or Modify the UI design with place the buttons on the top of scroll view.Please provide me some solution for me.Thanks in advance. | 2016/03/18 | [
"https://Stackoverflow.com/questions/36078874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5723645/"
] | This is how i got the transparent RGB integer value
```
Bitmap myDisplayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_pic);
if (myDisplayBitmap != null && !myDisplayBitmap.isRecycled())
{
Palette palette = Palette.from(myDisplayBitmap).generate();
Palette.Swatch vibrantSwatch = palette.getDarkVibrantSwatch();
/*If vibrantSwatch is null then return 0 otherwise :-) */
int opaqueDarkVibrantColor = vibrantSwatch != null ? vibrantSwatch.getRgb() : 0;
/*Call the method that returns alpha color */
int transparentRGBInt = getColorWithAplha(opaqueDarkVibrantColor, 0.5f)
yourLayout.setBackgroundColor(transparentRGBInt);
// prints something like -2146428888
Log.i("info", String.valueOf(transparentRGBInt));
}
```
and here is the method that returns alpha value, you need to pass two params int RGB color value and ratio of transparency.
```
/**
* @param color opaque RGB integer color for ex: -11517920
* @param ratio ratio of transparency for ex: 0.5f
* @return transparent RGB integer color
*/
private int getColorWithAplha(int color, float ratio)
{
int transColor = 0;
int alpha = Math.round(Color.alpha(color) * ratio);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
transColor = Color.argb(alpha, r, g, b);
return transColor ;
}
```
**Edit**
Use this to get the Hex value from the int RGB value
```
String opHexColor = String.format("#%06X", (0xFFFFFF & opaqueDarkVibrantColor));
``` | I haven't tested this but something like this should work
```
private int setAlpha(int color, int alpha) {
alpha = (alpha << 24) & 0xFF000000;
return alpha | color;
}
``` |
2,289,642 | What is the best route to go for learning OOP if one has done some programming in C.
My intention was first to take the natural leap and "increment with one" and go for Stroustrup. But since I got my hands on the little old Bertrand Meyer's OOSC2 and I qoute from the appendix page 1135 *"..according to Donald Knuth, it would make Edsger Dijkstra 'physically ill to think of programming in C++"*
And Meyer himself *"..that C++ is not the ideal OOP language..."*
And what about this A critiqe on C++ on this question: [A critique of C++](http://burks.brighton.ac.uk/burks/pcinfo/progdocs/cppcrit/)
Should I skip C++ and go for C# and or Java directly if my intention is a great and deep understanding of a modern OOP-language, or do I miss good points on this subject in C++?
Well I know this is a discussion-thing but I mark it wiki and you're answers could mean a lot for me in choices to come. | 2010/02/18 | [
"https://Stackoverflow.com/questions/2289642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163407/"
] | Any language will do if you learn it from a good book. I learned both C++ and Java starting from [Bruce Eckel's books](http://www.mindviewinc.com/Books/).
After you know some basics of OOP, I would suggest reading [Object-Oriented Programming with ANSI-C](http://www.planetpdf.com/codecuts/pdfs/ooc.pdf). It will give you some deep insights on how OOP languages work, because it implements an OOP language from C. | I would say Java. A good book that helped me is [this one.](https://rads.stackoverflow.com/amzn/click/com/0072225130) |
62,026,992 | I have an external function that changes a state inside a component thru `ref` and `ImperativeHandler` hook
```
const [state, setState] = useState(0);
// inside component
const testFunc = () => {
setState(1)
}
// outside of component
function *generator {
yield ...
yield testFunc()
// next yield should wait till state is updated, only then it can be executed
yield ...
}
```
but I can't figured out how to track that state has been chaged, since `setState` hook has no callback option.
How can I track the moment when the state changed in the outside function such as my `generator` example? | 2020/05/26 | [
"https://Stackoverflow.com/questions/62026992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11069163/"
] | Since you are using hooks and the updater function doesn't receive a 2nd argument like the class updater version, you might want to implement an updater with a 2nd argument on your own:
```
function useStateWithCallback(initState) {
const cbRef = useRef(null);
const [state, setState] = useState(initState);
useEffect(() => {
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null;
}
}, [state]);
const updater = (value, callback) => {
cbRef.current = typeof callback === "function" ? callback : null;
setState(value);
};
return [state, updater];
}
```
* We create our own `useState` with the same signature, a function that accept an initial state and returns a tuple of the current state and an update function, but this time the updater function takes 2 arguments, the next state and a callback.
* We need a way to store the callback passed to our updater, we could store it inside a state with `useState` but each update will trigger a render so we are storing it in a ref which is persistent across renders but mutable and won't trigger re-renders when updated. We start with a `null` value.
* We store and handle the actual state of the value with `useState`
* We sync an effect to this state value and calling the callback stored in our ref. We do that conditionally as the effect will run on the first render before any state been updated (this is why we start the ref with `null`).
* We create our own `updater` function which store the callback in our ref (while validating that its indeed a function) and trigger the actual state update.
* We return our tuple with the real state and our custom updater
Running example:
```js
const {useState, useRef, useEffect} = React;
function useStateWithCallback(initState) {
const cbRef = useRef(null);
const [state, setState] = useState(initState);
useEffect(() => {
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null;
}
}, [state]);
const updater = (value, callback) => {
cbRef.current = typeof callback === "function" ? callback : null;
setState(value);
};
return [state, updater];
}
function App() {
const [count, setCount] = useStateWithCallback(0);
const myCallback = currentState => console.log("currentState", currentState);
const onClick = () => {
setCount(c => c + 1, myCallback);
};
return <button onClick={onClick}>{count}</button>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="root" />
``` | >
> since setState has no callback option
>
>
>
`setState` can be passed a second argument, which is a callback function executed after state has been updated.
ref : <https://fr.reactjs.org/docs/react-component.html#setstate> |
5,777 | I'm a freelance graphic designer, so mostly, my pricing and what not is pretty casual and I don't work 24/7 as I have other things to take care of, so when I quote someone, I figure out how long it will take me roughly and also take into account how difficult it might be. I give them the price, get a deposit and start work. I usually tell them that the odd revision or two is included.
BUT...
In the situation that I'm asking about, I always seem to get people who are really specific on what they want, which is brilliant; it seems nice and simple and I know exactly what I'm doing. But then as the job progresses and I send them samples, they begin to change their mind, they request way more revisions/redesigns that I ever expected etc. Now, I'm fine with this, as obviously I'm happy to work with them until they are happy with their product but when I mention that it's been more work than they initially stated they almost always get angry and lash out (via email) at how I'm not holding up my end of the bargain.
I always feel awful asking for more money and I almost never get more/they cancel altogether and I'm left with nothing, usually not even the (tiny) deposit that I stated was non refundable (to protect myself from exactly this...)
What is the best way of wording something (*anything*) initially, whereby this might not happen as much. Or am I just being too polite? | 2012/02/03 | [
"https://graphicdesign.stackexchange.com/questions/5777",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/3494/"
] | Stefan has several excellent points, which I'll echo and expand upon:
* Write up a contract. You don't start *anything* without a contract.
It took me over a week to write my first contract, but that baby is
as detailed and iron-clad as I could make it, and now I can
slice-and-dice and adapt it to future jobs. The AIGA has a ridiculously detailed sample contract you can use to start with: <http://www.aiga.org/standard-agreement/>
* In that contract you spell out precisely what you are doing for the
client. Be repetitive to the point where you feel silly, because it
will save your butt later.
* As part of that contract, you specify what amount of money is due
when: deposit of $X or Y%, $X or Y% upon Milepost 1, $X or Y% upon
Milepost 2, remaining $X or last 10% when client signs off on final
product. You want to leave a little at the end so that the client
feels like they can still command your attention, but not so much
that if you had to walk away it would ruin your bank account. I like
10% as my wiggle room.
* You include N rounds of revisions. (I usually have three.) You
specify "after N rounds of revisions, any additional revisions will
be billed at $X per hour." That gives them warning right up front
that if they want to go 'round the mulberry bush, you'll be happy to
accommodate them, but they'll be paying for it.
* As part of this process, when they send you the first revision, you IMMEDIATELY respond with, "Thank you, I am in receipt of your email with blah blah revision. Per our contract, this is the first round of
revisions to this project." Now, it's up to you what constitutes "a round of revisions." It can be "one large design change," it can be "one hour of little revisions over and over," whatever. But have an idea in mind BEFORE you open the file.
* You do the same with the second round. At the third round, you
respond, "I just want to remind you before I start that this is your
last round of revisions allotted in our contract. After this,
subsequent changes will be billed on a per-hour basis and invoiced
[weekly]."
* Include a Kill Fee or a cancellation fee. The idea is that you always get paid for your time and effort, no matter where they stop in the process. You can pro-rate it to an hourly cost from the last pay milestone to the cancellation point. That will also give them pause.
* Don't be shy about asking for money. If you're a professional, act
like one. Would your plumber be shy about sending you a bill? You are
a professional providing a service. It's not your fault if they don't
like the service; you still had to do the work. Of course you want
them to be happy, but you also need to pay your grocery bill.
Basically, don't do more work than you agreed to before they agree to pay you for it. When you're reaching your estimate, STOP and tell them so. | I think all of us who have done the small free-lance thing have had to deal with this. Most of what I was going to write has already been covered in Stefan's answer, but I have a few more thoughts...
Never *ever* feel awful about asking for money up front. They are going to have to pay for your service, whether up front or after the fact - so why feel bad about the timing? In general, people pay up-front for *everything* (or sign a contract to pay later). Your services are not any less valuable than those of other vendors.
The key to this is having a clear definition and agreement. If you have a written agreement, and get part of the money up-front or in stages, it empowers you to dig in your heels and say "this is what you agreed to, and this is what you have paid for". If a client starts to make too many requests, you will have to draw the line.
For what it's worth, below is the workflow guideline that I adhere to. I do most of my work in a small 2-man team and this has worked well for us. Everything is broken down by stage, with requirements to be fulfilled before progressing to the next stage.
1. **Definition**
We collaborate with the client to define an detailed spec of the project requirements before we do any work. This involves all of their requirements (layout, colors, branding, time, etc.) all of our requirements (time, money, etc.)
We don't proceed out of this stage until we understand the client, and the client understands us. We typically require a non-refundable payment (generally not 100%, but a significant portion of the project quote) at this point.
2. **Design**
Wireframes & sketches are used to knock down a basic layout. Some rough styling will be done, but none of the time-consuming minor tweaks that really polish a design. We don't continue to the next stage until the client agrees that they are happy with the overall design.
If the client wants something that is not part of the agreed project definition, we stop everything and revise the definition & price accordingly.
3. **Refinement**
For logos & simple print designs, this is the last phase and just involves polishing the design.
At this point, if the client says "I want to change X about the layout" and it's a nontrivial change, we simple say "sorry, that needed to be done during the Design phase". If they are adamant that they need to make the change, we quote them a price to alter the agreement.
4. **Delivery**
The client gets their product. We get any remaining payment. The books are closed and we are done. After this point, *any* change is treated as a new job and is quoted accordingly.
(If we're doing a website or app, there is also an Assembly and Debugging stage before Delivery.)
Generally we require payment at each major stage. Ie., before Design, before Assembly, before Delivery. This keeps us on equal footing with our clients -- at any point of the game, we have provided part of a product and received part of a payment. If they fire us, we walk away with a clean soul and without having done work for free. This hasn't happened yet, but I don't doubt that it will someday. People are fickle.
I think this equal footing is extremely important. We don't ask too much of them without providing anything in return, and do not give them too much without requiring something in return.
If you devalue your work, a client will not hesitate to increase requirements (by way of revisions, changes, suggestions, etc.) - and if you do not have an agreement in place (and some money in your pocket), you may feel beholden to their requests. |
86,840 | According to [this link](http://scopeboy.com/elec/gyrator.html), the following schematic is equivalent to an inductance R1\*R2\*C placed between input and ground. Under which conditions is this true? As a guideline, we assume Vcc=9V. See [this post](https://electronics.stackexchange.com/questions/86565/whats-the-purpose-of-this-transistor-setup-answer-simulate-an-impedance) for the context of the question.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fBZPxT.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Application with R1=390 Ohm, R2=22 kOhm, R3=2.2 kOhm, R4=70 kOhm, C1=100 nF, C2=200 uF. | 2013/10/29 | [
"https://electronics.stackexchange.com/questions/86840",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/30909/"
] | There are better gyrator circuits so let me give you the downsides of this circuit first.
The idea behind this gyrator circuit is that at the emitter there is a voltage that connects back to the input via R1. If the emitter voltage is phase shifted to the input, it will take a current (via R1) from the input that appears to be reactive i.e. it looks like an inductor's current.
However the input is also feeding the network (C1 etc.) which does the phase shifting and so this "capacitive circuit" is in parallel with the "intentional" inductive current via R1. This makes it a band-pass filter but, it can look like an inductor across a range of frequencies.
Better gyrators use an op-amp or another transistor to buffer C1, Anyway, the analysis: -
At point B (base) the AC voltage relative there to the input voltage is: -
\$\dfrac{R\_2}{R\_2+\dfrac{1}{sC\_1}}\$ and this voltage is also at the emitter (the emitter voltage is fractionally less in AC terms but this can be largely ignored). The emitter also acts as a reasonably good ideal voltage source so we don't have to worry about its output impedance of a few ohms.
The current into R1 is the voltage across it divided by R1 (I = V/R): -
Current = \$\dfrac{V\_{IN}}{R\_1}(1-\dfrac{sC\_1 R\_2}{sC\_1 R\_2+1})\$
The impedance, Z into R1 is \$V\_{IN}\$ divided by current: -
Z = \$\dfrac{R\_1}{1-\dfrac{sC\_1 R\_2}{sC\_1 R\_2+1}}\$ = \$\dfrac{R\_1+sC\_1 R\_1 R\_2}{1+sC\_1 R\_2-sC\_1 R\_2} = R\_1+sC\_1 R\_1 R\_2\$
In other words the impedance looking into R1 is an inductance of C1\*R1\*R2 in series with a resistor of R1 ohms. Remember there is current through the capacitor but this can be ignored if R2 is a lot bigger than R1 and the gain of the transistor is high. | Redoing the analysis, I find a somewhat different result for the real part of the impedance
\$Z=R\_1+\frac{R\_2}{\beta+1} + j\omega C\_1 R\_1 R\_2\$ |
15,432,432 | In one of the answers to [Get HWND on windows with Qt5 (from WId)](https://stackoverflow.com/questions/14048565/get-hwnd-on-windows-with-qt5-from-wid) it is suggested to employ **QPlatformNativeInterface** in order to recover the native window handler.
To access the QT header though the example uses its full path:
```
#include <QtGui/5.0.0/QtGui/qpa/qplatformnativeinterface.h>
```
This, of course, is not acceptable as a definitive solution.
Is there a way to include **QPlatformNativeInterface** using the default inclusion system of QT?
Notice that neither
```
#include <QPlatformNativeInterface>
```
works (this file is not generated during the default QT build)
nor
```
#include <QGuiApplication>
```
works (which only contains a forward declaration of **QPlatformNativeInterface**) | 2013/03/15 | [
"https://Stackoverflow.com/questions/15432432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064216/"
] | You can use
```
QT += gui-private
```
in your project file, as in the [example plugin](http://qt.gitorious.net/qt/qtbase/blobs/HEAD/src/plugins/platforms/minimal/minimal.pro), and then just
```
#include <qpa/qplatformnativeinterface.h>
```
should work (works for me at least).
These APIs are indeed private, but if you have to use them, I guess this is better than adding an `#ifdef` for each version. | By searching a little bit more it seems that **QPlatformNativeInterface** is currently private and will be made public as part of the [Qt Platform Abstraction](http://wiki.qt.io/Qt-Platform-Abstraction) when this library will stabilize. |
16,115,867 | I have been having some trouble with this code. I have tried my best to stay with the book but the book seems to be wrong.
The following code should display the RSS feed for which ever radio button has been selected. You can also see the website on <http://w3.cnm.edu/~bnoble/cis1210/afds/Travel/TravelDeals.html>.
Thanks in advance for any help!
```
<html>
<head>
<title>Travel Deals RSS Feed</title>
<script>
var rssRequest = false;
function getRequestObject()
{
try
{
rssRequest = new XMLHttpRequest();
}
catch (requestError)
{
try
{
rssRequest = new ActiveXObject();
}
catch (requestError)
{
try
{
rssRequest = new
ActiveXObject("Micorsoft.XMLHTTP");
}
catch (requestError)
{
window.alert("I am sorry. Your browser does not support AJAX. Please upgrade your broweser and try again.");
return false;
}
}
}
return rssRequest;
}
function rssUpdate()
{
if(!rssRequest)rssRequest = getRequestObject();
for (var i=0; i<6; ++i)
{
if (document.forms[0].deals[i].checked == true)
{
var rss = document.forms[0].deals[i].value;
break;
}
}
rssRequest.abort();
rssRequest.open("get","TravelDeals.php?" + "rss" + rss, true);
rssRequest.send(null)
rssRequest.onreadystatechange=getRssDeals;
//clearTimeout(recentDeals);
//var recentDeals = setTimeout('rssUpdate()', 5000);
}
function getRssDeals()
{
if(rssRequest.readyState==4 && rssRequest.status == 200)
{
var deals = rssRequest.responseXML;
document.getElementById("rssFeed").innerHTML = ""
var dealsInfo=deals.getElementsByTagName("item");
if (dealsInfo.length > 0)
{
for (var i=0; i<dealsInfo.length; ++i)
{
var curHeadline = dealsInfo[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var curlink = dealsInfo[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
var curPubDate = dealsInfo[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
var curDesc = dealsInfo[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var curDeal = "<a href='" + curLink + "'>" + curHeadline + "</a><br/>";
curDeal += curDesc + "<br/>";curDeal += curDesc + "<br/>";
document.getElementById("rssFeed").innerHTML += curDeal;
}
}
else
document.getElementById("rssFeed").innerHTML = "The RSS feed appears to be broken or empty.";
}
}
</script>
</head>
<body onload="rssUpdate()">
<h1>Travel Deals RSS</h1>
<form method="get" action="">
<table border="1">
<colgroup span="1" width="125"/>
<colgroup span="1" width="350"/>
<tr>
<td align="top">
<input type="radio" name="deals" value="http://www.orbitz.com/rss/topdeals-vacationpackages.rss.xml" onclick="rssUpdate()"/><Orbitz<br/>
<input type="radio" name="deals" value="http://www.travelocity.com/dealservice/globaltrips-shopping-svcs/deals-1.0/services/RssDealsServices?ProductType=Air&rdr=GEN&nm=My~Travelocity~Specials&typ=0&orig=ABQ&dest=PHX,LAS,LAX,NYC,LGB&id=9197I1366355523195" checked="checked" onclick="rssUpdate()"/><Travelocity<br/>
<input type="radio" name="deals" value="http://press.hotwire.com/index.php?s=43&pagetemplate=rss" onclick="rssUpdate()"/><Hotwire<br/>
</td>
<td id="rssFeed" valign="top></td>
</tr>
</table>
</form>
</body>
``` | 2013/04/20 | [
"https://Stackoverflow.com/questions/16115867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2299963/"
] | There is no element with id `rssFeed` in the page.
You can solve it by adding a `div` with id `rssFeed` in the page
```
<div id="rssFeed"></div>
```
Try this complete code, because you have unclosed element in your markup
```
<html>
<head>
<title>Travel Deals RSS Feed</title>
<script>
var rssRequest = false;
function parseXML(xml){
var parser, xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml,"text/xml");
} else {
// Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xml);
}
}
function getRequestObject()
{
try
{
rssRequest = new XMLHttpRequest();
}
catch (requestError)
{
try
{
rssRequest = new ActiveXObject();
}
catch (requestError)
{
try
{
rssRequest = new
ActiveXObject("Micorsoft.XMLHTTP");
}
catch (requestError)
{
window.alert("I am sorry. Your browser does not support AJAX. Please upgrade your broweser and try again.");
return false;
}
}
}
return rssRequest;
}
function rssUpdate()
{
if(!rssRequest)rssRequest = getRequestObject();
for (var i=0; i<6; ++i)
{
if (document.forms[0].deals[i].checked == true)
{
var rss = document.forms[0].deals[i].value;
break;
}
}
rssRequest.abort();
rssRequest.open("get","TravelDeals.php?" + "rss" + rss, true);
rssRequest.send(null)
rssRequest.onreadystatechange=getRssDeals;
//clearTimeout(recentDeals);
//var recentDeals = setTimeout('rssUpdate()', 5000);
}
function getRssDeals()
{
if(rssRequest.readyState==4 && rssRequest.status == 200)
{
var deals = parseXML(rssRequest.responseXML); document.getElementById("rssFeed").innerHTML = ""
var dealsInfo=deals.getElementsByTagName("item");
if (dealsInfo.length > 0)
{
for (var i=0; i<dealsInfo.length; ++i)
{
var curHeadline = dealsInfo[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var curlink = dealsInfo[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
var curPubDate = dealsInfo[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
var curDesc = dealsInfo[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var curDeal = "<a href='" + curLink + "'>" + curHeadline + "</a><br/>";
curDeal += curDesc + "<br/>";curDeal += curDesc + "<br/>";
document.getElementById("rssFeed").innerHTML += curDeal;
}
}
else
document.getElementById("rssFeed").innerHTML = "The RSS feed appears to be broken or empty.";
}
}
</script>
</head>
<body onload="rssUpdate()">
<h1>Travel Deals RSS</h1>
<form method="get" action="">
<table border="1">
<colgroup span="1" width="125"/>
<colgroup span="1" width="350"/>
<tr>
<td align="top">
<input type="radio" name="deals" value="http://www.orbitz.com/rss/topdeals-vacationpackages.rss.xml" onclick="rssUpdate()"/><Orbitz<br/>
<input type="radio" name="deals" value="http://www.travelocity.com/dealservice/globaltrips-shopping-svcs/deals-1.0/services/RssDealsServices?ProductType=Air&rdr=GEN&nm=My~Travelocity~Specials&typ=0&orig=ABQ&dest=PHX,LAS,LAX,NYC,LGB&id=9197I1366355523195" checked="checked" onclick="rssUpdate()"/><Travelocity<br/>
<input type="radio" name="deals" value="http://press.hotwire.com/index.php?s=43&pagetemplate=rss" onclick="rssUpdate()"/><Hotwire<br/>
</td>
</tr>
</table>
<div id="rssFeed"><div>
</form>
</body>
</html>
``` | It's because you're missing a closing quote in your `td` element. You have `<td id="rssFeed" valign="top></td>` when what you want is `<td id="rssFeed" valign="top"></td>`. Fixing this should cause the element to show up. |
30,491,132 | After working on a repository in my computer i've opened the terminal to commit the changes to the github account with the purpose of updating the gh-pages branch (after 4 days of work).
I did not notice that I was on gh-pages branch already when a did the `git status` so I did as if I where on branch master.That is what I did:
1. `git add -A`
2. `git commit -m "message"`
3. `git push origin master`
After this I noticed that I was doing this in the gh-pages branch so I thought (not very cleverly) that i should go back to branch master to do the commits also there and then i did `git checkout master`. In that moment all my files (my local files, in my computer) went back in time!
The terminal showed a commit number when I did the first commit [gh-pages 4108d5a] but i can not find it in the github history.
Is there a way to recovery the previous state in my local files?? Thanks. | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3456454/"
] | It looks like you pushed to the wrong branch, and then changed branches. You should be able to do this:
`git checkout gh-pages`
`git push origin gh-pages`
and all of your work should still be on gh-pages. The master branch is right where you left it back in time. But nothing you mentioned should have removed from your gh-pages branch.
A good resource to get comfortable with how git branching, merging, etc... work is [learn git branching](http://pcottle.github.io/learnGitBranching/) | provided you didn't delete `gh-pages` you can do
```
git checkout gh-pages
```
and then to recover your work
```
git reset head~1 --soft
```
or you may very well merge your branch into `master` like:
```
git merge gh-pages
``` |
4,618,633 | I'm reading [this answer](https://math.stackexchange.com/a/687751/688539), in which, one of the step involves showing that:
$$s\_3(r\_1s\_2-r\_2s\_1)=0,\quad s\_1(r\_2s\_3-r\_3s\_2)=0\implies s\_2(r\_1s\_3-r\_3s\_1)=0$$
I am utterly confused on how this implication was arrived at. How does having the "s" prefactor make it any more possible to show the implication then if it doesn't? | 2023/01/15 | [
"https://math.stackexchange.com/questions/4618633",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/688539/"
] | Let $(a\_n, b\_n, c\_n, d\_n)$ be the quadruple after the $n$-th iteration, where $(a\_0, b\_0, c\_0, d\_0)$ are the initial values and can be arbitrary real numbers, the restriction to positive numbers is not necessary.
Without loss of generality we can assume that $a\_0+b\_0+c\_0+d\_0 = 0$, and consequently $a\_n+b\_n+c\_n+d\_n = 0$ for all $n$.
Then
$$
\begin{align}
a\_{n+1}^2+b\_{n+1}^2+c\_{n+1}^2+d\_{n+1}^2
&= \frac 12 \left( a\_n^2+b\_n^2+c\_n^2+d\_n^2 + a\_nb\_n+b\_nc\_n+c\_nd\_n + d\_n a\_n\right) \\
&= \frac 12 \left( a\_n^2+b\_n^2+c\_n^2+d\_n^2 + (a\_n+c\_n)(b\_n+d\_n)\right) \\
&= \frac 12 \left( a\_n^2+b\_n^2+c\_n^2+d\_n^2 - (a\_n+c\_n)^2\right) \\
&\le \frac 12 \left( a\_n^2+b\_n^2+c\_n^2+d\_n^2 \right) \, .
\end{align}
$$
It follows that
$$
\lim\_{n\to \infty} a\_n^2+b\_n^2+c\_n^2+d\_n^2 = 0
$$
and that implies that the four sequences $(a\_n)$, $(b\_n)$, $(c\_n)$, $(d\_n)$ converge to zero.
---
*Generalization for iterations of tuples with arbitrary length:*
For fixed $m \ge 2$, let $(x\_{n,1}, x\_{n,2}, \ldots, x\_{n,m})$ be the tuple after the $n$-th iteration of the initial tuple $(x\_{0,1}, x\_{0,2}, \ldots, x\_{0,m})$. Again we assume that $x\_{0,1} + x\_{0,2} +\cdots + x\_{0,m} = 0$.
In order to prove that
$$
\lim\_{n \to \infty} x\_{n,1}^2 + x\_{n,2}^2 +\cdots + x\_{n,m}^2 = 0
$$
and consequently $\lim\_{n \to \infty} x\_{n, j} = 0$ for all $1 \le j \le m$, it suffices to prove the following
>
> **Lemma:** Let $m \ge 2$ and $x\_1, x\_2, \ldots, x\_m \in \Bbb R$ with $x\_1 + x\_2 + \ldots + x\_m = 0$. Set $x\_{m+1} = x\_1$. Then
> $$
> \sum\_{j=1}^m \left( \frac{x\_j + x\_{j+1}}{2}\right)^2 \le C\_m \sum\_{j=1}^m x\_j^2
> $$
> with a constant $0 < C\_m < 1$ which depends only on $m$.
>
>
>
*Proof:* Set $S=\sum\_{j=1}^m x\_j^2$ and $S' = \sum\_{j=1}^m \left( \frac{x\_j + x\_{j+1}}{2}\right)^2$. If $S=0$ then $S' = 0$, so from now on we assume that $S > 0$.
$$ \tag{\*}
S' - S = \sum\_{j=1}^m \left( \frac{x\_j + x\_{j+1}}{2}\right)^2
- \sum\_{j=1}^m\frac{x\_j^2+x\_{j+1}^2}{2}
= -\frac 14 \sum\_{j=1}^m (x\_j - x\_{j+1})^2
$$
which already shows that $S' \le S$. But we need a slightly better estimate.
There must be (at least) one index $j$ with $|x\_k| \ge \sqrt{\frac Sm}$, and since the sum of all $x\_j$ is zero, there must be another index $l$ such that $x\_k$ and $x\_l$ have opposite sign. It follows that there is an index $j$ with $|x\_j - x\_{j+1}| \ge \frac 1m \sqrt{\frac Sm}$. This gives a negative upper bound for the right-hand side in $(\*)$, and we get
$$
S \le S - \frac 14 \frac{S}{m^3} = \left( 1 - \frac{1}{4m^3}\right) S \, .
$$
This proves the lemma. | **Proof**
Beginning by defining the iterating sequences
\begin{split}
X\_n& \triangleq(w\_n,x\_n,y\_n,z\_n) \to \left(\frac{w\_n+x\_n}{2},\frac{x\_n+y\_n}{2},\frac{y\_n+z\_n}{2},\frac{z\_n+w\_n}{2}\right) \\
X\_0 & = (a,b,c,d)
\end{split}
So considering :
$$ f (w,x,y,z) \to \left(\frac{w+x}{2},\frac{x+y}{2},\frac{y+z}{2},\frac{z+w}{2}\right) $$
$$ X\_{n+1} =f(X\_n) $$
Yet, for all $(w,x,y,z)$
$$ Df(w,x,y,z) : H=(h\_1,h\_2,h\_3,h\_4) \to \begin{pmatrix} \dfrac{1}{2} & 0 &0 & \dfrac{1}{2}\\ \dfrac{1}{2} & \dfrac{1}{2} & 0 & 0 \\ 0 & \dfrac{1}{2} & \dfrac{1}{2} & 0 \\ 0 & 0 & \dfrac{1}{2} & \dfrac{1}{2}\end{pmatrix}H $$
It follows that for all $(w,x,y,z)$
$$ ||| Df(w,x,y,z) |||\_{\infty}\triangleq\sup\_{||H||\neq 0} \dfrac{||Df(w,x,y,z)(H)||}{||H||}=1/2<1 $$
So by Banach-Picard theorem, it exists one and only one fixed point for $X\_n$ sequence whatever $X\_0$ (finite) is. Then by component combination every $w\_n,x\_n,y\_n,z\_n$ sequences converge.
I let you end the proof to show the unique limit for every of them. |
52,128,013 | I am trying to learn react. I see a lot of style change inside java script so far. As far as I know, the style should onle be managed by css files. But I am not sure this rule also applies to React. What is the best practice for react. For instance, is the following code a clean code, or is changing the style in the React component a smell and need to be refactored? If so, how it could be refactored?
```
“const Color = ({ title, color}) =>
<section className="color">
<h1>{title}</h1>
<div className="color"
style={{ backgroundColor: color }}>
</div>
</section>”
``` | 2018/09/01 | [
"https://Stackoverflow.com/questions/52128013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433619/"
] | I prefer to connect external .css file - it's much more clean.
If there is a need to keep styles in .js I would organize the code in that way:
```
const styles = {
color: 'red',
fontSize: '2rem',
backgroundColor: 'forestgreen'
}
```
And I would apply the styles I need just like here:
```
<div style={{color: styles.color, fontSize: styles.fontSize}}></div>
```
Or, If I need to apply all styles:
```
<div style={styles}></div>
``` | You can also use styled components <https://www.styled-components.com/> |
12,972,583 | I'm having a little trouble using UNION. (at least I suspect UNION is the tool)
I have the following:
Table 1: `us_states.us_state`
Table 2: `fex_tax_by_prov.TAX_PROVINCE`
I would like to use one mysql query to return all states and provinces as one result ('region'). I have something like this but it isn't correct.
```
SELECT *
FROM (
SELECT TAX_PROVINCE as region,
FROM fed_tax_by_prov
UNION
SELECT us_state as region,
FROM us_states
)
```
Any help would be much appreciated. Thanks | 2012/10/19 | [
"https://Stackoverflow.com/questions/12972583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962136/"
] | ```
select us_state as region from us_states
union
select tax_province from fed_tax_by_prov
```
should work as long as the two columns are of the same type, and adding an alias (only needs to be done for first select in the `union`) means you can refer to it in a wrapping `select`, much like you have in your example. | I got it, the problem was that I had an extra `SELECT *` at the beginning of the query.
Much thanks your your help people. |
28,178,554 | I'm trying to remove all Strings that are of even length in a set. Here is my code so far, but I am having trouble getting the index from the iterator in the enhanced-for-loop.
```
public static void removeEvenLength(Set<String> list) {
for (String s : list) {
if (s.length() % 2 == 0) {
list.remove(s);
}
}
}
``` | 2015/01/27 | [
"https://Stackoverflow.com/questions/28178554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3147737/"
] | Java 8 has introduced [Collection.removeIf()](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-), which allows you to do:
```
set.removeIf(s -> s.length() % 2 == 0)
``` | You don't need the index. But you do need the explicit `Iterator`. The iterator has the [`remove()` method](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--), no parameters, that removes the current item from the collection.
```
Iterator<String> itr = list.iterator(); // list is a Set<String>!
while (itr.hasNext())
{
String s = itr.next();
if (s.length() % 2 == 0) {
itr.remove();
}
}
``` |
27,523,372 | I just wrote a method that I'm pretty sure is terribly written. I can't figure out if there is a better way to write this in ruby. It's just a simple loop that is counting stuff.
Of course, I could use a select or something like that, but that would require looping twice on my array. Is there a way to increment several variables by looping without declaring the field before the loop? Something like a multiple select, I don't know. It's even worst when I have more counters.
Thank you!
```
failed_tests = 0
passed_tests = 0
tests.each do |test|
case test.status
when :failed
failed_tests += 1
when :passed
passed_tests +=1
end
end
``` | 2014/12/17 | [
"https://Stackoverflow.com/questions/27523372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use the `#reduce` method:
```
failed, passed = tests.reduce([0, 0]) do |(failed, passed), test|
case test.status
when :failed
[failed + 1, passed]
when :passed
[failed, passed + 1]
else
[failed, passed]
end
end
```
Or with a `Hash` with default value, this will work with any statuses:
```
tests.reduce(Hash.new(0)) do |counter, test|
counter[test.status] += 1
counter
end
```
Or even enhancing this with @fivedigit's idea:
```
tests.each_with_object(Hash.new(0)) do |test, counter|
counter[test.status] += 1
end
``` | ```
hash = test.reduce(Hash.new(0)) { |hash,element| hash[element.status] += 1; hash }
```
this will return a hash with the count of the elements.
ex:
```
class Test
attr_reader :status
def initialize
@status = ['pass', 'failed'].sample
end
end
array = []
5.times { array.push Test.new }
hash = array.reduce(Hash.new(0)) { |hash,element| hash[element.status] += 1; hash }
```
>
> => {"failed"=>3, "pass"=>2}
>
>
> |
69,916,471 | I have created a simple API with FastAPI and I want to export the output in a text file (txt).
This is a simplified code
```
import sys
from clases.sequence import Sequence
from clases.read_file import Read_file
from fastapi import FastAPI
app = FastAPI()
@app.get("/DNA_toolkit")
def sum(input: str): # pass the sequence in, this time as a query param
DNA = Sequence(input) # get the result (i.e., 4)
return {"Length": DNA.length(), # return the response
"Reverse": DNA.reverse(),
"complement":DNA.complement(),
"Reverse and complement": DNA.reverse_and_complement(),
"gc_percentage": DNA.gc_percentage()
}
```
And this is the output
```
{"Length":36,"Reverse":"TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT","complement":"ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA","Reverse and complement":"AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA","gc_percentage":5.142857142857143}
```
The file I would like to get
```
Length 36
Reverse TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT
complement ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA
Reverse and complement AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA
```
There is a simple way to do this. This is my first time working with APIs and I don't even know how possible is this | 2021/11/10 | [
"https://Stackoverflow.com/questions/69916471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4913254/"
] | ```
dict1={"Length":36,"Reverse":"TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT","complement":"ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA","Reverse and complement":"AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA","gc_percentage":5.142857142857143}
with open("output.txt","w") as data:
for k,v in dict1.items():
append_data=k+" "+str(v)
data.write(append_data)
data.write("\n")
```
Output:
```
Length 36
Reverse TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT
complement ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA
Reverse and complement AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA
gc_percentage 5.142857142857143
``` | I gonna assume that you have already got your data somehow calling your API.
```
# data = request.get(...).json()
# save to file:
with open("DNA_insights.txt", 'w') as f:
for k, v in data.items():
f.write(f"{k}: {v}\n")
``` |
38,831,058 | Given the following code:
```
#if MACRO_WITHOUT_A_VALUE
int var;
#endif
int main(){}
```
When compiled with, `g++ -std=c++1z -Wundef -o main main.cpp`,
it produces the following warning:
```
main.cpp:1:5: warning: "MACRO_WITHOUT_A_VALUE" is not defined [-Wundef]
#if MACRO_WITHOUT_A_VALUE
^
```
I'd like to keep the warning flag enabled, but suppress this particular instance.
I apply the following:
```
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wundef"
#pragma GCC diagnostic push
#endif
#if MACRO_WITHOUT_A_VALUE
int var;
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
int main(){}
```
This only solves the problem in `clang++`.
The command `clang++ -std=c++1z -Wundef -o main main.cpp` builds without warnings.
The command `g++ -std=c++1z -Wundef -o main main.cpp` builds with the same `[-Wundef]` warning as before.
**How can I suppress `-Wundef` warnings in `g++`?**
```
g++ (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0
clang version 3.8.0
``` | 2016/08/08 | [
"https://Stackoverflow.com/questions/38831058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/908939/"
] | What I've done before when third party headers were inducing warnings was to wrap them in my own private header that uses `#pragma GCC system_header` to just silence all the warnings from that header. I use my own wrapper to keep the includes neat and allow for an additional customization point in the future if needed. | This isn't disabling the warning, but fixing the preprocessor code to avoid it.
The below tests are based on a similar issue [here](https://stackoverflow.com/a/48403396/1888983), using `clang -Weverything`...
```
#define ZERO 0
#define ONE 1
#define EMPTY
// warning: 'NOTDEFINED' is not defined, evaluates to 0 [-Wundef]
#if NOTDEFINED
#warning NOTDEFINED
#endif
// false
#if ZERO
#warning ZERO
#endif
// true
#if ONE
#warning ONE
#endif
// error: expected value in expression
#if EMPTY
#warning EMPTY
#endif
// false
#if defined(NOTDEFINED) && NOTDEFINED
#warning NOTDEFINED
#endif
// false
#if defined(ZERO) && ZERO
#warning ZERO
#endif
// true
#if defined(ONE) && ONE
#warning ONE
#endif
// error: expected value in expression
#if defined(EMPTY) && EMPTY
#warning EMPTY
#endif
```
The one liner `#if defined(SOME_MACRO) && SOME_MACRO` can avoid this warning. To explicitly handle the case...
```
#if defined(DEBUG_PRINT)
#if DEBUG_PRINT
... true
#else
... false
#endif
#else
#error DEBUG_PRINT must be defined
#endif
```
To handle `EMPTY` see this: [How to test if preprocessor symbol is #define'd but has no value?](https://stackoverflow.com/questions/3781520/how-to-test-if-preprocessor-symbol-is-defined-but-has-no-value) |
8,423,410 | I'm not java developer, but I need to test a code. I installed jdk and i tested Hello Word it worked fine but When i try to javac this another script, I'm gettings this error.
My Code:
```
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import javax.microedition.io.Connector;
import java.io.IOException;
public class SMSUtility {
public static void sendMessage(String msisdn, String text)
throws IOException {
// Open connection
MessageConnection con = (MessageConnection)
Connector.open("sms://+" + msisdn);
// Create new message
TextMessage message = (TextMessage)
con.newMessage(MessageConnection.TEXT_MESSAGE);
// Set text
message.setPayloadText(text);
// Send message
con.send(message);
// Close connection
con.close();
}
}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8423410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079325/"
] | You need to also check in `PHP.ini` file
```
extension = php_openssl.dll
```
is enable or not, if not then just enable that by removing ; sign
```
allow_url_fopen = on
``` | I was using **file\_get\_contents** this way:
file\_get\_contents("<https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=>".$screenname."&count=5");
And that was not working, so I changed https to http and after that it is working well.
```
file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=".$screenname."&count=5");
``` |
373,919 | I have a cross-section of $x$, $y\_1$, and $y\_2$. These are individual level data used in labor economics. I have random variation in $x$ and I'm interested in the effect of $x$ on $y\_1$. It is well established in earlier research that $x$ causally affects $y\_2$ positively. Economic intuition says that $y\_2$ will affect $y\_1$ positively as well. Hence, $x$ has an effect on $y\_1$ through $y\_2$.
Estimating the regression $y\_1 = a\_1+a\_2x + a\_3y\_2$ I believe is problematic since $y\_2$ is endogenous. What type of model(s) can I estimate to identify the "direct" effect of $x$ on $y\_1$ (the $a\_2$ parameter) while controlling for the effect $x$ has on $y\_1$ through $y\_2$? | 2018/10/26 | [
"https://stats.stackexchange.com/questions/373919",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/224884/"
] | Say you have a model $y\_i = f(X\_i;\beta) + e\_i$, where $e\_i \sim N(0,\sigma^2)$, and you obtain an estimate of $\beta$, ($\hat \beta$). Then, by definition, you also have a "predicted error term" $\hat e\_i$, which is
$$ \hat e\_i \equiv y\_i - f(X\_i;\hat \beta) $$
When it comes to "predicting" $y\_i$, I can distinguish two scenarios:
1. If you are predicting $y\_i$ "in sample", i.e. based on **observed** values $X\_i$, then you are thinking on
$$ \hat y\_i = f(X\_i;\hat \beta) $$
It is obvious you should not include the predicted error term $\hat e\_i$ above, because you will get the exact observed data, i.e. $y\_i$.
2. If you are predicting $y\_i$ "out of sample", i.e. based on a given value of $X\_i$ which is of interest to you but not part of the sample (i.e. they do not belong to an observed individual/unit) then you "should" predict the error term too. However, in most applications (e.g. when the model includes a constant term), your best prediction for such error is zero! So here you just want to predict using
$$ \hat y\_i = f(Z\_i;\hat \beta) $$
where $Z\_i$ is a given set of values for $X\_i$ of your interest. | If the model you propose to describe your process neglects an error term,
$y = \beta x$
You are stating the model is 100% perfectly accurate and the process that generates $y$ will never deviate from the value $\beta x$. For example, your data may look like:
```
y x
5 1
10 2
15 3
```
If the model you propose includes an error term:
$y = \beta x + \epsilon$
You are stating the model is not 100% perfectly accurate and the process that generates $y$ will sometimes deviate from the value $\beta x$. For example, your data may look like:
```
y x
6 1
11 2
14 3
```
---
TLDR; Yes, it is prudent to assume an error term when modeling a real life data generating process. |
26,158,515 | So, I just want to know if its possible to slip in any code or a ternary operator inside the termination bit of a for loop. If it is possible, could you provide an example of a ternary operator in a for loop? Thanks!
```
for (initialization; termination; increment) {
statement(s)
}
``` | 2014/10/02 | [
"https://Stackoverflow.com/questions/26158515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4001407/"
] | The `termination` clause in the `for` statement (if supplied - it's actually optional) can be any expression you want so long as it evaluates to a `boolean`.
It must be an *expression*, not an arbitrary code block. | Yes you can since only thing here is `termination` should be a `boolean`
```
for (int i=0; i==10?i<5:i<6; i++) {
}
```
But what is the point of this?
Things to remember. Termination condition of a `for` loop should be a `boolean` |
9,639,007 | I have a list of constant strings that I need to display at different times during my Java program.
In C I could define the strings like this at the top of my code:
```c
#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"
```
I am wondering what is the standard way of doing this kind of thing in Java? | 2012/03/09 | [
"https://Stackoverflow.com/questions/9639007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1259828/"
] | Typically you'd define this toward the top of a class:
```
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
```
Of course, use the appropriate member visibility (`public`/`private`/`protected`) based on where you use this constant. | You can use
```
public static final String HELLO = "hello";
```
if you have many string constants, you can use external property file / simple
"constant holder" class |
43,091,563 | noob question:
Any examples of how to get parameters from the connected camera, such as supported resolutions?
I'm using DirectX June 2010.
Code to create a device:
```
HWND m_hwnd;
HDC *phdc;
IDirect3D9 *m_pD3D;
IDirect3DDevice9 *m_pDevice;
IDirect3DSwapChain9 *m_pSwapChain;
HRESULT DrawDevice::CreateDevice(HWND hwnd)
{
if (m_pDevice)
{
return S_OK;
}
// Create the Direct3D object.
if (m_pD3D == NULL)
{
m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (m_pD3D == NULL)
{
return E_FAIL;
}
}
HRESULT hr = S_OK;
D3DPRESENT_PARAMETERS pp = { 0 };
D3DDISPLAYMODE mode = { 0 };
hr = m_pD3D->GetAdapterDisplayMode(
D3DADAPTER_DEFAULT,
&mode
);
if (FAILED(hr)) { return hr; }
hr = m_pD3D->CheckDeviceType(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
mode.Format,
D3DFMT_X8R8G8B8,
TRUE // windowed
);
if (FAILED(hr)) { return hr; }
pp.BackBufferFormat = D3DFMT_X8R8G8B8;
pp.SwapEffect = D3DSWAPEFFECT_COPY;
pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
pp.Windowed = TRUE;
pp.hDeviceWindow = hwnd;
hr = m_pD3D->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hwnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
&pp,
&m_pDevice
);
if (FAILED(hr)) { return hr; }
m_hwnd = hwnd;
m_d3dpp = pp;
return hr;
}
```
My purpose is to give the user a list of options to choose...
Thanks !! | 2017/03/29 | [
"https://Stackoverflow.com/questions/43091563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7268713/"
] | I also have this problem when run in iOS 10.3.1 with xcode 8.3.2
Restart device, It will work well | I had similar issue. Tried below steps :
1. Quit Xcode `(cmd + Q)`
2. Clean project `(cmd + shift +k)`
3. Delete Derived data `(cmd + comma)`
But these didn’t worked. Instead **restarting device worked**! |
5,916,338 | I have such HTML node:
```
<div id='parent'>
<a href="#">test</a>
Need this
</div>
```
How to get 'Need this' text if I have handle for `parent` object?
I tried something like: `$('#parent').text()` but it also returns 'test'.
---
p.s. **Nothing** about editing html! I just have such content and I need to parse it. | 2011/05/06 | [
"https://Stackoverflow.com/questions/5916338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87152/"
] | ```
var temp = $('#parent').clone();
temp.children().remove();
alert(temp.text());
```
working example: <http://jsfiddle.net/hunter/H6jQp/> | ```
var $text = $("#parent").contents().filter(function(){ return this.nodeType != 1; });
alert($text.text());
```
Seems to do the trick. ([jsFiddle](http://jsfiddle.net/JfSvd/)) |
662,134 | I was thinking about backing up a Hyper-V host to the cloud and a potentially crazy idea came to mind.
With Google Drive, you can get 1TB of storage for 2 bucks a month. This would be more than sufficient to backup all of my VMs.
Is this a good idea for machines that don't contain critical / highly confidential information?
I am running Hyper-V Core 2012 R2. How would I go about doing this, if I were to ignore all warnings?
An Issue I see with this is that does GD even support incremental backups of a VHDX file or will it just sync over the whole drive again?
Thanks. | 2015/01/24 | [
"https://serverfault.com/questions/662134",
"https://serverfault.com",
"https://serverfault.com/users/243438/"
] | Like mentioned above, it's not state-of the art but you could do [Export-VM](https://docs.microsoft.com/en-us/powershell/module/hyper-v/export-vm?view=win10-ps) in a scheduled task if google drive is visible from the core hyper-v, with a drive letter.
It appears you can mount google drive as a drive letter using [subst](https://ss64.com/nt/subst.html).
Let me know if you need assistance with the scripts. | TLDR - this would be a bad plan for a business.
Each sync would be a full sync. Backing up the VHDX file will backup the data, but it isn't a full VM backup. If you restored over the existing VHDX you wouldn't notice, but if you had to restore to a new server, you'd lose the VM configuration.
If you just need a point in time, you could do an export from within Hyper-V to get the data and configuration.
You might look at a product like Veeam to create the backups to another server and sync those to Google for an offsite. |
37,058,528 | I am a beginner to coding and am trying to shrink down a large, error prone piece of code. Pretty much I want it so
```
if (tileBlocked[row - 1][col] == true)
{
add tileAir[row - 1][col] to averaging
}
```
such that I will find the average of the values in array tileAir only if tileBlocked does not list that area as blocked. I searched around and the only thing I found was Averageif, which is only for excel as far as I can tell. Is there any equivalent or some way in which I could decrease the size of this chunk of code and allow for better expand-ability?
Right now this is my current code:
```
for (int row = 1; row < 255; ++row) // Repeats for all rows, skipping the first and final row
{
for (int col = 1; col < 255; ++col) // Repeats for all columns, skipping the first and final column
{
bool check[4] = { tilesBlocked[row - 1][col], tilesBlocked[row][col - 1], tilesBlocked[row][col + 1], tilesBlocked[row + 1][col] }; // Creates an Array for testing what tiles should be ommited from the calculation
if (tilesBlocked[row][col][0] == true) // If the tile being calculated is blocked, skip it
{
}
else if (check[0] == true && check[1] == true && check[2] == true && check[3] == true)
{
}
else if (check[0] == false && check[1] == false && check[2] == false && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col - 1] + tilesOxygen[row][col + 1] + tilesOxygen[row + 1][col]) / 5);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == false && check[2] == false && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col - 1] + tilesOxygen[row][col + 1]) / 4);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == false && check[2] == true && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col - 1] + tilesOxygen[row + 1][col]) / 4);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == false && check[2] == true && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col - 1]) / 3);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == true && check[2] == false && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col + 1] + tilesOxygen[row + 1][col]) / 4);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == true && check[2] == false && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row][col + 1]) / 3);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == true && check[2] == true && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col] + tilesOxygen[row + 1][col]) / 3);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == false && check[1] == true && check[2] == true && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row - 1][col]) / 2);
tilesOxygen[row - 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == false && check[2] == false && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col - 1] + tilesOxygen[row][col + 1] + tilesOxygen[row + 1][col]) / 4);
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == false && check[2] == false && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col - 1] + tilesOxygen[row][col + 1]) / 3);
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == false && check[2] == true && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col - 1] + tilesOxygen[row + 1][col]) / 3);
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == false && check[2] == true && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col - 1]) / 2);
tilesOxygen[row][col - 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == true && check[2] == false && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col + 1] + tilesOxygen[row + 1][col]) / 3);
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == true && check[2] == false && check[3] == true)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row][col + 1]) / 2);
tilesOxygen[row][col + 1] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else if (check[0] == true && check[1] == true && check[2] == true && check[3] == false)
{
tilesOxygen[row][col] = ((tilesOxygen[row][col] + tilesOxygen[row + 1][col]) / 2);
tilesOxygen[row + 1][col] = tilesOxygen[row][col];
tilesOxygen[0][col] = 0;
tilesOxygen[row][0] = 0;
tilesOxygen[255][col] = 0;
tilesOxygen[row][255] = 0;
}
else
{
std::cout << "Something Broke";
}
}
}
```
As you can see this is highly unexpandable and prone to error. In this specific example tileAir is replaced with tileOxygen. | 2016/05/05 | [
"https://Stackoverflow.com/questions/37058528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6288812/"
] | **Dont do it**
```
$scope.example = () => {
$scope.example = 'object';
}
``` | @Integrator wrote correct answer. Just want to add to access to the form from your angular controller you also need to write $scope.formName. For example:
```
$scope.search.username.$invalid = true;
```
In this way you set form element to invalid. So in your case angular confuse form with method. It is a good practice to set form name like: xxxxForm to avoid such a conflicts |
254,004 | I'm trying to diagnose a relay control for a motor which was wired by someone else.
**QUESTION: How does this theoretically work? What is it called?**
[](https://i.stack.imgur.com/1P6Ws.jpg)
Pictured here is the relay which controls a bidirectional motor.
[](https://i.stack.imgur.com/5iEkO.png)
I believe the way it works is
* there are two poles for this single relay, represented by A1 and B1
* by default, when no control voltage is applied across terminals (C+/C-),
+ pole A1 is connected to A3
+ pole B1 is connected to B3
* when a control voltage is applied across terminals (C+/C-),
+ pole A1 is connected to A2
+ pole B1 is connected to B2
[](https://i.stack.imgur.com/P6jG4.png)
The confusing thing for me is the way this relay is wired: It seems like both circuits are never completed.
* **How does this theoretically work?**
* **Am I confused about how the relay works?**
* **Is the relay miswired?**
+ It seems like something should be connected to A2,A3,B2,B3. But what? | 2016/08/24 | [
"https://electronics.stackexchange.com/questions/254004",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/42934/"
] | Two SPDT latching? relays with a single bipolar coil which enables either Set or Reset. Forward or Reverse...
The poles go to the motor while the "throws" go to V+ and V- cross connected for bipolar motor direction power control.
Only doubt is how stop is selected before changing direction. | I think your drawings are correct.
Think of it like this: to reverse the motor, you have to reverse the current going through the motor.
Your motor wiring looks like

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fhuxzY.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
in this state, A1 is connected to the "positive" end of our voltage source, and B1 is connected to the negative one.
---
now, switching the state of the relais, the voltage now flows in the different direction through the motor, reversing its rotation.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2feg9GD.png) |
349,148 | What i know is that "Volume" is a undefined notion in general, and the best approach to define volume is by Lebesgue measure.
I'm studying linear-algebra right now and the text says that "absolute value of determinant of n vectors is equal to n-dimensional volume formed by vectors". (Note that it is not *defined* to be, but it is *equal* to)
What is the definition of $n$-dimensional volume? and where can i see the proof that the Lebesgue measure of $n$-dimensional parallepiped is equal to the determinant of vectors forming the parallepiped?
It was not that easy to me to prove that the Lebesgue measure of $n$-dimensional rectagular parallelepiped is equal to the intuitive Volume i.e.$ \prod |I\_k|$. So i guess the proof for equality of the Lebesgue measure and determinant would be really tedious and not that easy.. Where can i see this proof if there is, or what is the definition of volume in linear-algebra? | 2013/04/02 | [
"https://math.stackexchange.com/questions/349148",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61597/"
] | There is a proof in the book *Lebesgue integration and measure* by Alan Weir in section 6.3, called "The geometry of Lebesgue measure". | Suppose you have $n$ vectors $v\_1,v\_2,\dotsc,v\_n$ forming some $n$-parallelotope $P \subset \mathbb R^n$ of non-zero volume. Then the matrix $A = v\_1|v\_2|\dotsb|v\_n$ will be in $GL(\mathbb R^n)$ and $A([0,1]^n) = P$.
From the theory of translation invariant Radon measures on $\mathbb R^n$ it is known that any such measure $\mu$ must be equal to $cm\_n$ for some $c \in (0,\infty)$. And $A^{-1}m\_n$, the measure defined by $(A^{-1}m\_n)(E) = m\_n(A^{-1}(E))$, is indeed such a measure. Hence there is a constant $c\_A$ such that $m\_n(A(E)) = c\_Am\_n(E)$ for all Borel measurable $E \subseteq \mathbb R^n$. So what is this mysterious $c\_A$? Why, it is exactly $m\_n(A([0,1]^n))$, the volume of $P$.
But we can say more. The matrix $A$ above can be an arbitrary one in $GL(\mathbb R^n)$, so we can define a map $A \mapsto c\_A$ and it turns out to be a homomorphism of groups. Moreover, it's easily seen for orthogonal matrices and for symmetric positive definite matrices that $c\_A = |\det A|$. For a general matrix $A \in GL(\mathbb R^n)$ we can write $A=OS$ where $O$ is orthogonal and $S$ is symmetric positive definite, and we get that $c\_A = |\det A|$ for all invertible $A$. |
502,727 | How can I record keyboard actions with the timestamp, either to console, or preferably to a file?
I have showkey output like:
```
keycode 28 release
keycode 30 press
keycode 30 release
keycode 48 press
keycode 48 release
```
And I'd like it to be:
```
keycode 30 press 1551027529
keycode 30 release 1551027532
keycode 48 press 1551027534
keycode 48 release 1551027536
keycode 46 press 1551027542
keycode 46 release 1551027548
keycode 32 press 1551027549
keycode 32 release 155102751
```
I looked at [How to modify output in bash command pipeline](https://unix.stackexchange.com/questions/113515/how-to-modify-output-in-bash-command-pipeline) and have tried:
```
sudo showkey | awk -v date="$(date +%s)" '{print $1 date}'
```
And there is no output at all.
I've tried a `while` loop:
```
echo MY_PASSWORD |
stdbuf -o0 sudo -S showkey |
while read line;
do
echo "$line":$(date +%s) >> /home/reedbear/user_scripts/output.txt;
done
```
And my output shows the keypresses, but they all have the same time stamp, as I assume the while loop is evaluated with the full output of `showkey` when it is finished.
I don't know what `stdbuf` does, but I saw it somewhere last night. It does the same thing without it. | 2019/02/24 | [
"https://unix.stackexchange.com/questions/502727",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/113056/"
] | I somehow fixed it by adding a new stylesheet in qt5ct, with the content below:
```css
QMenuBar {
}
```
This above code pretty much does nothing. And I'm pretty sure any selector would work. But I am not sure why adding a simple blank CSS definition would fix the problem.
Before:
[](https://i.stack.imgur.com/yRogE.png)
After:
[](https://i.stack.imgur.com/vY3Np.png)
[](https://i.stack.imgur.com/qVUgl.png)
I'm on Ubuntu 18.04 using Gnome 3 desktop environment with adwaita-qt built from source as Qt5 style. | On Gnome 41.2, what worked for me was a mix of [user onetusers' answer](https://unix.stackexchange.com/a/660222/507025) and user [Silence and I's answer](https://unix.stackexchange.com/a/502818/507025). I followed those steps:
1. I added in `/etc/environment` the line:
```bsh
QT_QPA_PLATFORMTHEME='qt5ct'
```
so that the qt apps use the `qt5ct` app settings (if you do not do that `qt5ct` will complain that this variable's value is currently `gnome`). This made most of the app be dark except for the view pannel which was white with light font.
By this point Dolphin looked like this:
[](https://i.stack.imgur.com/FfZPc.png "Dolphin screenshot")
If I clicked `slipt` I got:
[](https://i.stack.imgur.com/91HYG.png "Dolphin screenshot after clicking slipt")
2. I added these lines
```css
[Colors:View]
BackgroundNormal=#2E2E2E
```
to the file `~/.config/kdeglobals`. This made the background dark so I could then read the files names which are displayed in a light color.
[](https://i.stack.imgur.com/LrXDW.png "Dolphin screenshot with dark background")
**Remark:**: the color used here is different from [user onetusers' answer](https://unix.stackexchange.com/a/660222/507025) because ze suggested a blueish dark gray color (#31363B) while I used pure dark gray (#2E2E2E) which I color picked from the background of the Nautilus files app with the adwaita dark theme enabled.
There still remained a blue border around the view (If you have two dolphin tabs in split view, the color we picked and the blue border appear only in the focused tab. #2E2E2E makes the focused tab stand out by being darker and it seems enough for me and more inline with the default files manager. IMO the blue border and blueish hue to the background are superfluos and detract from the overall theme). So I did the following step.
3. Through `qt5ct`, I applied the style sheet `fusion-fixes.qss` so that the blue borders disappear (The sheet is already there you need only check the box and apply).
This gave me this look:
[](https://i.stack.imgur.com/qsAZy.png "Dolphin screenshot after applying stylesheet")
which is similar to Nautilus:
[](https://i.stack.imgur.com/CVQcF.png "Nautilus screenshot")
**Remark:** I did all of this on Arch Linux 5.15.10 having installed the packages `qt5ct 1.5-1` and `gnome-themes-extra 3.28` (so that I could set the adwaita dark theme via gnome tweaks). |
64,037,496 | I am implementing some of the firebase SDKs into my pods, but I am having an issue with versioning them. I want to set Firebase 6.33. I did check the pod spec of this version and updated my pods according to that.
```
pod 'Firebase', '~> 6.33.0'
pod 'FirebaseCore', '~> 6.10.3'
pod 'FirebasePerformance', '~> 3.3.0'
pod 'FirebaseRemoteConfig', '~> 4.9.0'
pod 'FirebaseAnalytics', '~> 6.8.3'
pod 'FirebaseCrashlytics', '~> 4.6.1'
```
When I use the codes above, it gives me this error on jenkins:
>
> None of your spec sources contain a spec satisfying the dependencies:
> Firebase (~> 6.33.0), Firebase (= 6.33.0, ~> 6.33.0).
>
>
>
I did `pod deintegrate` first and `pod install` to do a clean installation. It doesn't give the error on my MacBook but on jenkins.
podspec.json: <https://github.com/CocoaPods/Specs/blob/master/Specs/0/3/5/Firebase/6.33.0/Firebase.podspec.json> | 2020/09/23 | [
"https://Stackoverflow.com/questions/64037496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6292521/"
] | For who is here with a Mac M1, trying to run `pod install --repo-update` in the VSCode terminal without success, the solution I found was:
* Find the native Terminal on Applications
* Make sure it is running with Rosetta (right click on Terminal > Obtain Information > Check Open With Rosetta)
* Open the terminal
* `cd path_to_your_ios_folder` and run `pod install --repo-update`. That should work!
I am using:
```
Pod: 1.11.0
firebase_core: ^1.6.0
firebase_crashlytics: ^2.2.1
firebase_analytics: ^8.3.1
firebase_messaging: ^10.0.6
flutter: 2.2.3
``` | Why all the different versions of firebase specified? For me I had three different Firebase related plugins (Analytics / Dynamiclinks / Firebasex). Each of these had a different source it was trying to pull from (some v 7.0.0 and some v 6.33.0). I went into the podfile and changed all of the versions to 6.33.0 and was able to build then. |
13,119,441 | I am coding some pages in HTML and CSS which will contain samples of code. I want to have the grey box like the do on WikiPedia (I know this is done with Media Wiki). An example page is:
<http://en.wikipedia.org/wiki/Dd_(Unix)#Uses>
You will see the code has a grey box with dotted lines around. Also higher up the page where just 'dd' is used the text is monospace but no box is shown.
Could you tell me how I get the same styles with CSS around the tag?
Thanks
Peter Jones | 2012/10/29 | [
"https://Stackoverflow.com/questions/13119441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782547/"
] | **HTML**
```
<code>dd if=/dev/sda of=MBR.img bs=512 count=1</code>
```
**CSS**
```
code{background:#F8F8FF; border:black dashed 1px; padding:6px}
```
**[DEMO](http://jsfiddle.net/jk6wk/)** | Just use an any inspecting tool (like, e.g., Firebug) to see, what CSS has been used on a page. As for your example, this is the following:
```
{
background-color: #F9F9F9;
border: 1px dashed #2F6FAB;
color: black;
line-height: 1.1em;
padding: 1em;
}
```
PS: If you want to have code highlighting, have a look at [highlight.js](http://softwaremaniacs.org/soft/highlight/en/). |
140,296 | I am a software engineer upgrading a piece of manufacturing software on site. This is only my third time going onsite. So to summarize, this has been a nightmare. I'm under-qualified for this particular onsite assignment and I warned the project lead about it. However, I agreed that I would give it my best try. A 2 day project is now going on its 6th day.
A solution to fix the issue was finally found and I'll be driving back home tomorrow, which is Sunday. The drive is 11 hours long and I typically work Monday through Friday. Monday, my company is expecting me to show up for work like any other week, but I've completely missed my weekend. I haven't seen my family since last Sunday and I need to catch up with "life".
Is it typically acceptable to ask for a day off to avoid working 12 days straight(2 driving, 10 working)? I'm salaried by the way. | 2019/07/13 | [
"https://workplace.stackexchange.com/questions/140296",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/106806/"
] | **Definitely ask for a day off.** Be ready for a few different potential responses:
1. **Monday might not be the best day to take** (or whichever day you request). Be ready with some alternatives (e.g., making your next weekend a long weekend or adding an extra day to a holiday break).
2. **No extra days off, but you can take a PTO day**. You might not be able to get an extra day off, but you could certainly ask to take one of your paid-time-off days (vacation, sick day, etc.).
3. **"I'll find a way to make it up to you."** Your manager/supervisor might not have a lot of options or have the bandwidth to handle a day off for you right now. Let the topic go for a few weeks and bring it back up if you feel like you haven't been made whole.
4. **Nothing to be done.** It's reasonable to expect work to go long some times. There will also be (and have also been) days when you can sneak out a little early or take a little longer lunch than would be strictly allowed. Hours can be a give and take that comes in fits and starts. | This answer may not be 100% relevant due to aspects of your working contract, but maybe you can take some aspects from it. You should really take a close look at employment law where you are from and your contract.
If you've been asked to drive 11 hours to get on-site, that should really be considered to be on-the-job. If you're working significantly beyond your regular hours, you should be getting paid overtime or have time in lieu. If you're getting paid overtime, just use some of your annual leave to take time off. If you have time in lieu, use that.
So, it is no problem to ask for time off. Ideally you should organise this as soon as possible.
Looking forward, you probably need to have a discussion with your boss about having a better arrangement. Let's look at the costs of the business if you drive to be on-site:
* Fuel costs for the car
* Wages for the employee for the days the employee is travelling
* Insurance (or risk) for the employee travelling on the road
* Extra nights' accommodation
Depending on location and availability, it would probably be cheaper for the business to fly the employee to be on-site (including taxi to and from the airport). In addition, the employee would be able to depart on the first day they are due to start work, and fly home on the last day. This means the employee is less likely to take leave on the days before and days after, and also will have higher job satisfaction.
Doing a rough calculation for where I'm from, the fuel costs alone approach the cost of the plane ticket.
I fully understand the factors will be different depending on where you're from. |
4,958,189 | As I've already figured out, there is at least six of them: `!@#$%&`.
Here is snip:
```
Dim A!, B@, C#, D$, E%, F&
Debug.Print "A! - " & TypeName(A)
Debug.Print "B@ - " & TypeName(B)
Debug.Print "C# - " & TypeName(C)
Debug.Print "D$ - " & TypeName(D)
Debug.Print "E% - " & TypeName(E)
Debug.Print "F& - " & TypeName(F)
```
Outputs
```
A! - Single
B@ - Currency
C# - Double
D$ - String
E% - Integer
F& - Long
```
Where is documentation on this syntax sugar?
What other possible suffixes are there?
Is there one for Date? | 2011/02/10 | [
"https://Stackoverflow.com/questions/4958189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194373/"
] | These suffixes are *type hints*, and the link in the accepted answer is outdated.
```
Dim someInteger% '% Equivalent to "As Integer"
Dim someLong& '& Equivalent to "As Long"
Dim someDecimal@ '@ Equivalent to "As Currency"
Dim someSingle! '! Equivalent to "As Single"
Dim someDouble# '# Equivalent to "As Double"
Dim someString$ '$ Equivalent to "As String"
Dim someLongLong^ '^ Equivalent to "As LongLong" in 64-bit VBA hosts
```
So you had them all, except `^` for `LongLong`, introduced in VBA7 for 64-bit host applications. Exactly why Microsoft introduced a new type hint for a new value type is beyond me though.
It's more *syntax poison* than *syntax sugar* though, and dates all the way back from ancestral, dinosaurian versions of BASIC before the `As` clause was a thing, for example in this Commodore 64 BASIC 2.0 fizzbuzz code:
```
1000 REM INIT VARIABLES
1010 LET FIZZ$ = "FIZZ"
1011 LET BUZZ$ = "BUZZ"
1020 LET FIZZ% = 3
1021 LET BUZZ% = 5
1030 LET MIN% = 1
1031 LET MAX% = 15
1100 PRINT FIZZ$ + ":" + STR$(FIZZ%)
1101 PRINT BUZZ$ + ":" + STR$(BUZZ%)
1102 PRINT FIZZ$ + BUZZ$ + ":" + STR$(FIZZ%*BUZZ%)
1105 PRINT
```
As you can see, type hints aren't the only paleo-code that VBA supports: line numbers, `Rem` comments, and explicit `Let` value assigments were also a thing in 1982. Avoid them at all costs.
In literals, prefer explicit conversions over type hints:
```
Debug.Print TypeName(32&) 'prints Long
Debug.Print TypeName(CLng(32)) 'prints Long
```
>
> *Ask yourself not whether you **can**, ask yourself whether you **should**.* -- unknown
>
>
> | A full(?) list is here <http://support.microsoft.com/kb/110264> under Variable and Function Name Prefixes. As Remou said - they are not recommended (the article says that use is "discouraged"). I believe you covered them all in your list. Date is technically a variant (stored as a floating point) so no shortcut for that one. |
4,212,992 | I am an Android developer and I want to write an `if` statement in my application. In this statement I want to check if the default browser (browser in Android OS) is running. How can I do this programmatically? | 2010/11/18 | [
"https://Stackoverflow.com/questions/4212992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511853/"
] | Add the below Helper class:
```
public class Helper {
public static boolean isAppRunning(final Context context, final String packageName) {
final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
if (procInfos != null)
{
for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
if (processInfo.processName.equals(packageName)) {
return true;
}
}
}
return false;
}
}
```
Now you can check from the below code if your desired App is running or not:
```
if (Helper.isAppRunning(YourActivity.this, "com.your.desired.app")) {
// App is running
} else {
// App is not running
}
``` | ```
fun Context.isAppInForeground(): Boolean {
val application = this.applicationContext
val activityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningProcessList = activityManager.runningAppProcesses
if (runningProcessList != null) {
val myApp = runningProcessList.find { it.processName == application.packageName }
ActivityManager.getMyMemoryState(myApp)
return myApp?.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
return false
}
``` |
269,468 | Reading contemporary histories of the First World War, I noticed that at the start the nation in the Balkans is referred to as *Servia*, but in numbers published after the back half of 1916, it has turned into *Serbia*.
Is there any particular reason for this?
Consulting [Google NGrams](https://books.google.com/ngrams/graph?content=Serbia%2C%20Servia&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2CSerbia%3B%2Cc0%3B.t1%3B%2CServia%3B%2Cc0) gives:-
[](https://i.stack.imgur.com/ht6yH.png)
which seems to correspond to my observation.
**Edit** Replaced Google NGram with version using capitalised names, as suggested by [Steven Littman](https://english.stackexchange.com/users/109885/steven-littman); the result makes rather more sense. | 2015/08/27 | [
"https://english.stackexchange.com/questions/269468",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/305/"
] | From a not credible [source](http://www.sciforums.com/threads/servia-serbia.135160/):
>
> In Ancient Greek, the letter **Beta** was pronounced like English **B**. But in Modern Greek, it's pronounced like English **V**. So "Serbia" became "Servia."
>
>
>
and from another similar [source](http://www.funtrivia.com/askft/Question101736.html) :
>
> It is called **Serbia** using the **Cyrillic** script and **Servia** when using the **Latin** script.
>
>
>
and finally a credible one could be find at <http://paperspast.natlib.govt.nz/cgi-bin/paperspast?a=d&d=NOT19150305.2.51>
[](https://i.stack.imgur.com/3T6rY.gif) | Servia was the medieval Latin spelling of Serbia according to Etynomline.
[Servia](https://en.wikipedia.org/wiki/Servia):
>
> * Historical English term, taken from Greek language, used in relation with Serbia, Serbs or the Serbian language. Wikipedia
>
>
>
[Serb](http://www.etymonline.com/index.php?term=Serb):
>
> * 1813, but in reference to the Wends; 1861 as "native of Serbia," from Serbian Srb, perhaps from a root meaning "man." Serbian is attested from 1848 as a noun, 1876 as an adjective. More common in 19c. was Servian.
>
>
>
[Servian](http://www.etymonline.com/index.php?term=Servian&allowed_in_frame=0):
>
> * 754 (n.), 1723 (adj.), from Medieval Latin Servia, from Serb Serb (see Serb).
>
>
>
Etymonline |
23,555 | **Background**
As background, I have found that taylor expansion provides poor estimates of a function at extreme parameter values. Indeed, the approximation at extreme values can get worse (more rapid exponential increase) as the order of the taylor series increases.
This seems intuitive, but I don't know that it is a rule... or if there is a proof.
**Questions**
1. Do all polynomials with order $> 1$ go to $\pm$ infinity?
2. Is there a good reference where I can find answers to a qustion such as this? | 2011/02/24 | [
"https://math.stackexchange.com/questions/23555",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/3733/"
] | Yes all non-constant polynomials are unbounded. You could see [Liouville's Theorem](http://en.wikipedia.org/wiki/Liouville%27s_theorem_%28complex_analysis%29), or just notice that the leading coefficient of the polynomial will dominate. That is if I look at $$p(x)=a\_n x^n +a\_{n-1}x^{n-1}+\cdots+a\_1x+a\_0$$ then as $x\rightarrow\infty$ we have $p(x)\sim a\_nx^n$ which goes to infinity.
Edit: I will elaborate, but it may not be needed, and may not clarify things further. Factoring out $x^n$, we see $$p(x)=x^n\cdot \left( a\_n+\frac{a\_{n-1}}{x}+\frac{a\_{n-2}}{x^2}+\cdots+\frac{a\_0}{x^n} \right)$$ taking $x\rightarrow \infty$ we find $$ \left( a\_n+\frac{a\_{n-1}}{x}+\frac{a\_{n-2}}{x^2}+\cdots+\frac{a\_0}{x^n} \right)\rightarrow a\_n$$ so that $p(x)\sim a\_nx^n$. As $x^n\rightarrow \infty$ when $x\rightarrow \infty$ we see that for nonzero $n$ the polynomial will go to infinity.
Remark: The symbol $g(x)\sim f(x)$ is short hand for $\lim\_{x\rightarrow \infty}\frac{f(x)}{g(x)}=1$, and reads "f(x) is asymptotic to g(x)." | Even linear polynomials get larger (in absolute value) than any fixed number at the variable goes to $\pm \infty$ Please see the discussion cited by lhf in the comment. |
376,751 | I'm new to AppleScript and I've reached this problem after several other problems and work arounds (see further down for more details). My current problem is that I'm telling Pages to check if any document is open with
```
tell application "Pages"
exists front document
end tell
```
but *sometimes* even when Pages has a document open the "exists" is always "false". And in general, it seems that sometimes, any reference to "front document" returns errors that it can't get it when it is clearly there. When I quit Pages and try again, usually it works...until it doesn't.
Any ideas?
My original problem stems from wanting to make a QuickAction to open a file in Pages -> export to PDF -> close Pages -> repeat as necessary. But the script gets ahead of itself and tries to complete the export before the file is even open.
```
tell application "Finder"
set theSelection to selection
repeat with oneItem in theSelection
set finderLocation to oneItem as text
open oneItem
tell application "Pages"
set idx to 0
repeat until (exists front document)
set idx to idx + 1
if idx > 2000 then quit
end repeat
set pagesLocation to file of front document as text
repeat until finderLocation = pagesLocation
set pagesLocation to file of front document as text
end repeat
set exportFile to file of front document as text
set exportFile to text 1 thru -6 of exportFile
set exportFile to exportFile & "pdf"
export front document to file exportFile as PDF with properties {image quality:Best}
close front document without saving
end tell
end repeat
end tell
```
So I've been trying to find a way to check if the document is open first before continuing. And I came up with this, to check if the front document file location in Pages matches the file locations opened by Finder. This worked until I tried from a fresh instance of Pages (quit Pages first then try). The problem there was that Pages would flag an error for not being able to find "front document" at all (since it needed to read its file path but nothing was open yet).
So now I'm here trying to check if ANYTHING is open before checking if the target file is open. But now, as described above, it seems that references to "document" just breaks and causes either "exists" or "file of front document" to hang.
Am I even headed in the right direction here or is there a better way to do this?
Thanks in advance.
EDIT:
now my script looks like this, and seems to be more consistent, at least so far
```
tell application "Finder"
set theSelection to selection
repeat with oneItem in theSelection
set nameOfDocument to name of oneItem
open oneItem
tell application "Pages"
repeat until (exists document nameOfDocument)
delay 0.1
end repeat
set exportFile to oneItem as text
set exportFile to text 1 thru -6 of exportFile
set exportFile to exportFile & "pdf"
export document nameOfDocument to file exportFile as PDF with properties {image quality:Best}
close document nameOfDocument without saving
end tell
end repeat
end tell
``` | 2019/12/04 | [
"https://apple.stackexchange.com/questions/376751",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/355200/"
] | What worked for me on Catalina 10.15.7 was to simply create a `Desktop Pictures` folder in the *root* `Library` folder at the same path, rather than trying to modify `System/Library`. In other words, instead of `/System/Library/Desktop\ Pictures` which is restricted, place your custom pictures at `/Library/Desktop\ Pictures`, and you should find they show up correctly in the control panel. | **Update!**
I found a solution that works on Catalina and should work on Big Sur too (although this hasn't been tested).
Your custom dynamic wallpapers can be stored anywhere and should be added to the Desktop & Screen Saver prefpane using the plus button in the bottom left.
Once you have your custom wallpapers imported, navigated to Accessibility settings and enable VoiceOver. Using VoiceOver, you can navigate (using tab) down to the dropdown menu for selection of screen fill preference *or* the dropdown menu for selection of dynamic preference (Dark, Light, or Dynamic).
You can toggle through these options using arrow keys and select Dynamic to enable your custom .heic file to dynamically change throughout the day (if the data is there).
[](https://i.stack.imgur.com/fwGmX.gif)
This method requires no disabling of SIP or any modification of permissions.
Enjoy! |
3,861,980 | I am using AJAX to generate actions on my website. For example, a "search results page" calls Ajax which initiates "/getResults.php". This PHP file returns a JSON with 20 entries that contains the results. The HTML Page calls the callback function and re-builds the DOM with the results from the JSON.
It thus seems inevitable that using Ajax in this form will result public API (just send "/getResults.php" a request with a query and you will get easy to use JSON).
Is there anyway to block these Ajax calls? This is more acute when setting database entries, and not only retrieving.
Thanks,
Joel | 2010/10/05 | [
"https://Stackoverflow.com/questions/3861980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434273/"
] | You could use nonces or short-lived CSRF token. Write it into the page and the session and pass it back with your requests. This adds a *little* bit of impedance, but anyone that's really determined to get your data won't have much of a problem doing so, since they could just screen-scrape a token to use in their own requests.
Why are you wanting to protect those interfaces, and how important is it that people not be able to get access to them outside of your app? If it's really critical that you protect that data, you'll need to go with a solution that isn't client-driven, which unfortunately means no AJAX, as you're likely well aware. | One rudimentary level of 'protection' is to check the `HTTP_REFERER` header on your server to make sure the request is coming from your own website. This can be spoofed, though, so I wouldn't trust it too much. |
31,513 | The following excerpt is from [Schwager's Hedge Fund Market Wizzards](http://books.google.de/books?id=eAR5mPSK9voC&lpg=PT104&ots=z34iduu-nG&dq=%22you%20can%20look%20for%20patterns%20where,%20on%22&hl=de&pg=PT104#v=onepage&q&f=false) (May 2012), an interview with the consistently successful hedge fund manager Jaffray Woodriff:
To the question: "What are some of the worst errors people make in data mining?":
>
> A lot of people think they are okay because they use in-sample data
> for training and out-of-sample data for testing. Then they sort the
> models based on how they performed on the in-sample data and choose
> the best ones to test on the out-of-sample data. The human tendency is
> to take the models that continue to do well in the out-of-sample data
> and choose those models for trading. That type of process simply
> turns the out-of-sample data into part of the training data because it
> cherry-picks the models that did best in the out-of-sample period. It
> is one of the most common errors people make and one of the reasons
> why data mining as it is typically applied yields terrible results.
>
>
>
The interviewer than asks: "What should you be doing instead?":
>
> You can look for patterns where, on average, all the models
> out-of-sample continue to do well. You know you are doing well if the
> average for the out-of-sample models is a significant percentage of
> the in-sample score. Generally speaking, you are really getting
> somewhere if the out-of-sample results are more than 50 percent of
> the in-sample. QIM's business model would never have worked if SAS and
> IBM were building great predictive modeling software.
>
>
>
**My questions**
Does this make any sense? What does he mean? Do you have a clue - or perhaps even a name for the proposed method and some references? Or did this guy find the holy grail nobody else understands? He even says in this interview that his method could potentially revolutionize science... | 2012/07/02 | [
"https://stats.stackexchange.com/questions/31513",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/230/"
] | Not sure if there'll be any other "ranty" responses, but heres mine.
*Cross Validation* is in no way "new". Additionally, *Cross Validation* is not used when analytic solutions are found. For example you don't use cross validation to estimate the betas, you use *OLS* or *IRLS* or some other "optimal" solution.
What I see as a glaringly obvious gap in the quote is no reference to any notion of actually checking the "best" models to see if they make sense. Generally, a good model makes sense on some intuitive level. It seems like the claim is that *CV* is a silver bullet to all prediction problems. There is also no talk off setting up at the higher level of model structure - do we use *SVM*, *Regression Trees*, *Boosting*, *Bagging*, *OLS*, *GLMS*, *GLMNS*. Do we regularise variables? If so how? Do we group variables together? Do we want robustness to sparsity? Do we have outliers? Should we model the data as a whole or in pieces? There are too many approaches to be decided on the basis of *CV*.
And another important aspect is what computer systems are available? How is the data stored and processed? Is there missingness - how do we account for this?
And here is the big one: do we have sufficiently good data to make good predictions? Are there known variables that we don't have in our data set? Is our data representative of whatever it is we're trying to predict?
*Cross Validation* is a useful tool, but hardly revolutionary. I think the main reason people like is that it seems like a "math free" way of doing statistics. But there are many areas of *CV* which are not theoretically resolved - such as the size of the folds, the numbers of splits (how many times do we divide the data up into $K$ groups?), should the division be random or systematic (eg remove a state or province per fold or just some random 5%)? When does it matter? How do we measure performance? How do we account for the fact that the error rates across different folds are correlated as they are based on the same $K-2$ folds of data.
Additionally, I personally haven't seen a comparison of the trade off between computer intensive *CV* and less expensive methods such as *REML* or *Variational Bayes*. What do we get in exchange for spending the addiional computing time? Also seems like *CV* is more valuable in the "small $n$" and "big $p$" cases than the "big $n$ small $p$" one as in "big $n$ small $p$" case the out of sample error is very nearly equal to the in sample error. | >
> You can look for *patterns* where, on average, all the models
> out-of-sample continue to do well.
>
>
>
My understanding of the word *patterns* here, is he means different market conditions. A naive approach will analyse all available data (we all know more data is better), to train the best curve fitting model, then run it on all data, and trade with it all the time.
The more successful hedge fund managers and algorithmic traders use their market knowledge. As a concrete example the first half hour of a trading session can be more volatile. So they'll try the models on all their data but for just that first half hour, and on all their data, but excluding that first half hour. They may discover that two of their models do well on the first half hour, but eight of them lose money. Whereas, when they exclude that first half hour, seven of their models make money, three lose money.
But, rather than taking those two winning models and use them in the first half hour of trading, they say: that is a bad time of day for algorithmic trading, and we're not going to trade at all. The rest of the day they will use their seven models. I.e. it appears that the market is easier to predict with machine learning at those times, so those models have more chance of being reliable going forward.
(Time of day isn't the only pattern; others are usually related to news events, e.g. the market is more volatile just before key economic figures are announced.)
That is my interpretation of what he is saying; it may be totally wrong, but I hope it is still useful food for thought for somebody. |
15,123,238 | Hello i am trying to display the result of search in my homepage. I am running an internet radio website and i am trying to get this to work.
The users will use the search engine to find a song "John" for example: <http://tir.fullerton.edu/search/searchv2.php>
it will show all possible results.
Then once they find it they click on the hyperlink ("this Song").
Then it display the results.
i want to be able to display these results on our header homepage.
<http://tir.fullerton.edu/> | 2013/02/27 | [
"https://Stackoverflow.com/questions/15123238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2117287/"
] | [MD5](http://en.wikipedia.org/wiki/MD5) is a hash function which is irreversible and two input may produce the same output.
in case the content of the files is not 'secret' you can use MD5 for a verification process, this should be quite easy.
* Create a hashtabe (or just a table) with the hashes of all the resources your application uses
* Once the applet lanched create an [hash for each of the files](https://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java) and compare it with your table, if its not the same, someone has changed the content of your jar file.
*I'd recommend to keep the hash table within the code so it will be harder to modify* | If you are using your resources, you have to decrypt them then the client can use them, because they are being used in the game. |
210,559 | I'm trying to adjust Message Queuing properties (specifically, message storage limits) via Computer Management on my machine. It fails with the following message:
The properties of cannot be set.
Error: Access is denied.
I am logged in with an account that is part of the local Administrators group. I can perform all other administrative tasks I have tried. What could be preventing me from changing these settings?
Platform: Windows Vista Business SP2 (x64) | 2010/12/08 | [
"https://serverfault.com/questions/210559",
"https://serverfault.com",
"https://serverfault.com/users/33834/"
] | This blog may also be useful: <http://blog.aggregatedintelligence.com/2012/03/msmqsecurity-descriptor-cannot-be-set.html>
Basically, it says that in order to be able to change the settings of a queue, your account must be set as an owner of the queue and it explains how to do so.
It worked for me. | I had the same problem and found this useful:
>
> 1. Go to the server which host the MSMQ
> 2. Click Start > Run then Regedit
> 3. Navigate to HKLM\Software\Microsoft\MSMQ\Parameters\
> 4. you will see a Binary Type ‘REG\_DWORD’ named as Workgroup.
> 5. The Data for that should be 0×00000000 (0)
> 6. Doubleclick on that DWORD and change the value to 1. Leave everything else as default
> 7. Close Regedit
> 8. Go to services then restart MSMQ service.
> 9. Right click properties on Message Queuing. You should be able to see more tabs and the error is gone.
>
>
> |
69,540,428 | I have files name filename.gz.1 and i need to rename them to filename.gz,
There are allot of files and every name is different,
I know i cant to this `for i in $(ls); do mv $i $i.1; done`,
But can i do this reverse, from filename.gz.1 to filename.gz and keep the original file name?
I have tried this,
```
for i in $(ls | grep "xz\|gz"); do echo "mv $i $i | $(rev) | $(cut -c3-) | $(rev) |)"; done
```
But this ignores my Pipes.
Can anyone help me? | 2021/10/12 | [
"https://Stackoverflow.com/questions/69540428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14380853/"
] | You can use
```sh
for i in ...;
do
echo "$i --> ${i%.*}"
done
```
The `${i%.*}` will remove at the end (`%`) what match a period followed by anything (`.*`) | I was able to resolve it like this:
```
for i in $(ls | grep "xz\|gz"); do echo "mv $i $i" | rev | cut -c3- | rev; done | bash
``` |
12,066,555 | ```
TABLE T1 TABLE T2
+----+------------+ +----+------------+
| Id | Name | | Id | Some_Data |
+----+------------+ +----+------------+
| | | | | |
```
Query1:
```
SELECT * FROM T1 JOIN T2 ON T1.Id=T2.Id WHERE T1.Id=1001
```
Query2:
```
SELECT * FROM T1 JOIN T2 ON T1.Id=T2.Id WHERE T2.Id=1001
```
If T2 has 10 million rows of which only 100 has Id=1001, which of the above query is the more appropriate one to use? Or it doesn't matter as SQL Server is smart enough to know what to do best?
Thanks. | 2012/08/22 | [
"https://Stackoverflow.com/questions/12066555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | I think the problem here is that the join - with many millions of rows - always come first and only after that will come the where clause.
Try this instead on your tables and see the timestamps in the messages tab:
```
declare @t1 table (id int, name nvarchar(100));
declare @t2 table (id int, name nvarchar(100));
insert into @t1 (id, name) values (1, 'a')
insert into @t1 (id, name) values (2, 'b')
insert into @t1 (id, name) values (3, 'c')
insert into @t1 (id, name) values (4, 'd')
insert into @t1 (id, name) values (5, 'e')
insert into @t2 (id, name) values (5, 'e')
insert into @t2 (id, name) values (5, 'f')
insert into @t2 (id, name) values (5, 'g')
insert into @t2 (id, name) values (5, 'h')
insert into @t2 (id, name) values (5, 'i')
insert into @t2 (id, name) values (6, 'j')
insert into @t2 (id, name) values (7, 'k')
insert into @t2 (id, name) values (8, 'l')
print getdate()
-- this is your select statement
select * from @t1 t1 inner join @t2 t2 on t1.id = t2.id where t1.id = 5;
print getdate()
-- this is your select statement
select * from @t1 t1 inner join @t2 t2 on t1.id = t2.id where t2.id = 5;
print getdate()
-- this is done with a WITH to do the filtering beforehand
-- of course, indices will affect the performance a lot
with w2 (id, name) as (select * from @t2 where id = 5)
select * from w2 inner join @t1 t1 on w2.id = t1.id
print getdate()
```
Of course, ignore my sample data and use your tables like in the WITH clause. | First, this is a real question I am facing, and the database is from a third-party software product where I have read only access to generate some reports.
From all the very helpful answerers, I gather that there is no straightforward answer. I conclude from the postings that: first ensure the keyed columns are indexed, and then let SQL Server take care of the optimization.
Thanks to all. |
2,195,905 | I have hyperlinks, all are named 'mylink'. They should all fire the same event, but only the first element named 'mylink' actually fires. My code is as follows:
```
$(document).ready(function() {
$("#formID").validationEngine()
$('#mylink').click(function(e){
var goto = $(this).attr('href'); //get the url
$.ajax({
url: goto
}); //execute the href
e.preventDefault(); //prevent click
$('#mylink').parent().parent().fadeOut("slow");
});
})
```
Where am I going wrong? | 2010/02/03 | [
"https://Stackoverflow.com/questions/2195905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225239/"
] | ```
$(function(){
$("#formID").validationEngine(); // don't forget your semi-colons
$(".mylink").click(function(e){ // ID's should be unique, use classes instead
e.preventDefault();
$.ajax({ url: $(this).attr("href") });
$(this).parent().parent().fadeOut("slow"); // refer to this as 'this'
});
});
``` | You can't re-use an "id" value. A given "id" can only be used once on a page.
If you need multiple elements to be affected, use a "class" component:
```
<div id="uniqueString" class="makeMeMoo makeMePurple makeMeClickable">
<!-- whatever -->
</div>
``` |
16,664,231 | This is cross-domain ajax request:
```
$.ajax({
type: "POST",
dataType: "jsonp",
contentType: "application/jsonp",
data: '{"UserName":"newuser","Password":"pwd"}',
crossDomain: true,
async: false,
url: "http://xxx.xx.xx.xx/MyService/SampleService.svc/GetData",
jsonpCallback: function (jsonData) {
console.log(jsonData);
alert('Hi');
},
complete: function (request, textStatus) {
alert(request.responseText);
alert(textStatus);
},
error: function (request, textStatus, errorThrown) {
alert(textStatus);
}
});
```
This is my WCF REST service's method:
```
namespace SampleServiceRestAPI
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SampleService : ISampleService
{
...
public string GetData(UserData userData)
{
string response = "Hi_" + userData.UserName;
return response;
}
...
}
```
Interface:
```
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetData")]
[OperationContract]
string GetData(UserData userData);
```
Datacontract:
```
[DataContract]
public class UserData
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
}
```
And thepart of `web.config`:
```
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.serviceModel>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" >
<serviceActivations>
<add factory="System.ServiceModel.Activation.ServiceHostFactory" relativeAddress="SampleService.svc" service="SampleServiceRestAPI.SampleService"/>
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="SampleServiceRestAPI.SampleService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
bindingConfiguration="webWinBinding" contract="SampleServiceRestAPI.ISampleService" />
</service>
<!--<service behaviorConfiguration="metadataBehavior" name="MyService">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>-->
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webWinBinding" maxBufferSize="2147483647" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647">
<readerQuotas maxArrayLength="100000" maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
<!--<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
<protocols>
<add name="HttpPost"/>
<add name="HttpPostLocalhost"/>
</protocols>
</webServices>
</scripting>
</system.web.extensions>-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<appSettings>
<add key="ErrorCodeFile" value="~/App_Data/ErrorCode.txt"/>
</appSettings>
```
The error I got in the Firebug:
>
> "NetworkError: 500 Internal Server Error - <http://173.161.176.229/MyService/SampleService.svc/GetData?callback=undefined&>{%22UserName%22:%22newuser%22,%22Password%22:%22pwd%22}&\_=1369120080493"
>
>
> | 2013/05/21 | [
"https://Stackoverflow.com/questions/16664231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1751860/"
] | Inputs:
* 0-4 inputs
* 5-9 inputs
* More than 9 inputs
Values:
* 0-100
* 101-999
* Greater than 999
The program accepts when there are between 5 and 9 inputs and each input value is a 3-digit number between 101 and 999. | equivalence classes for your problem are:
1. set of numbers that are not three digit and greater than hundred...
2. set of numbers that are less than one hundred
3. set of numbers that are greater than one hundred and less than 999
4. set consisting of the number 100 |
13,521,531 | Just wondering what the best way to visually represent this algorithm program might be? We want to visually represent the shortest path and the packet moving through the routers if possible? Any ideas? Looking at turtle it seems we could achieve what we want. Any pointers welcome. Thanks.
Trying to visually represent this: displays shortest path between group of weighted (number value) nodes.
```
from heapq import heappush, heappop # for priority queue
pq = []
class node:
label = ''
# adjacency list of the node
neighbors = [] # list of nodes
distances = [] # distances to neighbors
# for Dijkstra
prevNode = None
totalDistance = float('Inf')
visited = False
# constructor
def __init__(self, label):
self.label = label
self.neighbors = []
self.distances = []
self.prevNode = None
self.totalDistance = float('Inf')
self.visited = False
# find the shortest paths to all nodes recursively
def dijkstra(node):
# visit all neighbors and update them if necessary
for i in range(len(node.neighbors)):
n = node.neighbors[i]
d = node.distances[i]
if n.totalDistance > d + node.totalDistance:
n.prevNode = node
n.totalDistance = d + node.totalDistance
heappush(pq, (n.totalDistance, n))
node.visited = True
(d, ne) = heappop(pq)
if not ne.visited:
dijkstra(ne)
# get the shortest path to the given node
def route(endNode):
node = endNode
labels = [endNode.label]
# distances = []
while node.label != node.prevNode.label:
# distances.append(node.totalDistance - node.prevNode.totalDistance)
node = node.prevNode
labels.append(node.label)
labels.reverse()
return labels
# distances.reverse()
# return (labels, distances)
# create a graph
a = node('a')
b = node('b')
c = node('c')
d = node('d')
e = node('e')
f = node('f')
g = node('g')
graph = (a, b, c, d, e, f, g)
# create bidirectional edges of the graph
edges = []
edges.append((b, c, 3))
edges.append((d, e, 1))
edges.append((b, d, 2))
edges.append((c, e, 1))
edges.append((a, b, 1))
edges.append((a, d, 1))
edges.append((c, f, 1))
edges.append((e, f, 3))
edges.append((e, g, 1))
# create adjaceny list of neighbors for each node
for edge in edges:
edge[0].neighbors.append(edge[1])
edge[0].distances.append(edge[2])
edge[1].neighbors.append(edge[0])
edge[1].distances.append(edge[2])
# print the graph
print 'The graph:'
print
for n in graph:
print 'Node: ', n.label
print 'Neighbors:'
for i in range(len(n.neighbors)):
print n.neighbors[i].label, n.distances[i]
print
# find the shortest paths to all neighbors starting w/ the given node
startNode = a
print 'Route start node:', startNode.label
startNode.prevNode = startNode
startNode.totalDistance = 0
dijkstra(startNode)
##print
##print 'The graph after Dijkstra:'
##print
##for n in graph:
## print 'Node:', n.label
## print 'totalDistance:', n.totalDistance
## print 'prevNode:', n.prevNode.label
## print
# print the shortest path to the given node
endNode = f
print 'Route end node:', endNode.label
print 'Route:', route(endNode)
print 'Total distance:', endNode.totalDistance
``` | 2012/11/22 | [
"https://Stackoverflow.com/questions/13521531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1378618/"
] | Try [Multimedia Timers](http://msdn.microsoft.com/en-us/library/windows/desktop/dd742877%28v=vs.85%29.aspx) - they provide greatest accuracy possible for the hardware platform. These timers schedule events at a higher resolution than other timer services.
You will need following Win API functions to set timer resolution, start and stop timer:
```
[DllImport("winmm.dll")]
private static extern int timeGetDevCaps(ref TimerCaps caps, int sizeOfTimerCaps);
[DllImport("winmm.dll")]
private static extern int timeSetEvent(int delay, int resolution, TimeProc proc, int user, int mode);
[DllImport("winmm.dll")]
private static extern int timeKillEvent(int id);
```
You also need callback delegate:
```
delegate void TimeProc(int id, int msg, int user, int param1, int param2);
```
And timer capabilities structure
```
[StructLayout(LayoutKind.Sequential)]
public struct TimerCaps
{
public int periodMin;
public int periodMax;
}
```
Usage:
```
TimerCaps caps = new TimerCaps();
// provides min and max period
timeGetDevCaps(ref caps, Marshal.SizeOf(caps));
int period = 1;
int resolution = 1;
int mode = 0; // 0 for periodic, 1 for single event
timeSetEvent(period, resolution, new TimeProc(TimerCallback), 0, mode);
```
And callback:
```
void TimerCallback(int id, int msg, int user, int param1, int param2)
{
// occurs every 1 ms
}
``` | Based on the other solutions and comments, I put together this VB.NET code. Can be pasted into a project with a form. I understood @HansPassant's comments as saying that as long as `timeBeginPeriod` is called, the "regular timers get accurate as well". This doesn't seem to be the case in my code.
My code creates a multimedia timer, a `System.Threading.Timer`, a `System.Timers.Timer`, and a `Windows.Forms.Timer` after using `timeBeginPeriod` to set the timer resolution to the minimum. The multimedia timer runs at 1 kHz as required, but the others still are stuck at 64 Hz. So either I'm doing something wrong, or there's no way to change the resolution of the built-in .NET timers.
**EDIT**; changed the code to use the StopWatch class for timing.
```
Imports System.Runtime.InteropServices
Public Class Form1
'From http://www.pinvoke.net/default.aspx/winmm/MMRESULT.html
Private Enum MMRESULT
MMSYSERR_NOERROR = 0
MMSYSERR_ERROR = 1
MMSYSERR_BADDEVICEID = 2
MMSYSERR_NOTENABLED = 3
MMSYSERR_ALLOCATED = 4
MMSYSERR_INVALHANDLE = 5
MMSYSERR_NODRIVER = 6
MMSYSERR_NOMEM = 7
MMSYSERR_NOTSUPPORTED = 8
MMSYSERR_BADERRNUM = 9
MMSYSERR_INVALFLAG = 10
MMSYSERR_INVALPARAM = 11
MMSYSERR_HANDLEBUSY = 12
MMSYSERR_INVALIDALIAS = 13
MMSYSERR_BADDB = 14
MMSYSERR_KEYNOTFOUND = 15
MMSYSERR_READERROR = 16
MMSYSERR_WRITEERROR = 17
MMSYSERR_DELETEERROR = 18
MMSYSERR_VALNOTFOUND = 19
MMSYSERR_NODRIVERCB = 20
WAVERR_BADFORMAT = 32
WAVERR_STILLPLAYING = 33
WAVERR_UNPREPARED = 34
End Enum
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757625(v=vs.85).aspx
<StructLayout(LayoutKind.Sequential)>
Public Structure TIMECAPS
Public periodMin As UInteger
Public periodMax As UInteger
End Structure
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757627(v=vs.85).aspx
<DllImport("winmm.dll")>
Private Shared Function timeGetDevCaps(ByRef ptc As TIMECAPS, ByVal cbtc As UInteger) As MMRESULT
End Function
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx
<DllImport("winmm.dll")>
Private Shared Function timeBeginPeriod(ByVal uPeriod As UInteger) As MMRESULT
End Function
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757626(v=vs.85).aspx
<DllImport("winmm.dll")>
Private Shared Function timeEndPeriod(ByVal uPeriod As UInteger) As MMRESULT
End Function
'http://msdn.microsoft.com/en-us/library/windows/desktop/ff728861(v=vs.85).aspx
Private Delegate Sub TIMECALLBACK(ByVal uTimerID As UInteger, _
ByVal uMsg As UInteger, _
ByVal dwUser As IntPtr, _
ByVal dw1 As IntPtr, _
ByVal dw2 As IntPtr)
'Straight from C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include\MMSystem.h
'fuEvent below is a combination of these flags.
Private Const TIME_ONESHOT As UInteger = 0
Private Const TIME_PERIODIC As UInteger = 1
Private Const TIME_CALLBACK_FUNCTION As UInteger = 0
Private Const TIME_CALLBACK_EVENT_SET As UInteger = &H10
Private Const TIME_CALLBACK_EVENT_PULSE As UInteger = &H20
Private Const TIME_KILL_SYNCHRONOUS As UInteger = &H100
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757634(v=vs.85).aspx
'Documentation is self-contradicting. The return value is Uinteger, I'm guessing.
'"Returns an identifier for the timer event if successful or an error otherwise.
'This function returns NULL if it fails and the timer event was not created."
<DllImport("winmm.dll")>
Private Shared Function timeSetEvent(ByVal uDelay As UInteger, _
ByVal uResolution As UInteger, _
ByVal TimeProc As TIMECALLBACK, _
ByVal dwUser As IntPtr, _
ByVal fuEvent As UInteger) As UInteger
End Function
'http://msdn.microsoft.com/en-us/library/windows/desktop/dd757630(v=vs.85).aspx
<DllImport("winmm.dll")>
Private Shared Function timeKillEvent(ByVal uTimerID As UInteger) As MMRESULT
End Function
Private lblRate As New Windows.Forms.Label
Private WithEvents tmrUI As New Windows.Forms.Timer
Private WithEvents tmrWorkThreading As New System.Threading.Timer(AddressOf TimerTick)
Private WithEvents tmrWorkTimers As New System.Timers.Timer
Private WithEvents tmrWorkForm As New Windows.Forms.Timer
Public Sub New()
lblRate.AutoSize = True
Me.Controls.Add(lblRate)
InitializeComponent()
End Sub
Private Capability As New TIMECAPS
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
timeKillEvent(dwUser)
timeEndPeriod(Capability.periodMin)
End Sub
Private dwUser As UInteger = 0
Private Clock As New System.Diagnostics.Stopwatch
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
Dim Result As MMRESULT
'Get the min and max period
Result = timeGetDevCaps(Capability, Marshal.SizeOf(Capability))
If Result <> MMRESULT.MMSYSERR_NOERROR Then
MsgBox("timeGetDevCaps returned " + Result.ToString)
Exit Sub
End If
'Set to the minimum period.
Result = timeBeginPeriod(Capability.periodMin)
If Result <> MMRESULT.MMSYSERR_NOERROR Then
MsgBox("timeBeginPeriod returned " + Result.ToString)
Exit Sub
End If
Clock.Start()
Dim uTimerID As UInteger
uTimerID = timeSetEvent(Capability.periodMin, Capability.periodMin, _
New TIMECALLBACK(AddressOf MMCallBack), dwUser, _
TIME_PERIODIC Or TIME_CALLBACK_FUNCTION Or TIME_KILL_SYNCHRONOUS)
If uTimerID = 0 Then
MsgBox("timeSetEvent not successful.")
Exit Sub
End If
tmrWorkThreading.Change(0, 1)
tmrWorkTimers.Interval = 1
tmrWorkTimers.Enabled = True
tmrWorkForm.Interval = 1
tmrWorkForm.Enabled = True
tmrUI.Interval = 100
tmrUI.Enabled = True
End Sub
Private CounterThreading As Integer = 0
Private CounterTimers As Integer = 0
Private CounterForms As Integer = 0
Private CounterMM As Integer = 0
Private ReadOnly TimersLock As New Object
Private Sub tmrWorkTimers_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs) _
Handles tmrWorkTimers.Elapsed
SyncLock TimersLock
CounterTimers += 1
End SyncLock
End Sub
Private ReadOnly ThreadingLock As New Object
Private Sub TimerTick()
SyncLock ThreadingLock
CounterThreading += 1
End SyncLock
End Sub
Private ReadOnly MMLock As New Object
Private Sub MMCallBack(ByVal uTimerID As UInteger, _
ByVal uMsg As UInteger, _
ByVal dwUser As IntPtr, _
ByVal dw1 As IntPtr, _
ByVal dw2 As IntPtr)
SyncLock MMLock
CounterMM += 1
End SyncLock
End Sub
Private ReadOnly FormLock As New Object
Private Sub tmrWorkForm_Tick(sender As Object, e As System.EventArgs) Handles tmrWorkForm.Tick
SyncLock FormLock
CounterForms += 1
End SyncLock
End Sub
Private Sub tmrUI_Tick(sender As Object, e As System.EventArgs) _
Handles tmrUI.Tick
Dim Secs As Integer = Clock.Elapsed.TotalSeconds
If Secs > 0 Then
Dim TheText As String = ""
TheText += "System.Threading.Timer " + (CounterThreading / Secs).ToString("#,##0.0") + "Hz" + vbCrLf
TheText += "System.Timers.Timer " + (CounterTimers / Secs).ToString("#,##0.0") + "Hz" + vbCrLf
TheText += "Windows.Forms.Timer " + (CounterForms / Secs).ToString("#,##0.0") + "Hz" + vbCrLf
TheText += "Multimedia Timer " + (CounterMM / Secs).ToString("#,##0.0") + "Hz"
lblRate.Text = TheText
End If
End Sub
End Class
``` |
4,746 | [Bytebeat](http://canonical.org/~kragen/bytebeat/) is a style of music one can compose by writing a simple C program that's output is piped to `aplay` or `/dev/dsp`.
```
main(t){for(;;t++)putchar(((t<<1)^((t<<1)+(t>>7)&t>>12))|t>>(4-(1^7&(t>>19)))|t>>7);}
```
There is a good deal of information on the [bytebeat site](http://canonical.org/~kragen/bytebeat/), a [javascript implementation](http://wurstcaptures.untergrund.net/music/), and more demos and example compositions in [this thread](http://www.metafilter.com/111959/Todays-formulaic-music).
Very simple rules : Try to write a pretty sounding composition. Most up votes wins since that's obviously subjective, although not that subjective considering the usual results. | 2012/01/24 | [
"https://codegolf.stackexchange.com/questions/4746",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3071/"
] | (Signed 16-bit little endian, 8000Hz mono (`--format=S16_LE`))
Music
-----
**Much** better than before! (although it's quite long)
`main(t){for(;;t++)putchar(((7&(((t>>17)+1)>>2)+((t>>10)&1+2*(t>>18&1))*(("23468643"[7&t>>12]-48)+(3&t>>11))+((3&t>>17)>0)*(3&t>>9)*!(1&t>>10)*(((2+t>>10&3)^(2+t>>11&3))))*t*"@06+"[3&t>>15]/32));}`
(You can listen this [at here](http://snd.sc/zFYrxo))
I wrote this, but even I don't know how some part works, like `>0` and (especially) the first `7&`.
Change for loop to `for(;!(t>>22);t++)`... to listen it 'once'. I don't know whether it "loops" exactly the same way, however.
Melody (base of above music)
----------------------------
I love this melody I made (C-G-A-F ftw), but it's too 'plain'...
`main(t){for(;;t++)putchar(((t>>10)&1)*(t*("23468643"[7&t>>12]-48)+t*(3&t>>11))*"@06+"[3&t>>15]/32);}`
Simple music (which I made before)
----------------------------------
`main(t){for(;;t++)putchar(t*(3&t>>11)+(t&t>>11)*4*!((t>>11)%3));}` | Emphasising "beat" over "byte":
```
#include<math.h>
double s(double,double);double r(double,double);double d(double);double f(double);
char bytebeat(int t){return (d(f(t/4000.)/3) + 1) * 63;}
double f(double t){
double sn=s(1./2,t-1); sn*=(sn*sn);
return 3*s(1./4,1/s(1,t))+3*s(4,1/sn)/2+s(4,1/(sn*sn*sn*sn*sn))/4
+2*s(55+18.3*r(1./2,t),t)+s(110+s(5,t)/4000,t)*s(1,t)+s(220+110*r(1,t)+55*r(3,t),t)/5
+s(880+440*r(1./2,t)-220*r(1,t)+110*r(2,t)+s(5,t)/4000,t)
*(2+s(1760+438*r(3./2,t)-1234*r(2,t)+423*r(5,t),t))/9
+s(s(1,t)+s(1./2,t)+s(1./4,t)+s(1./8,t),t)*s(s(1,t)+s(1./2,t)+s(1./4,t)+s(1./8,t)+1,t)
+r(264+11*r(1./20,t),t)*s(1./20,t);
}
double s(double f,double t){return d(sin(f*3.14159265*(t+999)));}
double r(double f,double t){return s(f,t)<0;}
double d(double a){return tanh(a+a*a/4);}
main(t){for(;;++t)putchar(bytebeat(t));}
```
To be used at 8 kHz, uint8 mono. Sounds best over decently bass-capable loudspeakers. |
3,325,676 | I got the following sets:
A= { { 1 , 3 , 5 , 7 , 9 } , { 1 , 2 , 3 } , 1 , 2 , 3 , 4 , 5 }
B= { 1 , 3 , 5 , 7 , 9 }
I'm a bit confused. What would A ∩ B be? | 2019/08/17 | [
"https://math.stackexchange.com/questions/3325676",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/695902/"
] | $A$ is an unusual set in that some of its elements are numbers and others are sets of numbers. This kind of sets are rarely used in mathematics -- except sometimes in exercises that confuse beginning students ...
$\{1,3,5,7,9\}$ is one of the elements of $A$. This set is *not an element* of $B$ -- it happens to be $B$ itself, but that doesn't make it an *element* of $B$ -- and therefore it is not an element of $A\cap B$.
$\{1,2,3\}$ is another element of $A$ that is not an element of $B$; it is not an element of $A\cap B$ either.
On the other hand $7$ is not an element of $A$. It's an element of an element of $A$, but that's a different thing. | To answer your question, $A\cap B=\{1,3,5\} $.
And, for extra credit, appreciate the distinction between these two true statements:
$$\{1,2,3,4,5\}\subset A $$
$$\{1,3,5,7,9\}\in A $$ |
103,247 | I'm a much like beginner level, so pardon me if this is a very basic silly question. Once I've a JPEG photograph image file, how can I find out whether it is a RAW file or not? | 2018/12/03 | [
"https://photo.stackexchange.com/questions/103247",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/79381/"
] | >
> Once I've a JPEG photograph image file, how can I find out whether it is a RAW file or not?
>
>
>
**If you have a JPEG file, then it is not a RAW file.**
RAW isn't a single format, but rather a collective name for image files that contain data straight from the sensor. RAW files need to be processed in order to convert them to more general-purpose image formats like JPEG or PNG. Most cameras can do that processing themselves, so that they save their images in JPEG format, or they can write the RAW data into a file for processing on your computer. Either way, if you know your file is a JPEG file, then by definition it is not a RAW file. | RAW format, as generally called, is a group of file types with different suffixes. There are `*.raw` files and proprietary files like `*.cr2` for Canon, for example and many others. I am a Canoneer so the following is based on my experience with my Canon.
Almost every manufacturer has their own RAW file format. Be also careful that some, Canon for sure, updates their RAW format so claim "All [Canon] image tools can open all [Canon] RAW images" is false. To preview a RAW file one need program that can process the the particular file format in particular version. Even mighty Photoshop have issues opening every RAW file.
RAW file is a dump of the data collected from the sensor plus data containing the camera setups. It is complete and lossless acquisition of data from the camera to the memory. RAW format is not an image format at all.
The cameras have built-in image processors (in case of Canon it is named Digic*X*) that interpret the RAW file to JPEG and show on screen and/or store to memory.
When one use any digital camera the internal workflow is:
1. Open the shutter (mechanical: slide first curtain away, digital: start saving the data stream from the chip)
2. Acquire the scene
3. Close the shutter (mechanical: slide second curtain over the chip, digital: stop saving the data stream)
4. Dump the data acquired to the buffer
5. Process the image to jpeg using pre-set options
6. Show preview to the screen.
7. Save the *image*
8. Clear buffer memory.
If the `RAW` mode is selected, the processor saves the data to *image* as-is in the body-specific format. If the `RAW+JPEG` mode is selected, processor saves the data as-is to *image.cr2* (for Canons) and processed image to *image.jpeg*. If `JPEG` mode is selected only the processed *image* is saved and the raw data are lost forever.
That's why the RAW *images* are humongous when compared to true image formats. If you have 12MPx camera with 16bit depth the RAW file holds 12 000 000 \* 16 bits of image information plus negligible amount of data keeping the setups.
JPEG is, on the other hand, file format dedicated to store images in files with reasonably size. It is based on lossy compression and benefits from the fact, that 50 shades of black are black to human eye, so why bother? It works similarly to `.mp3` audio format - it ignores the nuances the detector can distinguish but human senses can't. The level of ignorance is regulated by the compression quality.
How to identify RAW files?
* They are humongous
* Few previewers can process them
* The file extension is *not* `jpg` or `jpeg` |
1,386,243 | ```
Dim objMail As New Mail.MailMessage("no-reply@mywebsite.com", ToEmail, "Password Reset", body)
```
...and the problem is that the message is sent as pure text including the `<br>` tags within the body
How could i send the email as html? | 2009/09/06 | [
"https://Stackoverflow.com/questions/1386243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59314/"
] | Have a look at [MailMessage.IsBodyHtml](http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.isbodyhtml.aspx) | Easy:
```
objMail.IsBodyHtml = True
``` |
1,263,072 | I would like to change a 4x4 matrix from a right handed system where:
x is left and right, y is front and back and z is up and down
to a left-handed system where:
x is left and right, **z** is front and back and **y** is up and down.
For a vector it's easy, just swap the y and z values, but how do you do it for a matrix?
[](https://i.stack.imgur.com/iDgv6.png) | 2009/08/11 | [
"https://Stackoverflow.com/questions/1263072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/153844/"
] | After 12 years, the question is still misleading because of the lack of description of axis direction.
What question asked for should probably be how to convert  to .
[](https://i.stack.imgur.com/iDgv6.png)
The answer by @cmann is correct for the above question and @Gerrit explains the reason. And I will explain how to graphically get that conversion on the transform matrix.
We should be clear that **orthogonal matrix** contains both **rotation matrix** and **point reflection**(only point reflection will change the coordinate system between left-handed and right-handed). Thus they can be expressed as a 4x4 matrix and obey to transform matrix multiplying order. "The matrix of a composite transformation is obtained by multiplying the matrices of individual transformations."
 to  contains both **rotation matrix** and **point reflection**. But we can get the composite transformation graphically.
According to above image, after transformation,  in RhC(Right-handedCorrdinate) will be  in LfC as below

where  is a transform bring points expressed in above RhC to points expressed in LhC.
Now We are able to convert () to () accroding to transform matrix multiplying order as below image.
[](https://i.stack.imgur.com/BI7Js.png)
The result is the same as @cmann's.
**Result**:
 | Since this seems like a homework answer; i'll give you a start at a hint: What can you do to make the determinant of the matrix negative?
Further (better hint): Since you already know how to do that transformation with individual vectors, don't you think you'd be able to do it with the basis vectors that span the transformation the matrix represents? (Remember that a matrix can be viewed as a linear transormation performed on a tuple of unit vectors) |
22,450 | We draw $n$ values, each equiprobably among $m$ distinct values. What are the odds $p(n,m,k)$ that at least one of the values is drawn at least $k$ times? e.g. for $n=3000$, $m=300$, $k=20$.
Note: I was passed a variant of this by a friend asking for "a statistical package usable for similar problems".
My attempt: The number of times a particular value is reached follows a binomial law with $n$ events, probability $1/m$. This is enough to get odds $q$ that a particular value is reached at least $k$ times [Excel gives $q\approx 0.00340$ with `=1-BINOMDIST(20-1,3000,1/300,TRUE)`]. Given that $n\gg k$, we can ignore the fact that odds of a value being reached depends on the outcome for other values, and get an *approximation* of $p$ as $1-(1-q)^m$ [Excel gives $p\approx 0.640$ with `=1-BINOMDIST(20-1,3000,1/300,TRUE)^300`].
*update: the exponent was wrong in the above, that's now fixed*
Is this correct? *(now solved, yes, but the approximation made leads to an error in the order of 1% with the example parameters)*
**What methods can work for arbitrary parameters $(n,m,k)$?** Is this function available in R or other package, or how could we construct it? *(now solved, both exactly for moderate parameters, and theoretically for huge parameters)*
I see how to do a simulation in C, what would be an example of a similar simulation in R? *(now solved, a corrected simulation in R and another in Python gives $p\approx 0.647$)* | 2012/02/08 | [
"https://stats.stackexchange.com/questions/22450",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/8469/"
] | This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Let $X\_j \sim Binomial(n,\frac{1}{m})$ $\forall j = 1,..,m$.
$$P(\max\_j X\_j \geq k) = 1 - P(\max\_j X\_j < k)$$
$$ = 1 - P(X\_1 < k,...,X\_m < k)$$
and, assuming independence of the $m$ random variables,
$$ = 1 - \prod^m\_{j=1}P(X\_j < k)$$
$$ = 1 - [P(X\_1 < k)]^m$$
$$ = 1 - [\sum^{k-1}\_{i=0} {n \choose i}(\frac{1}{m})^i(1-\frac{1}{m})^{n-i}]^m$$
or, if you have the binomial cdf function in the language you are using:
$$ = 1 - [Binomial\\_cdf(k-1;n,\frac{1}{m})]^m$$ | The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size. Letting $N\_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N\_1,\dots,N\_m)\sim multinomial\left(n;\frac{1}{m},\frac{1}{m},\dots,\frac{1}{m}\right)$$ Now leveraging off of @danieljohnson's answer the probability we are after is
$$p(n,m,k)=1-Pr(N\_1<k,\dots,N\_m<k)$$
i.e. if all numbers are repeated less than $k$ times, then none are repeated at least $k$ times. And "not none" is the same as "at least one" so we can take the probability away from one. This could be computed via a "brute force" approach, as the pmf we have is particularly simple:
$$p(n,m,k)=1-m^{-n}\sum\_{N\_1<k,\dots,N\_m<k|N\_1+\dots+N\_m=n}{n\choose N\_1\dots N\_m}$$
$$=1-\frac{n!}{m^{n}}\sum\_{N\_1=0}^{k-1}\sum\_{N\_2=0}^{k-1}\dots\sum\_{N\_{m-1}=0}^{k-1}\frac{1}{N\_1!N\_2!\dots N\_{m-1}!(n-N\_1-N\_2-\dots-N\_{m-1})!}$$
The last formula is correct provided we interpret a negative factorial as $\pm\infty$ (consistent with the gamma function) which eliminates these from the summation.
On doing a quick google search came up with [Bruce Levin's article](https://projecteuclid.org/journals/annals-of-statistics/volume-9/issue-5/A-Representation-for-Multinomial-Cumulative-Distribution-Functions/10.1214/aos/1176345593.full). This gives a representation of the multinomial distribution as a collection of poisson random variables, with their sum being fixed. (note this might explain why @whuber has found that poisson approximation works better than binomial). Now, using the representation given in theorem 1 of the paper, we have:
$$p(n,m,k)=1-\frac{n!}{s^n\exp(-s)}\left[\prod\_{j=1}^{m}Pr(X\_j\leq k-1)\right]Pr(W=n)$$
Where $X\_j\sim Poisson\left(\frac{s}{m}\right)$ and are independent, and $W=\sum\_{j=1}^{m}Y\_j$ is a sum of independent truncated poisson distributions - basically $Y\_j$ is $X\_j$ conditioned to be less than or equal to $k-1$. Note that we can simplify the general formula by noting that the terms in the product do not depend on the index $j$, and so is just a single poisson cdf raised to the power of $m$. Thus we have:
$$p(n,m,k)=1-\frac{n!}{s^n}\left[e\_{k-1}\left(\frac{s}{m}\right)\right]^mPr(W=n)$$
Where $e\_k(x)=\sum\_{j=0}^{k}\frac{x^j}{j!}$ denotes the [exponential sum function](https://mathworld.wolfram.com/ExponentialSumFunction.html). note that because we have factorial an powers of potentially large numbers, numerically it will probably be better to work in terms of the logarithm of the second term, and then exponentiate back at the end of the calculation. Alternatively, we can choose the recommended $s=N$ as our algorithm parameter, and then make use of the stirling approximation to $n!$ - this is recommended in the paper and corresponds to "mean matching" of each poisson distribution with the multinomial cell (i.e. $E(X\_i)=E(N\_i)$). Then we get $\frac{n!}{n^n}\approx\sqrt{2\pi n}$.
The paper provides two approximations for $Pr(W=n)$ on based on normal approximation, and another based on edgeworth expansion. details are in the paper (see equation 4). Note though that his method allows for different probability parameters, so terms like $\frac{1}{t}\sum\_{1}^t\sigma\_l^2$ can be replaced with $\sigma\_1^2$ and so on, which avoid unecessary computation. Note that we also have the mallows bounds provided in the paper - which can be used to check the accuracy of the approximations. |
3,008,065 | (also posted on maven-users)
Wondering if anyone can shed some light on inheritance of the elements in pom.xml as relates to resource processing and the WAR plugin.
The documentation for the pom [1] has resources listed under "Elements in the POM that are merged". Some experimentation on my local poms against maven 2.2.1 don't appear to exhibit that behavior. What I see is it looks like is inherited by child projects (in a multi-module build), but that if any of those projects have their own block it replaces the parent, not merged. Is that correct?
Example:
```
parent-pom.xml
|
|-> child-pom.xml
```
The following works as I'd expect, with files in dev not included in a final WAR.
parent-pom.xml
```
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>${dev-config.path}</exclude>
</excludes>
</resource>
</resources>
```
child-pom.xml
```
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>${dev-config.path}</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/rules</directory>
</resource>
<resource>
<directory>src/test/rules</directory>
</resource>
</resources>
```
The following change to the child (removing any declaration for src/main/resources) appears to result in src/main/resource not being considered during process-resources, not inheriting from the parent as I'd expected.
child-pom.xml
```
<resources>
<resource>
<directory>src/main/rules</directory>
</resource>
<resource>
<directory>src/test/rules</directory>
</resource>
</resources>
```
[1] <http://maven.apache.org/guides/introduction/introduction-to-the-pom.html> s | 2010/06/09 | [
"https://Stackoverflow.com/questions/3008065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258670/"
] | Indeed, that's what the documentations says. But I confirm that Maven inheritance overrides resources instead of adding to them. This is actually captured in [MNG-2751](https://issues.apache.org/jira/browse/MNG-2751), and indirectly in [MNG-2027](https://issues.apache.org/jira/browse/MNG-2027), that you might want to bump.
TBH, I'm very curious to see what the maven folks will say on this (I'm personally happy with the current behavior, I don't really want child poms to be "polluted" by specific needs, like exclusions, in a hierarchy) and changing this behavior might break a lot of projects. | As noted in [adding additional resources to a maven pom](https://stackoverflow.com/questions/1101462/adding-additional-resources-to-a-maven-pom), this can be worked around using the [build-helper](http://www.mojohaus.org/build-helper-maven-plugin/) plugin. |
56,385,498 | I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
```
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
```
JS for reset button:
```
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
```
Reset Button:
```
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56385498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682302/"
] | Use `type="reset"` for your button:
```
<button type="reset">Cancel</button>
``` | Please try to use in js like:
```
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
``` |
59,380,955 | when performing `terraform plan`, if an `azurerm_kubernetes_cluster` (Azure) resource exists in the state, terraform will print some information from `kube_config` which seems sensitive
Example printout: (all `...` values get printed)
```
kube_config = [
{
client_certificate = (...)
client_key = (...)
cluster_ca_certificate = (...)
host = (...)
password = (...)
}
```
I'm not exactly sure WHICH of those values are sensitive, but `password` probably is...right?
On the other hand, terraform does seem to have *some* knowledge of which values are sensitive, as it does print the `client_secret` this way:
```
service_principal {
client_id = "(...)"
client_secret = (sensitive value)
}
```
So, my questions would be:
1. Are those values actually sensitive?
2. If so, is there a way to instruct terraform to mask those values in the plan?
Versions we are using:
```
provider "azurerm" {
version = "~>1.37.0"
}
```
The reason why this is problematic is that we pipe the plan in a Github PR comment.
Thanks | 2019/12/17 | [
"https://Stackoverflow.com/questions/59380955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968087/"
] | You can get the href by using `this`
```
$('.classofButton').click ( function () {
$('#content').load ($(this).attr('href')) ;
} );
``` | You can do it like this.
```js
$('.classofButton').click(function(event) {
event.preventDefault();
var href = $(this).attr('href');
$('#content').load(href) ;
});
```
```css
#content {
width: 200px;
height: 200px;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="classofButton" href="http://google.com">google.com</a>
<a class="classofButton" href="https://yahoo.com">yahoo.com</a>
<div id="content"></div>
``` |
5,832,436 | I got one strange problem which I never got before. Please see this code:
The css:
```
#btn{
margin-left:150px;
padding:10px;
display:block;
}
#btn a{
padding:5px 20px;
background:green;
color:#FFF;
text-decoration:none;
outline:none;
}
#btn a:hover{
background:#933;
}
#btn a:focus, #btn a:active{
background:#CF0;
color:#000;
```
}
Here the HTML
```
<div id="btn">
<a href="#">Click here</a>
</div>
```
The **focus** and **active** css working well in firefox, but not in the chrome and safari. | 2011/04/29 | [
"https://Stackoverflow.com/questions/5832436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/687414/"
] | Use tabindex="0" to make an element focusable if it is not already. See <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex> for more information about tabindex.
Setting tabindex to -1 makes it unfocusable. Setting tabindex to a positive integer is not recommended unless you're trying to explicitly set the tab order, as it can create accessibility issues.
For more information about tabindex and accessibility, see <https://webaim.org/techniques/keyboard/tabindex>. | You should know that the pseudo class :focus doesn't go with A. The A tag has 4 pseudo classes : :link, :hover, :active, :visited |
9,190,663 | I have a Razor view with a couple of dropdown lists. If the value of one of the dropdown's is changed I want to clear the values in the other drop down and put new ones in. What values I put in depends on the values in the model that the view uses and that is why I need to send the model back from the view to the controller. The controller will then also need to be able to modify the dropdown by sending back data to the view. Note, that I am not saying that I want to go back to the controller from a form submit using Ajax. I am going back to the controller using a form submit, but not using Ajax.
Please can someone give me some simple code or some pointers to show how this might be done.
Thanks | 2012/02/08 | [
"https://Stackoverflow.com/questions/9190663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/991788/"
] | `each()` is a function, so you need to close its invocation parentheses. You are missing the trailing one.
```
$(document).ready(function () {
$(":input").each(function() {
if($(this).val() != "")
window.setInterval(saveData, 5000);
}); // <-- You were missing the closing `)` here.
});
``` | You need to close your `.each` function:
```
$(document).ready(function () {
$(":input").each(function() {
if($(this).val() != "")
window.setInterval(saveData, 5000);
});
});
``` |
15,230,268 | In x86 assembly language, is there any way to obtain the upper half of the `EAX` register? I know that the `AX` register already contains the lower half of the `EAX` register, but I don't yet know of any way to obtain the upper half.
I know that `mov bx, ax` would move the lower half of `eax` into `bx`, but I want to know how to move the upper half of `eax` into `bx` as well. | 2013/03/05 | [
"https://Stackoverflow.com/questions/15230268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975097/"
] | I would do it like this:
```
mov ebx,eax
shr ebx, 16
```
ebx now contains the top 16-bits of eax | For 16-bit mode, this is the smallest (not fastest) code: only 4 bytes.
```
push eax ; 2 bytes: prefix + opcode
pop ax ; 1 byte: opcode
pop bx ; 1 byte: opcode
```
It's even more compact than single instruction `shld ebx,eax,16` which occupies 5 bytes of memory. |
11,477,902 | I've been trying to utilize a mail.php file from the jquery contactable plugin (found on google!) to use on my website. Although the script provided is fairly simple I'm running into issues with integrating it with my Host's SMTP requirement. Here is the original script without SMTP authentication:
```
<?php
// Assign contact info
$name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$issue = stripcslashes($_POST['issue']);
$comment = stripcslashes($_POST['message']);
$subject = stripcslashes($_POST['subject']);
// Set headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Format message
$contactMessage =
"<div>
<p><strong>Name:</strong> $name <br />
<strong>E-mail:</strong> $emailAddr <br />
<strong>Issue:</strong> $issue </p>
<p><strong>Message:</strong> $comment </p>
<p><strong>Sending IP:</strong> $_SERVER[REMOTE_ADDR]<br />
<strong>Sent via:</strong> $_SERVER[HTTP_HOST]</p>
</div>";
// Send and check the message status
$response = (mail('mymail@mymail.com', $subject, $contactMessage, $headers) ) ? "success" : "failure" ;
$output = json_encode(array("response" => $response));
header('content-type: application/json; charset=utf-8');
echo($output);
?>
```
I've tried using suggestions from Google and played around with it for hours. Here is the latest version based on my nil-understanding of php thus far. -\_\_- (Based on this: <http://blog.geek4support.com/php-mail-script-with-smtp-authentication-how-to-send-mails-by-php-mail-script-using-smtp-authetication/>)
```
<?php
require_once "Mail.php";
// Assign contact info
$name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$issue = stripcslashes($_POST['issue']);
$comment = stripcslashes($_POST['message']);
$subject = stripcslashes($_POST['subject']);
$host = "mail.mywebsite.com";
$username = "mywebsitemail@mywebsiteaddress.com";
$password = "mymailpassword";
// Set headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Format message
$contactMessage =
"<div>
<p><strong>Name:</strong> $name <br />
<strong>E-mail:</strong> $emailAddr <br />
<strong>Issue:</strong> $issue </p>
<p><strong>Message:</strong> $comment </p>
<p><strong>Sending IP:</strong> $_SERVER[REMOTE_ADDR]<br />
<strong>Sent via:</strong> $_SERVER[HTTP_HOST]</p>
</div>";
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$response = ($smtp->send('mymail@mymail.com', $subject, $contactMessage, $headers)) ? "success": "failure";
$output = json_encode(array("response" => $response));
header('content-type: application/json; charset=utf-8');
echo($output);
?>
```
I've actually run into a bit of a problem. My host doesn't support PHPMailer :-(. Only PearMail with SMTP. They have suggested tweaking the code listed above and incorporating my existing one with it. Exactly, what I've been trying to do before posting this online. Back to square 1, any ideas?
Comments, suggestions, anything would be most appreciated! :-) | 2012/07/13 | [
"https://Stackoverflow.com/questions/11477902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004013/"
] | For sending mails, try [PHPMailer](http://phpmailer.worxware.com/), it's tested, everybody uses it, and it just works.
It also has a lot of features and configuration options.
The latest version is [this one](http://sourceforge.net/projects/phpmailer/files/latest/download?source=files), as for sending mails using SMTP with PHPMailer this is all the code you need
```
// Data received from POST request
$name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$issue = stripcslashes($_POST['issue']);
$comment = stripcslashes($_POST['message']);
$subject = stripcslashes($_POST['subject']);
// Send mail
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
// SMTP Configuration
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "myhost"; // SMTP server
$mail->Username = "yourusername@gmail.com";
$mail->Password = "yourpassword";
//$mail->Port = 465; // optional if you don't want to use the default
$mail->From = "my@email.com";
$mail->FromName = "My Name";
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($issue . "<br /><br />" . $comment);
// Add as many as you want
$mail->AddAddress($emailAddr, $name);
// If you want to attach a file, relative path to it
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
$response= NULL;
if(!$mail->Send()) {
$response = "Mailer Error: " . $mail->ErrorInfo;
} else {
$response = "Message sent!";
}
$output = json_encode(array("response" => $response));
header('content-type: application/json; charset=utf-8');
echo($output);
``` | This my test script for getting around the disabled PHP mail() function. It uses PearMail. The print statements are for testing in a browser, you may want to remove them.
```
<?php
/*
* Script to send an email as the PHP mail() function is disabled.
* The hosting company requires SMTP authentication etc.
* need to install the pear mail package in the cPanel
*
* Use the support@myserver.com as the sending/from email
* (or maybe the welcome one?)
*
* Sunday, 11 october 2015
* G O’Rilla
*
*
*/
function pearMail( $e_mail, $subject, $content ) {
/*
// To ignore the Strict Standards (which are non fatal) change your error
// reporting level in the php.ini file or better, inline with error_reporting()
*/
error_reporting(E_ERROR | E_PARSE);
# To use installed modules (cPanel - PHP Extensions and Applications Package Installer)
# Add “/home/myaccount/php” to the include path. To do this, add the following code to your script:
ini_set("include_path", '/home/myaccount/php:' . ini_get("include_path") );
require_once 'Mail.php';
#Server host only allows SMTP authentication
/*
* Use below setting for SMTP Authentication.
* --
* SMTP Host : myserver.com
* SMTP User : Use domain email Address [xyz@myserver.com]
* SMTP Password : Use domain email password.
* SMTP Port : 25
*/
//print "Start Script <br>";
$params = array();
$params["host"] = “myserver.com"; # - The server to connect. Default is localhost - use your domain name.
$params["port"] = 25; # - The port to connect. Default is 25.
// Error: return fron mailer: Failed to set sender: welcome@theappflap.com
//[SMTP: Invalid response code received from server (code: 550, response:
// Access denied - Invalid HELO name (See RFC2821 4.1.1.1))]
// sever requires authentication so TRUE
$params["auth"] = TRUE; # - Whether or not to use SMTP authentication. Default is FALSE.
$params["username"] = "support@myserver.com"; #- The username to use for SMTP authentication.
$params["password"] = “********”; #- The password to use for SMTP authentication.
print_r ( $params );
//Other parameters assuming default values will do
#$params["localhost"] - The value to give when sending EHLO or HELO. Default is localhost
#$params["timeout"] - The SMTP connection timeout. Default is NULL (no timeout).
#$params["verp"] - Whether to use VERP or not. Default is FALSE.
#$params["debug"] - Whether to enable SMTP debug mode or not. Default is FALSE.
# Mail internally uses Net_SMTP::setDebug .
#$params["persist"] - Indicates whether or not the SMTP connection should persist over multiple calls to the send() method.
#$params["pipelining"] - Indicates whether or not the SMTP commands pipelining should be used.
$rc = $mailer = & Mail::factory( "smtp", $params ); # creates a mailer instance
if ( $rc == NULL ) {
print "<br>Failed to create mail instance <br>";
}
else {
print "<br>mail instance created <br>";
}
$recipients = $email; //'support@myserver.com';
$headers['From'] = 'welcome@myserver.com';
$headers['To'] = $email; //'support@myserver.com'; // Input param
$headers['Subject'] = $subject; //'TAF: Test message'; // Input param
$body = $content; //'This is a test using PEAR mailer'; // Input param
print ( "recipients: " . $e_mail . " subject: " . $subject . " content: " . $content . "<br>");
$rc = $mailer->send( $recipients, $headers, $body );
print ( "return from mailer; " . $rc );
//print "<br>End Script";
}
?>
``` |
236 | ### Congratualtions BokkyPooBah for [reaching 2k reputation](https://ethereum.stackexchange.com/users?tab=Reputation&filter=all) in two weeks!
Every healthy beta site needs a [dozen very active users](http://area51.stackexchange.com/proposals/89704/ethereum). BokkyPooBah managed to show us how it's possible to write a lot of high-quality answers in quite a short amount of time.
We still need 2-3 members with 10k+ reputation, around 10 more members with 3k+ reputation and around 50 users with 200+ repuation. (Moderators excluded.)
### Why is that?
After a site graduates out of Beta state, privileges will be harder to earn.
* 10k reputation allows access to moderator tools (access reports, delete questions, review reviews).
* 3k reputation allows to cast close and reopen votes which is among the most important moderation tools for the community to help deciding which questions are on- or off-topic for the site and help spotting duplicates.
* 200 reputation is generally measured to show the user has understood the mechanics of a stack exchange site.
### How to gain reputation fast?
[Extracted from Stack Exchange Meta](https://meta.stackexchange.com/a/17250/226837):
1. **Post quality answers.** This should be numbered 1 2 and 3. But a good answer will more often than not trump a fast answer. Though there are cases where it does not.
2. **Monitor the [frontpage](https://ethereum.stackexchange.com/) and the [new questions list.](https://ethereum.stackexchange.com/questions?sort=newest)** Learn their cache time and refresh accordingly or use the tag pages ([Example](https://ethereum.stackexchange.com/questions/tagged/solidity+or+smart-contracts?sort=newest)) to get live updates on new questions.
3. **Setup a good but short list of Interesting and Ignored tags.** For example set [web3js](https://ethereum.stackexchange.com/questions/tagged/web3js "show questions tagged 'web3js'"), [solidity](https://ethereum.stackexchange.com/questions/tagged/solidity "show questions tagged 'solidity'") and [evm](https://ethereum.stackexchange.com/questions/tagged/evm "show questions tagged 'evm'") as interesting tags. This will help you see questions, which you can answer, quicker.
4. **Avoid Wall of Text questions.** They take way too much effort for little reward. And usually are syntax errors or bad structure.
5. **Post an answer even though the question has 1–2 or even 3 answers.** In these cases, take your time and answer well. This will usually net you a good sum of rep.
6. **Learn when to edit.** Post a short answer at first and then edit. You have <5 minutes to make that answer shine.
7. **Be humble, thorough and fair.** There are a lot of smart people out there and many will know much more than you about the subject. Be thorough in the code you post, check it for syntax errors and make sure it fits the question. And if you see that the correct answer is already there, upvote it, that person deserves the rep.
Did I miss anything? Who's next? ;-) | 2016/04/13 | [
"https://ethereum.meta.stackexchange.com/questions/236",
"https://ethereum.meta.stackexchange.com",
"https://ethereum.meta.stackexchange.com/users/87/"
] | Here we go, @BokkyPooBah already at 3k! Congratulations, now we have 5 users at 3000 reputation! | Congratualations @eth for being the first to reach 10,000 reputation! Hurray! |
36,706,369 | After some effort (I'm a newbie) I've managed to create a method that reads a text file and puts it into a multi dimensional array. However the array size is hard coded and it doesn't deal with blank lines very well so I have the following questions:
1) How do I define my array to be equal to the size of the text file?
2) Is there an easy way to handle a blank line? Ideally I'd like to just delete any blanks from the text file so that the array contains no null values but I am open to suggestions on the best way to handle it.
Here is what I have so far:
```
public void TextFileReader (){
String[][] textFileData = new String[5][2];
InputStreamReader InputSR = null;
BufferedReader BufferedRdr = null;
String thisLine = null;
InputSR = new InputStreamReader(getResources().openRawResource(R.raw.text_file));
BufferedRdr = new BufferedReader(InputSR);
try {
// open input stream text_file for reading purpose.
int i = 0;
while ((thisLine = BufferedRdr.readLine()) != null) {
String[] parts = thisLine.split(" ");
textFileData[i][0] = parts[0];
textFileData[i][1] = parts[1];
Log.v("String Array"+i+"0", String.valueOf(textFileData[i][0]));
Log.v("String Array"+i+"1", String.valueOf(textFileData[i][1]));
i = i +1;
}
} catch (Exception e) {
e.printStackTrace();
}
}
``` | 2016/04/19 | [
"https://Stackoverflow.com/questions/36706369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6061723/"
] | As I said in my comment, using [ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) in this situation makes things much simpler since you don't have to worry about knowing the size before hand. You can implement it like so:
```
ArrayList<String[]> arrayList = new ArrayList<>();
try {
// open input stream text_file for reading purpose.
while ((thisLine = BufferedRdr.readLine()) != null) {
if (!thisLine.isEmpty()) {
String[] parts = thisLine.split(" ");
arrayList.add(parts);
}
}
} catch (Exception e) {
e.printStackTrace();
}
```
---
Notice that I added the following condition:
```
if (!thisLine.isEmpty()) {
```
this makes it so that empty lines are skipped and not added to the `ArrayList`.
---
You can view the contents of your `ArrayList` by iterating through it just like you would an array:
```
for (String[] row : arrayList) {
System.out.println(Arrays.toString(row));
}
```
Or like so:
```
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(Arrays.toString(arrayList.get(i)));
}
```
---
I made a dummy file with the following data:
```
line one
line two
line three
```
Notice the empty lines between each line. Printing the contents of the `ArrayList` resulted in:
```
[line, one]
[line, two]
[line, three]
```
---
*If* you really want to use a double array, you could iterate through the file first and count how many non-empty lines you have just like you're doing so already (with the addition of `if (!thisLine.isEmpty()) {`) and then dimension your array like that.
---
**EDIT**
Using `ArrayList`, if you wanted to get line 2, column 2, you could do it like so (keep in mind arrays start at index 0):
```
String[] row = arrayList.get(1);
```
Will grab the row that you want
```
String value = row[1];
```
Will grab the column of the row that you want.
Printing `value` out with `System.out.println(value);` yields in:
>
> two
>
>
>
Or you could just do it in one line:
```
String value = arrayList.get(1)[1];
```
*Or* better yet, you can create a method, so that you can call it any time:
```
public static String getValue(ArrayList<String[]> arrayList, int row, int column) {
return arrayList.get(row)[column];
}
```
Which you can call like so:
```
String value = getValue(arrayList, 1, 1);
``` | Is there a particular reason why you need to use an array? Arrays are usually bad practice for this exact reason: they have a static size that needs to be changed manually to avoid over-flow. In practice almost no one uses arrays unless there is a specific need to do so.
A better approach is to look at other containers that change their size dynamically, such as an Arraylist. You should be able to create an Arraylist of Arraylists that has the same effect, but doesn't offer the limitation of an array.
When coding typically try not to re-invent the wheel, just use native libraries and their features to do what you want them to do.
As for the blank line, I'd presume that when a blank line happens the String is being populated as empty, so in that case you'd just need to check if the String is empty, and then populate your container in whichever way you see fit in that case, or as the poster below suggests don't populate the container at all. |
3,328,721 | I have been trying to prove the inequality
>
> $$\int\_{0}^{\infty} |f(x)|^2 dx \leq C \int\_{0}^{\infty} x^2 |f^{\prime}(x)|^2 dx$$
>
>
>
for some constant $C$, under the most general set of assumptions possible. Obviously we need to have that $f$ is square-integrable and differentiable.
I can prove a version of the inequality with $C=4$, provided that additionally $x |f(x)|^2 \to 0$ as $x\to \infty$ (the proof is by integration by parts and the Cauchy-Schwartz inequality). Can this be improved? Thank you. | 2019/08/20 | [
"https://math.stackexchange.com/questions/3328721",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93509/"
] | **Constant is $\boldsymbol{\le4}$**
Whatever conditions are needed to justify the following steps:
$$
\begin{align}
\int\_0^\infty|f(x)|^2\,\mathrm{d}x
&=\int\_0^\infty\left|\int\_x^\infty f'(t)\,\mathrm{d}t\right|^2\,\mathrm{d}x\tag1\\
&\le\int\_0^\infty\int\_x^\infty t^{-3/2}\,\mathrm{d}t\int\_x^\infty t^{3/2}|f'(t)|^2\,\mathrm{d}t\,\mathrm{d}x\tag2\\
&=\int\_0^\infty2x^{-1/2}\int\_x^\infty t^{3/2}|f'(t)|^2\,\mathrm{d}t\,\mathrm{d}x\tag3\\
&=\int\_0^\infty t^{3/2}|f'(t)|^2\int\_0^t2x^{-1/2}\,\mathrm{d}x\,\mathrm{d}t\tag4\\
&=\int\_0^\infty t^{3/2}|f'(t)|^24t^{1/2}\,\mathrm{d}t\tag5\\
&=4\int\_0^\infty t^2|f'(t)|^2\,\mathrm{d}t\tag6
\end{align}
$$
Explanation:
$(1)$: Funamental Theorem of Calculus (assuming $f$ vanishes at $\infty$)
$(2)$: Cauchy Schwarz
$(3)$: integrate
$(4)$: change order of integration
$(5)$: integrate
$(6)$: simplify
It seems that if $(6)$ exists and $f$ vanishes at $\infty$, the inequality holds.
---
**$\boldsymbol{4}$ is Sharp**
Define
$$
f\_a(t)=\frac{t^{-1/2}}{t^{-a}+t^a}\tag7
$$
then
$$
\begin{align}
\int\_0^\infty f\_a(t)^2\,\mathrm{d}t
&=\int\_0^\infty\frac{t^{-1}}{\left(t^{-a}+t^a\right)^2}\mathrm{d}t\tag8\\
&=\int\_0^\infty\frac{t^{2a-1}}{\left(1+t^{2a}\right)^2}\mathrm{d}t\tag9\\
&=\frac1{2a}\int\_0^\infty\frac1{(1+t)^2}\mathrm{d}t\tag{10}\\[6pt]
&=\frac1{2a}\tag{11}
\end{align}
$$
Explanation:
$\phantom{1}(8)$: apply $(7)$
$\phantom{1}(9)$: multiply numerator and denominator by $t^{2a}$
$(10)$: substitute $t^{2a}\mapsto t$
$(11)$: evaluate
Taking the derivative of $(7)$
$$
f\_a'(t)=\frac{t^{-\frac32+a}\left(4a+(1-2a)\left(1+t^{2a}\right)\right)}{2\left(1+t^{2a}\right)^2}\tag{12}
$$
Thus,
$$
\begin{align}
\int\_0^\infty t^2f\_a'(t)^2\,\mathrm{d}t
&=\int\_0^\infty t^2\,\left(\frac{t^{-\frac32+a}\left(4a+(1-2a)\left(1+t^{2a}\right)\right)}{2\left(1+t^{2a}\right)^2}\right)^2\mathrm{d}t\tag{13}\\
&=\int\_0^\infty\frac{t^{-1+2a}\left(4a+(1-2a)\left(1+t^{2a}\right)\right)^2}{4\left(1+t^{2a}\right)^4}\,\mathrm{d}t\tag{14}\\
&=\int\_0^\infty\frac{16a^2+8a(1-2a)(1+t)+(1-2a)^2(1+t)^2}{8a(1+t)^4}\,\mathrm{d}t\tag{15}\\[3pt]
&=\frac23a+\frac12(1-2a)+\frac1{8a}(1-2a)^2\tag{16}\\[6pt]
&=\frac16a+\frac1{8a}\tag{17}
\end{align}
$$
Explanation:
$(13)$: apply $(12)$
$(14)$: simplify
$(15)$: substitute $t^{2a}\mapsto t$
$(16)$: integrate
$(17)$: simplify
The ratio of $(11)$ over $(17)$ is $\frac4{1+\frac43a^2}$. As $a\to0$, this gets arbitrarily close to $4$. | You say you can prove it *if* $x|f(x)|^2\to0$. It seems very likely that your proof can be modified to work without that extra assumption.
Because there must exist $x\_n\to\infty$ such that $x\_n|f(x\_n)|^2\to0$; if not then $|f(x)|^2\ge c/x$ for all $x\ge A$, which implies that $\int|f(x)|^2=\infty$.
I haven't seen your proof, but "surely" it works just using integration by parts on the interval $(0,x\_n)$ instead of an arbitrary interval. |
17,260,584 | Let's say I have
```
e1 :: Event t A
f :: A -> IO B
```
I want to create
```
e2 :: Event t B
```
which is triggered by `e1`, and whose values are determined by executing `f` on the value of `e1` at the time of the event occurrence.
I see two potential ways to do this, via dynamic event switching and using handlers, but they both look too complicated for such a simple thing.
What is the proper way to do this? | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110081/"
] | Since the function `f` has a side effect, this is actually not a simple thing to do. The main reason is that the order of side effects is not well-defined when there are multiple simultaneous events. More generally, I was unable to conceive a good semantics for dealing with IO actions in events. Consequently, reactive-banana does not provide a pure combinator for this situation.
If you want to do this anyway, you have to use a more elaborate mechanism that also determines the order of side effects. For instance, you can use `reactimate` and write a combinator
```
mapIO :: Frameworks t => (a -> IO b) -> Event t a -> Moment t (Event t b)
mapIO f e1 = do
(e2, fire2) <- liftIO newAddHandler
reactimate $ (\x -> f x >>= fire2) <$> e1
fromAddHandler e2
```
However, note that this may give unexpected results as the result event `e2` is no longer simultaneous with the input event `e1`. For instance, behaviors may have changed and other side effects may have been executed. | Can you call function `f` in `reactimate` (which as far as I understand is the "proper way" to handle IO from the event network)? From there, fire a new event of type `Event t B` to the event network. Or is this what you meant by "using handlers"? |
58,930,825 | In my application I am getting message sent date from API response, I want to calculate the difference between current date and the date from API response in days(difference) using angular 8 and map in ngFor.
<https://stackblitz.com/edit/angular-xv1twv?file=src%2Fapp%2Fapp.component.html>
Please help me. Should I use moment. | 2019/11/19 | [
"https://Stackoverflow.com/questions/58930825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898861/"
] | You don't need to use momentjs.
```js
calculateDiff(data){
let date = new Date(data.sent);
let currentDate = new Date();
let days = Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60 / 60 / 24);
return days;
}
```
```html
<div *ngFor="let data of responseData" class="dataHolder">
<div>{{data.title}}</div>
<div>{{data.type}}</div>
<div>{{data.msg}}</div>
Message sent on: <div>{{data.sent}}</div>
<div style="font-weight:bold;">sent {{calculateDiff(data)}}_ days ago</div>
</div>
``` | In your html, pass the dateString to the c**alculateDiff** function
```
<div style="font-weight:bold;">sent {{calculateDiff(data.sent)}} days ago</div>
```
In your ts, change your code like this,
```
calculateDiff(date: string){
let d2: Date = new Date();
let d1 = Date.parse(date); //time in milliseconds
var timeDiff = d2.getTime() - d1;
var diff = timeDiff / (1000 * 3600 * 24);
return Math.floor(diff);
}
``` |
39,137,811 | I want to store graph data in marklogic using semantic triple. I am able to do that when i use ttl file with uri of <http://example.org/item/item22>.
But i want to store this triple wrt to documents which are stored in Marklogic.
Means i have one document "Java KT" which is in relation to Java class, and all this data is present in marklogic , how can i create a ttl file with uri to document which is present in marklogic DB? | 2016/08/25 | [
"https://Stackoverflow.com/questions/39137811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6755516/"
] | Load your documents, load your triples, and just add extra triples with document uri as subject or object, and some triple entity uri as the other side. You could express those in another ttl file, or create them via code.
Next question would be, though, how you would want to use documents and triples together?
HTH! | my question is what is the IRI that i will be writing in ttl file which will be of my document available in DB. As ttl file accepts IRIs , so what is the iri for my document ?
@grtjn |
30,889,952 | What happens if you change the variable `b`, or what if you change `a`. What does the order have to do with anything.
I know `count = count + 1` but the two variables is messing up my brain.
```
b = 7;
a = 7;
a = b;
a += 1;
```
What happens to `b`? | 2015/06/17 | [
"https://Stackoverflow.com/questions/30889952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053544/"
] | >
> What happens to `b`?
>
>
>
Nothing happens to `b`.
When you do
```
a = b;
```
you're copying **the value** stored in `b` and putting it in `a`. (You're *not* making `a` an alias of `b`.)
When you then do `a += 1;` you're changing the value stored in `a` (and the value stored in `b` remains unchanged).
You can verify this by printing the final values after your code snippet:
```
System.out.println(a); // prints 8
System.out.println(b); // prints 7
```
>
> What happens if you change the variable `b`, or what if you change `a`. What does the order have to do with anything.
>
>
>
`a` and `b` are two independent variables and changing one will never affect the other.
The order matters since when you do `a = b` the value of `b` is copied into `a` and whatever `a` stored before is discarded. If you had done `a += 1` prior to `a = b`, then `a` would have been restored to 7 again. | **int** is raw type you don't copy reference but the value itself. This will work same way for **Integer** because it is **immutable** class.
```
int b = 7;
int a = 7;
a = b;
a+=1;
System.out.println(a);// ->8
System.out.println(b);// ->7
``` |
19,535,624 | I have 2 chart with different yAxis title. I need the titles to be horizontal and align to the right (on the left side of the Y line).
The title align worked only on the vertical centered. (and I need my titles to be in the middle)
I tried adding text-align to the style with no success.
```
yAxis: {
"title": {
"style": {
"textAlign": "right"
}
}
}
```
<http://jsfiddle.net/g7kUc/>
Would love to hear ideas on how to work around this problem. | 2013/10/23 | [
"https://Stackoverflow.com/questions/19535624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853546/"
] | You're gonna like this, there is not documented option "textAlign" but not under style, but title property. For example: <http://jsfiddle.net/g7kUc/1/>
```
yAxis: {
"title": {
"text": "test",
"textAlign": "right"
}
}
``` | One way is to just specify different offsets for the two axis labels:
```
offset:25
offset:40
```
<http://jsfiddle.net/CTPe9/>
I know it's a bit manual, but it has the right effect. If the labels change in length, you should be able to calculate the correct offset from the length of the string and the font used.
Another way is to not use the title at all. You have more contol over the labels:
```
"labels": {
"style": {
"fontWeight":"bold",
"color": "#6D869F",
"textAlign": "right"
},
"enabled": true,
"align":"right",
y:-60,
formatter: function() {
if (this.isFirst) {
return "12345";
} else {
return "";
}
}
},
```
This fiddle shows it in action <http://jsfiddle.net/zNHhh/>.
It works by only showing one label (in the formatter function). This label is then aligned right, and moved using the 'y' parameter. |
54,989,822 | I want to make a unit test for a Mqtt client module in Android Studio, because i want to send data from an Android Device to PC, but i don't know how to test that without a real server, i'm using paho library. There is a way to do that? | 2019/03/04 | [
"https://Stackoverflow.com/questions/54989822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can not use the paho library to mock a broker, but there is moquette broker (<https://github.com/moquette-io/moquette>) which you might be able to use to embed a broker in an existing Java app | Yes, it is easy to perform local offline tests while developing with Android Studio and Android Emulator at your Mac, Linux or Windows computer -
First install [mosquitto](https://mosquitto.org/download/) and run the broker at the localhost (on Windows just double click the `mosquitto.exe`, on Linux/Mac run `./mosquitto` in Terminal window).
Then open another Terminal window and subscribe to all topics by running:
```
./mosquito_sub -v -t "#"
```
Or on Windows in cmd window:
```
mosquito_sub.exe -v -t "#"
```
Finally in your Java source code change the URL when running in the emulator:
```
public static boolean isEmulator() {
return (Build.PRODUCT != null && Build.PRODUCT.toLowerCase().contains("sdk")) ||
(Build.MODEL != null && Build.MODEL.toLowerCase().contains("sdk"));
}
private static final String BROKER_URL =
isEmulator() ? "tcp://10.0.2.2/" : "tcp://test.mosquitto.org/";
``` |
6,584,660 | I am developing a site for which I would like to protect buyers by anonymizing their email addresses.Similar to craigslist's system, when a seller needs to contact a buyer they should be able to send an email to an anonymized address such as 1425415125@mysite.com which will then be routed to the user's email address.
My plan right now is to:
1. Set up a bucket (catch-all) inbox
2. Generate a random key for each buyer which will be the user specific ('1425415125' above) section of the email address
3. Monitor the bucket inbox and parse out this user specific section. Once I know the user, the email can be forwarded to the correct address
My questions are as follows:
1. Can you see any issues with the above solution
2. Are there any open source solutions to the existing problem
3. Are there any gotchas that one should be aware of when developing such a system?
Thanks in advance
JP | 2011/07/05 | [
"https://Stackoverflow.com/questions/6584660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138347/"
] | You may wish to look at mail "piping" - the ability for someone to send an email to a mail server, which then gets thrown immediately to an executable, which then forwards your mail onto the recipient (by pulling the real email address from the database based on the incoming address from the piped message).
My personal recommendation would be to check out [HMailServer](http://www.hmailserver.com/), which has a COM API (the admin side is written in PHP, hence the requirement for legacy interop), is free and open-source, and is very well-documented. It doesn't have mail piping built-in, but is easily extensible given the API and support for scripts which run on [server-side message events](http://www.hmailserver.com/documentation/v5.3/?page=reference_scripts)
HTH,
Benjamin | I do not see any problem with your setup, infact that is correct way to do because if your scheduled application fails, the emails will still be in the catch-all email box. Only once the email has been successfully delivered to somebody, the email should be deleted. You will be able to monitor and log the activity of your own application to monitor progress and failures.
I do not recommend Piping because, if for any reason piping goes successfully but your exe crashes, you will loose the email. Tracking will be difficult. Scheduling the jobs will not be possible.
If your application is independent of mail server, it is easy to manage it and replace your mail server whenever possible. It is easy to extend.
In this you will have to use some pop reader library, and schedule your application to run frequently. |
29,096,687 | I'm still new to Node.JS and I'm trying to call a REST API using GET method.
I use 'request' package from this [link](https://www.npmjs.com/package/request). The call actually works but when I try to return the response body from other .JS file, I get 'undefined'.
Here is my 'first.js'
```
var request = require('request');
var first = function (){
};
first.prototype.getValue = function (value){
var thpath = somePath + value;
var postheaders = {
'Content-Type': 'x-www-form-urlencoded'
};
var options = {
url : 'https://' + thpath,
method : 'GET',
headers : postheaders,
};
var data_rec = "";
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
data_rec = JSON.parse(body);
console.info(data_rec);
return data_rec;
} else return "failed to get";
});
};
module.exports = first;
```
Here is my 'second.js'
```
var first = require('./first');
var instance = new first();
var val1 = instance.getValue(someValue);
console.info(val1);
```
The 'console.info(data\_rec)' from 'first.js' returns a JSON (which means that the call is working). However, 'console.info(val1)' from 'second.js' returns 'undefined'. Can anybody find the solution?
Update:
I am able to get the solution by using [sync-request](https://www.npmjs.com/package/sync-request) package. | 2015/03/17 | [
"https://Stackoverflow.com/questions/29096687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3567018/"
] | It is rather straightforward using regexps:
```
import os, re
samples = {}
for f in os.listdir("."):
m = re.match(r"MySample (\d+) (\d+).wav", f)
if m:
samples[tuple(int(x) for x in m.groups())] = f
``` | You can use a regexp to match
```
import re
def getKey(x):
m=re.match ('MySample (\d+) (\d+).wav',x)
if m:
return (m.group(1),m.group(2))
else:
return None
sample=["MySample 117 12.wav", "MySample 011 18.wav", "MySample 13 45.wav"]
```
Then a list comprehension to create the dictionary
```
r=dict(((getKey(x),x) for x in sample))
``` |
8,774,311 | I keep getting this error when i try to read the content of a `txt` file:
*index.php:*
```
<?php
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fwrite(STDOUT, "Welcome $handle");
?>
```
in the command line i do: `cat texte.txt | php index.php`
where `texte.txt` contains a name. the two files txt and php are in the same folder. I used to work fine, i don't know why this error comes in my case. | 2012/01/08 | [
"https://Stackoverflow.com/questions/8774311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/602257/"
] | Because you used to output `$line`, not `$handle`. | You're seeing PHP's string representation of "resource" objects/vars. `fwrite` the `$line` and you should get your desired result.
Example:
```
<?php
echo fopen('foo.txt', 'r');
```
Outputs:
```
Resource id #2
``` |
1,532,193 | Is it possible to read cookie expiration date using JavaScript?
If yes, how? If not, is there a source I can look at? | 2009/10/07 | [
"https://Stackoverflow.com/questions/1532193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177883/"
] | If you have control over the code where the cookie is set, then you can add code to store the expiration date in the browser's local storage for later retrival. For example:
```
// set cookie with key and value to expire 30 days from now
var expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
document.cookie = [
"key=value",
"expires=" + expires.toUTCString()
].join("; ");
// store cookie expiration date for key in local storage
if (window.localStorage) {
localStorage.setItem("keyExpires", expires.toISOString());
}
```
Later, you can lookup when the cookie expires in local storage. For example:
```
var expires = localStorage.getItem("keyExpires");
```
Local storage currently has broad support.
<https://caniuse.com/#feat=namevalue-storage> | There is a work-around to OP's question if you also control the setting of the cookies. I do it like this:
```js
function setCookie(name, value, expiryInDays) {
const d = new Date();
d.setTime(d.getTime() + expiryInDays * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}_${d.toUTCString()};expires=${d.toUTCString()}`;
}
function showCookies() {
if (document.cookie.length !== 0) {
const allCookies = document.cookie.split(/;\s*/);
const wrapper = document.getElementById('allCookies');
wrapper.innerHTML = allCookies.reduce((html, cookie, index) => {
const cookieParts = cookie.split('=');
const cookieValueParts = cookieParts[1].split('_');
const cookieHtml = [
`<b>${index + 1}</b>`,
`Cookie name: ${cookieParts[0]}`,
`Cookie value: ${cookieValueParts[0]}`,
`Expires: ${cookieValueParts[1] || 'unknown'}`
].join('<br>');
return html + `<p>${cookieHtml}</p>`;
}, '');
}
}
```
```html
<button onclick="showCookies()">Show me the cookies!</button>
<div id="allCookies"></div>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.