text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Generating multi-level JSON
I have an array of Objects, each containing a Location and a Links array of indeterminate length. How can I create a multilevel JSON object with loops?
The end JSON should look like
item1: [
{ "location": [
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value }
],
"links": [
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value }
]
}
],
item2: [ //repeat of above ]
The issue I'm having is how to correctly form the objects. The objects that the array contains are defined as
function Links(){
this.location = null;
this.links= [];
function getLocation(){
return location;
}
function setLocation(marker){
this.location = marker;
}
function getLinks(){
return links;
}
}
My current solution is
var json=[];
var linkData;
for (var i=0; i < tourList.length; i++){
var data = tourList[i];
//create new child array for insertion
var child=[];
//push location marker data
child.push({
latitude: data.location.position.$a,
longitude: data.location.position.ab,
stopNum: i,
filename: data.location.title
});
//add associated link data
for (var j=0; j<data.links.length; j++){
linkData = data.links[i];
child.push({
latitude: linkData.position.$a,
longitude: linkData.position.ab,
stopNum: i+j,
fileName: linkData.title
});
}
//push to json array
json.push(child);
}
//stringify the JSON and post results
var results= JSON.stringify(json);
However, this is not quite working, as
$post= json_decode($_POST['json'])
PHP statement is returning a malformed array where $post.length is seen as an undefined constant. I'm assuming that this is due to the incorrect formatting.
With objects defined above, how can I create a well-formed JSON to be sent to the server?
The current result of stringify() is
[
{"latitude":43.682211,"longitude":-70.45070499999997,"stopNum":0,"filename":"../panos/photos/1-prefix_blended_fused.jpg"},
[
{"latitude":43.6822,"longitude":-70.45076899999998,"stopNum":0,"fileName":"../panos/photos/2-prefix_blended_fused.jpg"}
],
{"latitude":43.6822,"longitude":-70.45076899999998,"stopNum":1,"filename":"../panos/photos/2-prefix_blended_fused.jpg"},
[
{"latitude":43.68218,"longitude":-70.45088699999997,"stopNum":1,"fileName":"../panos/photos/4-prefix_blended_fused.jpg"},
{"latitude":43.68218,"longitude":-70.45088699999997,"stopNum":2,"fileName":"../panos/photos/4-prefix_blended_fused.jpg"}
]
]
Also, I'm using $post.length in
$post = json_decode($POST['json']);
for ($i=0; $i<$post.length; $i++) { }
to iterate over the processed array.
The POST request is via a jQuery.ajax() function defined as
$.ajax({
type: "POST",
url: "../includes/phpscripts.php?action=postTour",
data: {"json":results},
beforeSend: function(x){
if (x && x.overrideMimeType){
x.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(data){
if (data == "success")
console.log("Tour update successful");
else
console.log("Tour update failed");
}
});
A:
This should work.
var json = [];
var linkData;
for (var i = 0; i < tourList.length; i++) {
var data = tourList[i];
//create new child array for insertion
var child = [{ }];
//push location marker data
child[0]['location'] = [{
latitude: data.location.position.$a,
longitude: data.location.position.ab,
stopNum: i,
filename: data.location.title
}];
child[0]['links'] = [];
//add associated link data
for (var j = 0; j < data.links.length; j++) {
linkData = data.links[i];
child.links.push({
latitude: linkData.position.$a,
longitude: linkData.position.ab,
stopNum: i + j,
fileName: linkData.title
});
}
//push to json array
json.push(child);
}
//stringify the JSON and post results
var results = JSON.stringify(json);
But why are you making the output JSON so complex? A simpler way would be to use something like this:
item1: {
"location": {
"latitude": value, "longitude": value, "stopNum": value, "fileName": value
},
"links": [
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value },
{"latitude": value, "longitude": value, "stopNum": value, "fileName": value }
]
},
item2: [ //repeat of above ]
What you are doing is creating 'arrays' for single objects. Why do that? If you use this format, the code (subtly) simplifies:
var json = [];
var linkData;
for (var i = 0; i < tourList.length; i++) {
var data = tourList[i];
//create new child array for insertion
var child = { };
//push location marker data
child.location = {
latitude: data.location.position.$a,
longitude: data.location.position.ab,
stopNum: i,
filename: data.location.title
};
child.links = [];
//add associated link data
for (var j = 0; j < data.links.length; j++) {
linkData = data.links[i];
child.links.push({
latitude: linkData.position.$a,
longitude: linkData.position.ab,
stopNum: i + j,
fileName: linkData.title
});
}
//push to json array
json.push(child);
}
//stringify the JSON and post results
var results = JSON.stringify(json);
| {
"pile_set_name": "StackExchange"
} |
Q:
Compile error for QT 5.2.1; expected unqualified-id before 'delete'
I'm trying to compile QT 5.2.1 for an older Linux distro (Suse Linux Enterprise 11) and after a while I receive the error below:
In file included from qxcbxsettings.cpp:46:0:
/usr/include/X11/extensions/XIproto.h:1825:17:
error: expected unqualified-id before 'delete'
BOOL delete;
I'm more or less confident this is caused by the fact that "delete" is a reserved word for C++. If this header would be my own, I would simply rename delete to something else, but of course it is not an option in case of an X11 header file.
Any ideas how can I force gcc to compile as plain C for this header? All I found is a configure option -no-c++11 for qt's configure script, but that did not make a difference.
A:
delete is a reserved keyword in C++, There is bug reported related to X11/extensions/XIproto.h file here
They also provided patch for same
So you need to apply patch for compiling further patch is like
+#if defined(__cplusplus) || defined(c_plusplus)
+ BOOL c_delete;
+#else
BOOL delete;
+#endif
| {
"pile_set_name": "StackExchange"
} |
Q:
writing a CoffeeScript Class
I have the following simple CoffeeScript Class:
class Country
constructor: (@val) ->
console.log @val
foreign: ->
@val isnt "United States"
domestic: ->
not foreign()
I have this simple class to determine some logic for a select drop down.
Here is how I am calling it:
$country = new Country($val) if $('select[id*="country"]').val() > 0
console.log $country.foreign? if $country?
$val is being set in an on('change') event. $country.foreign? is always evaluating to true even if I select a country other than the US. Not sure what I am doing wrong here. The @val is being set to the value I am passing in, but the foreign function isn't working properly
A:
It should be
console.log $country.foreign()? if $country?
foreign is a function call.
Also that translates to this:
if (typeof $country !== "undefined" && $country !== null) {
console.log($country.foreign() != null);
}
So you get a log of whether or not the return is null, you probably want to drop the ?
console.log $country.foreign() if $country?
| {
"pile_set_name": "StackExchange"
} |
Q:
JS creating divs with a for loop inside container
I am trying to create a number of divs inside a container, but i cant figure out how to nest the created ones within the main container. Is it also possible or better to create the container before in the html?
JS
function createDiv(numberOfDivs) {
var i = 0;
var newElement = [];
var mainContainer = document.createElement('div');
mainContainer.innerHTML = 'MAIN CONTAINER';
mainContainer.className = 'main';
document.body.appendChild(mainContainer);
for (i; i < numberOfDivs; i++) {
newElement[i] = document.createElement('div');
newElement[i].style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
newElement[i].className = 'box';
newElement[i].id = (i + 1);
newElement[i].textContent = 'this is div number: ' + (i + 1);
document.body.appendChild(newElement[i]);
}
};
createDiv(10);
A:
Yes, you can create the container in the html ahead of time, as others have suggested. Then you can nest your divs inside that container.
<html><body><div id="mainContainer" ></div></body></html>
As others suggested you can apply the necessary css to make it hidden if necessary until you want it visible.
Then javascript to nest divs inside mainContainer:
function createDiv(numberOfDivs){
var $mainContainer = $("#mainContainer");
for (i; i < numberOfDivs; i++) {
var newDiv = $("<div class='box' />");
//...you can add whatever attributes to the div that you want...
$mainContainer.append(newDiv);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
COLLECT_SET() in Hive, keep duplicates?
Is there a way to keep the duplicates in a collected set in Hive, or simulate the sort of aggregate collection that Hive provides using some other method? I want to aggregate all of the items in a column that have the same key into an array, with duplicates.
I.E.:
hash_id | num_of_cats
=====================
ad3jkfk 4
ad3jkfk 4
ad3jkfk 2
fkjh43f 1
fkjh43f 8
fkjh43f 8
rjkhd93 7
rjkhd93 4
rjkhd93 7
should return:
hash_agg | cats_aggregate
===========================
ad3jkfk Array<int>(4,4,2)
fkjh43f Array<int>(1,8,8)
rjkhd93 Array<int>(7,4,7)
A:
Try to use COLLECT_LIST(col) after Hive 0.13.0
SELECT
hash_id, COLLECT_LIST(num_of_cats) AS aggr_set
FROM
tablename
WHERE
blablabla
GROUP BY
hash_id
;
A:
There is nothing built in, but creating user defined functions, including aggregates, isn't that bad. The only rough part is trying to make them type generic, but here is a collect example.
package com.example;
import java.util.ArrayList;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StandardListObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
public class CollectAll extends AbstractGenericUDAFResolver
{
@Override
public GenericUDAFEvaluator getEvaluator(TypeInfo[] tis)
throws SemanticException
{
if (tis.length != 1)
{
throw new UDFArgumentTypeException(tis.length - 1, "Exactly one argument is expected.");
}
if (tis[0].getCategory() != ObjectInspector.Category.PRIMITIVE)
{
throw new UDFArgumentTypeException(0, "Only primitive type arguments are accepted but " + tis[0].getTypeName() + " was passed as parameter 1.");
}
return new CollectAllEvaluator();
}
public static class CollectAllEvaluator extends GenericUDAFEvaluator
{
private PrimitiveObjectInspector inputOI;
private StandardListObjectInspector loi;
private StandardListObjectInspector internalMergeOI;
@Override
public ObjectInspector init(Mode m, ObjectInspector[] parameters)
throws HiveException
{
super.init(m, parameters);
if (m == Mode.PARTIAL1)
{
inputOI = (PrimitiveObjectInspector) parameters[0];
return ObjectInspectorFactory
.getStandardListObjectInspector((PrimitiveObjectInspector) ObjectInspectorUtils
.getStandardObjectInspector(inputOI));
}
else
{
if (!(parameters[0] instanceof StandardListObjectInspector))
{
inputOI = (PrimitiveObjectInspector) ObjectInspectorUtils
.getStandardObjectInspector(parameters[0]);
return (StandardListObjectInspector) ObjectInspectorFactory
.getStandardListObjectInspector(inputOI);
}
else
{
internalMergeOI = (StandardListObjectInspector) parameters[0];
inputOI = (PrimitiveObjectInspector) internalMergeOI.getListElementObjectInspector();
loi = (StandardListObjectInspector) ObjectInspectorUtils.getStandardObjectInspector(internalMergeOI);
return loi;
}
}
}
static class ArrayAggregationBuffer implements AggregationBuffer
{
ArrayList<Object> container;
}
@Override
public void reset(AggregationBuffer ab)
throws HiveException
{
((ArrayAggregationBuffer) ab).container = new ArrayList<Object>();
}
@Override
public AggregationBuffer getNewAggregationBuffer()
throws HiveException
{
ArrayAggregationBuffer ret = new ArrayAggregationBuffer();
reset(ret);
return ret;
}
@Override
public void iterate(AggregationBuffer ab, Object[] parameters)
throws HiveException
{
assert (parameters.length == 1);
Object p = parameters[0];
if (p != null)
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
agg.container.add(ObjectInspectorUtils.copyToStandardObject(p, this.inputOI));
}
}
@Override
public Object terminatePartial(AggregationBuffer ab)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> ret = new ArrayList<Object>(agg.container.size());
ret.addAll(agg.container);
return ret;
}
@Override
public void merge(AggregationBuffer ab, Object o)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> partial = (ArrayList<Object>)internalMergeOI.getList(o);
for(Object i : partial)
{
agg.container.add(ObjectInspectorUtils.copyToStandardObject(i, this.inputOI));
}
}
@Override
public Object terminate(AggregationBuffer ab)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> ret = new ArrayList<Object>(agg.container.size());
ret.addAll(agg.container);
return ret;
}
}
}
Then in hive, just issue add jar Whatever.jar; and CREATE TEMPORARY FUNCTION collect_all AS 'com.example.CollectAll';
You should them be able to use it as expected.
hive> SELECT hash_id, collect_all(num_of_cats) FROM test GROUP BY hash_id;
OK
ad3jkfk [4,4,2]
fkjh43f [1,8,8]
rjkhd93 [7,4,7]
It's worth noting that the order of the elements should be considered undefined, so if you intend to use this to feed information into n_grams you might need to expand it a bit to sort the data as needed.
A:
Modified Jeff Mc's code to remove the restriction (presumably inherited from collect_set) that input must be primitive types. This version can collect structs, maps and arrays as well as primitives.
package com.example;
import java.util.ArrayList;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.StandardListObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
public class CollectAll extends AbstractGenericUDAFResolver
{
@Override
public GenericUDAFEvaluator getEvaluator(TypeInfo[] tis)
throws SemanticException
{
if (tis.length != 1)
{
throw new UDFArgumentTypeException(tis.length - 1, "Exactly one argument is expected.");
}
return new CollectAllEvaluator();
}
public static class CollectAllEvaluator extends GenericUDAFEvaluator
{
private ObjectInspector inputOI;
private StandardListObjectInspector loi;
private StandardListObjectInspector internalMergeOI;
@Override
public ObjectInspector init(Mode m, ObjectInspector[] parameters)
throws HiveException
{
super.init(m, parameters);
if (m == Mode.PARTIAL1)
{
inputOI = parameters[0];
return ObjectInspectorFactory
.getStandardListObjectInspector(ObjectInspectorUtils
.getStandardObjectInspector(inputOI));
}
else
{
if (!(parameters[0] instanceof StandardListObjectInspector))
{
inputOI = ObjectInspectorUtils
.getStandardObjectInspector(parameters[0]);
return (StandardListObjectInspector) ObjectInspectorFactory
.getStandardListObjectInspector(inputOI);
}
else
{
internalMergeOI = (StandardListObjectInspector) parameters[0];
inputOI = internalMergeOI.getListElementObjectInspector();
loi = (StandardListObjectInspector) ObjectInspectorUtils.getStandardObjectInspector(internalMergeOI);
return loi;
}
}
}
static class ArrayAggregationBuffer implements AggregationBuffer
{
ArrayList<Object> container;
}
@Override
public void reset(AggregationBuffer ab)
throws HiveException
{
((ArrayAggregationBuffer) ab).container = new ArrayList<Object>();
}
@Override
public AggregationBuffer getNewAggregationBuffer()
throws HiveException
{
ArrayAggregationBuffer ret = new ArrayAggregationBuffer();
reset(ret);
return ret;
}
@Override
public void iterate(AggregationBuffer ab, Object[] parameters)
throws HiveException
{
assert (parameters.length == 1);
Object p = parameters[0];
if (p != null)
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
agg.container.add(ObjectInspectorUtils.copyToStandardObject(p, this.inputOI));
}
}
@Override
public Object terminatePartial(AggregationBuffer ab)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> ret = new ArrayList<Object>(agg.container.size());
ret.addAll(agg.container);
return ret;
}
@Override
public void merge(AggregationBuffer ab, Object o)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> partial = (ArrayList<Object>)internalMergeOI.getList(o);
for(Object i : partial)
{
agg.container.add(ObjectInspectorUtils.copyToStandardObject(i, this.inputOI));
}
}
@Override
public Object terminate(AggregationBuffer ab)
throws HiveException
{
ArrayAggregationBuffer agg = (ArrayAggregationBuffer) ab;
ArrayList<Object> ret = new ArrayList<Object>(agg.container.size());
ret.addAll(agg.container);
return ret;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
In which case PHP sort function returns FALSE?
PHP sort() function and other functions from this family returns
true on success or false on failure. In which case sort function returns false? What is possible source of failure?
Example:
$array = [1, 5, 22, 8, 3, 3];
$returnValue = sort($array);
var_dump($returnValue); // bool(true)
I can't imagine any case in which $returnValue could be false.
I have also tried sort variants with user-defined comparison function, which can possibly introduce some error, but with no success.
$array = [1, 5, 22, 8, 3, 3];
$returnValue = usort($array, function($a, $b) { return 'Hello World'; });
var_dump($returnValue); // bool(true)
Actually you can do whatever you want in your comparison function, because callback's return value is internally
casted to integer, and you will get $returnValue === true everytime. This also applies for user-defined comparison function
without returned value. PHP returns null in this case, which is internally casted to integer: (int)null === 0
and thus everything is correct.
A:
It will return false if parameter one is not an array
| {
"pile_set_name": "StackExchange"
} |
Q:
Example of a deterministic algorithm?
Good evening I was wondering if someone could please provide me with a simple pseudocode example of a deterministic algorithm... I will greatly appreciate it and surely give you points!!. thanks
A:
To me, "deterministic" could mean many things:
Given the same input, produces the same output every time.
Given the same input, takes the same amount of time/memory/resources every time it is run.
Problems of complexity class P that can be solved in polynomial time by a deterministic computer, as opposed to problems of complexity class NP which can be only solved in polynomial time using a non-deterministic computer.
Which of these do you mean?
The most simple deterministic algorithm is this random number generator.
def random():
return 4 #chosen by fair dice roll, guaranteed to be random
It gives the same output every time, exhibits known O(1) time and resource usage, and executes in PTIME on any computer.
| {
"pile_set_name": "StackExchange"
} |
Q:
android find custom view by attribute
I'm working with a layout, that hosts many custom views. Each custom view has "myname:num" attribute, that holds unique number value.
Question: how can I find a view by "num" attribute? Normally I would use findViewById() method, but since the "android:id" can't be a number, I have to find another solution.
Layout definition:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myname="http://schemas.android.com/apk/res/com.example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.custom.MyView
myname:num="17"
myname:type="2" />
<com.example.custom.MyView
myname:num="18"
myname:type="2" />
<com.example.custom.MyView
myname:num="19"
myname:type="2" />
</LinearLayout>
</LinearLayout>
A:
Give each view an id, and then in your activity you can dynamically call each view by using
int dynamicId = getResources().getIdentifier("*unique_id*", "id", "*package_name*");
findViewById(dynamicId);
So if you id'ed each incrementally as view_1, view_2, ... view_numViews you can then get them dynamically using something like a loop
for(int i = 1; i <= numViews; i ++){
int dynamicId = getResources().getIdentifier("view_" + i, "id", "*package_name*");
MyView view = (MyView) findViewById(dynamicId);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Food Timing: Keeping Bacon Warm While Cooking With Bacon Fat Made from Said Bacon
The Situation:
Guy decides he wants to make bacon and potato cubes (I can't think of a better term) for breakfast.
Guy wants to cook potatoes in bacon fat
Guy cooks bacon and places bacon on paper towels to dry off
Guy cooks potatoes in left over bacon fat
By the time potatoes are done (20 mins or so), the bacon is cold :(
What can be done to remedy this? Should I just wrap the bacon in tin-foil? I've yet to fully master "timing" when it comes to cooking two different parts of a meal at the same time
A:
I render off the necessary fat over low heat, then remove the bacon strips, increase the heat, and fry using the rendered fat. When nearly done, I return the bacon to the pan to crisp it before serving.
Of course, you could also just save the grease from one batch to use with the next, thereby ensuring you always have both fresh-cooked bacon and (reasonably-fresh) grease to use without having to produce the former before the latter.
A:
Turn your oven on as low as it will go. Put the cooked bacon in there, it will keep warm.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why this implementations have different results?
Hi i need to generate some hash / checksum from same text in c# and ts/js
i found some solution here on stackoverflow but have some issue
so my js
private getStableHash(s, hashlength) {
let hash = 0;
const bytes = this.string2Bin(s);
for (let i = 0; i < bytes.length; i++) {
hash += bytes[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
// final avalanche
hash += (hash << 3);
console.log(hash);
hash ^= (hash >> 11);
console.log(hash);
hash += (hash << 10);
console.log(hash);
return Math.round(hash % hashlength);
}
private string2Bin(str) {
const result = [];
for (let i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
and c#
private int GetStableHash(string s, int hashlength)
{
int hash = 0;
var bytes = System.Text.Encoding.ASCII.GetBytes(s);
foreach (byte b in bytes)
{
hash += b;
hash += (hash << 10);
hash ^= (hash >> 6);
}
// final avalanche
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 10);
return (int)(hash % hashlength);
}
getStableHash('dbo.files.xxx.yyy.zzz/aaa/3',10000000)
returns 7414302 in both cases so it is FINE
but if i change this last line
hash += (hash << 10);
to
hash += (hash << 15);
in both implementations
c#change in this line 474798750 to -1986274658 and returns -6274658
and
js changein this line 474798750 to 2308692638 and returns 8692638
why is that ? what im missing here?
regards !
A:
int in C# is a singed 32bit integer. If you do bitshifting that sets the first bit to 1, the number will get negative.
numbers in JS are 64bit floating point numbers, with 52bit integer precision. Bitwise operators are however only done on a 32bit signed representation of the number.
Therefore the bitshifting << is the same in both, but the addition += only works on 32 bit in C#, but on 52bit in JS.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to increase webview height dynamically in android
Can anybody tell me how to increase the webview height dynamically in android? My webview content will come some time less and sometimes I have to show webview full layout.
Thanks
A:
use this code
android:layout_height="wrap_content"
then you find web view height automatically increase.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent IndexedDb from growing exponentially in chrome
I wanted to try IndexedDB, to see if it is fit for my purpose.
Doing some testing, I noticed, that its grow rate seems to be exponentially with every insert.
(Only tested in google chrome version 31.0.1650.63 (Offizieller Build 238485) m / Windows by now)
My Code in full: http://pastebin.com/15WK96FY
Basically I save a string with 2.6 mio characters.
Checking window.webkitStorageInfo.queryUsageAndQuota I see that it consumes ~7.8MB, meaning ~3 bytes per character used.
If I save the string 10 times however, I get a usage of ~167MB, meaning ~6.4 bytes per character used.
By saving it 50 times I'm high up in the gigabytes and my computer starts to freeze.
Am I doing something wrong or is there a way around this behaviour?
A:
Your test is wrong. Field test2 should not be indexed.
| {
"pile_set_name": "StackExchange"
} |
Q:
${\rm Aut}(G)$ is cyclic $\implies G$ is abelian
I would appreciate if you could please express your opinion about my proof. I'm not yet very good with automorphisms, so I'm trying to make sure my proofs are OK.
Proof:
Since ${\rm Aut}(G)$ is cyclic, ${\rm Aut}(G)$ is abelian. Thus for any elements $\phi, \psi \in{\rm Aut}(G)$ and some elements $g_i \in G$, $\phi\psi(g_1g_2)=\phi\psi(g_1)\phi\psi(g_2)=g_3g_4=\phi\psi(g_2)\phi\psi(g_1)=\phi\psi(g_2g_1)=g_4g_3$. Hence, $g_3g_4=g_4g_3\implies G$ is abelian.
The proof seems to be quite straightforward, but I'd rather ask for advice.
A:
There is a nice chain of small results which proves this which continues down the path that Groups suggests. If ${\rm Aut}(G)$ is cyclic, then so is any subgroup of it, in particular ${\rm Inn}(G)$. ${\rm Inn}(G)\cong G/Z(G)$ where $Z(G)$ is the center. If $G/Z(G)$ is cyclic, the group is abelian.
A:
The $\phi,\psi$ commute, and also the following steps are also OK:
$$\phi\psi(g_1g_1)=\phi\psi(g_1)\phi\psi(g_2)=g_3g_4.$$
Its not clear in your argument why $g_3g_4=\phi\psi(g_2)\phi\psi(g_1)$?
We are allowed to use commutativity of maps $\phi,\psi$, and we have to conclude commutativity of $g_1,g_2$. You may proceed in following directions.
(1) Consider a specific subgroup of ${\rm Aut}(G)$, namely ${\rm Inn}(G)$. How it is related with $G$?
(2) ${\rm Aut}(G)$ is cyclic, so is ${\rm Inn}(G)$, then using (1), what this will imply?
| {
"pile_set_name": "StackExchange"
} |
Q:
Akka Stream test flow when Supervision.Resume implemented
I recently implemented an akka-stream flow which parse some json messages, validate the presence of a given key (destination_region) and pass to the next stage a case class containing the original message and the destination_region string.
I implemented a custom decider so that in case it face any parsing or key error, it will trigger Supervision.Resume after logging the exception.
A minimalistic implementation would look like:
package com.example.stages
import com.example.helpers.EitherHelpers._
/*
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
object EitherHelpers {
implicit class ErrorEither[L <: Throwable, R](val either: Either[L, R]) extends AnyVal {
def asFuture: Future[R] = either.fold(Future.failed, Future.successful)
def asTry: Try[R] = either.fold(Failure.apply, Success.apply)
}
}
*/
import scala.concurrent.ExecutionContext
import akka.NotUsed
import akka.stream.scaladsl.Flow
import akka.stream.ActorAttributes.supervisionStrategy
import akka.stream.Supervision
import software.amazon.awssdk.services.sqs.model.Message
import io.circe.parser.parse
import io.circe.{DecodingFailure, ParsingFailure}
object MessageContentValidationFlow {
def apply()(
implicit executionContext: ExecutionContext): Flow[Message, MessageWithRegion, NotUsed] = {
val customDecider: Supervision.Decider = {
case e @ (_: DecodingFailure | _: ParsingFailure) => {
println(e)
Supervision.Resume
}
case _ => Supervision.Stop
}
Flow[Message]
.mapAsync[MessageWithRegion](2) { message =>
println(s"Received message: $message")
val messageWithRegion = for {
parsed <- parse(message.body()).asFuture
region <- parsed.hcursor.downField("destination_region").as[String].asFuture
} yield { MessageWithRegion(message, region) }
messageWithRegion
}
.withAttributes(supervisionStrategy(customDecider))
}
}
case class MessageWithRegion(message: Message, region: String)
I managed to test the case where the message is valid, however I have not clue about how to test the flow in case of ParsingFailure or DecodingFailure. I have tried almost all methods available for sub in the implementation below:
package com.example.stages
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Keep
import akka.stream.testkit.scaladsl.{TestSink, TestSource}
import io.circe.generic.JsonCodec, io.circe.syntax._
import io.circe.generic.auto._
import software.amazon.awssdk.services.sqs.model.Message
import org.scalatest.FlatSpec
@JsonCodec case class MessageBody(destination_region: String)
class MessageContentValidationFlowSpecs extends FlatSpec {
implicit val system = ActorSystem("MessageContentValidationFlow")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val (pub, sub) = TestSource.probe[Message]
.via(MessageContentValidationFlow())
.toMat(TestSink.probe[MessageWithRegion])(Keep.both)
.run()
"MessageContentValidationFlow" should "process valid messages" in {
val validRegion = "eu-west-1"
val msgBody = MessageBody(validRegion).asJson.toString()
val validMessage = Message.builder().body(msgBody).build()
sub.request(n = 1)
pub.sendNext(validMessage)
val expectedMessageWithRegion = MessageWithRegion(
message = validMessage,
region = validRegion
)
assert(sub.requestNext() == expectedMessageWithRegion)
}
ignore should "trigger Supervision.Resume with empty messages" in {
val emptyMessage = Message.builder().body("").build()
assert(emptyMessage.body() == "")
sub.request(n = 1)
pub.sendNext(emptyMessage)
sub.expectComplete()
}
}
Does anyone know how to test that Supervision.Resume was triggered and which exception was caught by the custom decider?
A:
Since Supervision.Resume drops erroneous elements and continues processing the stream, one way to test that supervision strategy is to run a stream that contains a mix of "good" and "bad" elements and confirm whether the materialized value consists of only the "good" elements. For example:
import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import org.scalatest._
import scala.concurrent._
import scala.concurrent.duration._
class MyTest extends FlatSpec with Matchers {
implicit val system = ActorSystem("MyTest")
implicit val materializer = ActorMaterializer()
val resumingFlow = Flow[Int].map {
case 2 => throw new RuntimeException("bad number")
case i => i
}.withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider))
"resumingFlow" should "drop the number 2" in {
val result: collection.immutable.Seq[Int] =
Await.result(Source((1 to 5).toSeq).via(resumingFlow).runWith(Sink.seq), 5.seconds)
result should be (List(1, 3, 4, 5))
}
}
In your case, create a stream that has valid Message objects and at least one invalid Message object.
| {
"pile_set_name": "StackExchange"
} |
Q:
java- how to logically process n-levels of for loops where n is a variable
In a java program, I am getting some data with each value being assigned a name-
Each data item has a 'level' which is a numeric value.
For level 1, there are 'n' number of values--
the data items have names
1-1, 1-2, 1-3.....1-n.
Now, level 2 items have names which are derived from level 1's data items.
So there can be 'm' values of level 2, corresponding to each level 1 item. In the name of each data item, each named section corresponding to a level, is separated from other section of name with a '~'.
For eg,
1-1~2-1, 1-1~2-2, 1-1~2-3......1-1~2-m --->level2 corresp. to level 1 item "1-1"
1-2~2-1, 1-2~2-2, 1-2~2-3, ....1-2~2-m--->level2 corresp. to level 1 item "1-2"
Now, I want to create a function where a parameter is number of levels, and I want to programmatically access all items of that level.
For eg, I can create a for loop within another for loop, to access items of level 2.
But how do I do this for level=x, where x is a variable?
A:
The simplest approach is to use recursion as well as a loop.
public static int count(List list) {
int sum = 0;
for(Object o: list) {
sum += o instanceof List ? count((List) o) : 1;
}
return sum;
}
As you can see, this will iterate through every element at every level.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to setup Eclipse to connect to a mobile device (generate crash logs regarding android/ios app crashes)
I've searched online about getting crash logs from android and/or ios devices but could not find anything. I am testing an external app atm and have solid steps to reproduce a crash. Though, I can get a crash log/dump for the developer by using Eclipse... any guides on how to do so? Thanks.
A:
To be able to see log calls and other info, you have to enable Debug Mode in your device.
You also need a specific driver to use your device with ADT. If you don't have that driver you can download a generic one from google in SDK Manager > Extras.
But be aware that "commercial" apps (downloaded from Google Play) are not debuggable,
or at least should not be.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVVM: Use DataGrid CheckBox IsChecked property to control the neighboring TextBox's TextDecorations
I need to accomplish the following without breaking MVVM (no code-behind/events). I have a DataGrid with a CheckBox column and a TextBox column. If the checkbox is checked, I'd like to change the TextBox's TextDecorations property to Strikethrough. While the compiler doesn't hate my XAML, it doesn't work. My XAML for the DataGridTextBoxColumn is as follows:
<DataGridTextColumn Header="Item Description" Binding="{Binding Path=ItemDescription, Mode=TwoWay}" Width="175">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="TextAlignment" Value="Center" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=complete, Path=IsChecked}" Value="True">
<Setter Property="TextDecorations" Value="Strikethrough"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
A:
Because of for each element in ItemsSource DataGrid creates its own TextBlock and CheckBox during runtime you can't have binding to this elements by names. Instead you should bind both CheckBox's Value and TextBlock's Style Setters to your Model. For example you have Model and ViewModel like this:
Model:
public class SomeModel : INotifyPropertyChanged
{
private string textField;
private bool boolField;
public event PropertyChangedEventHandler PropertyChanged;
public string TextField
{
get { return textField; }
set
{
if (value == textField) return;
textField = value;
OnPropertyChanged();
}
}
public bool BoolField
{
get { return boolField; }
set
{
if (value.Equals(boolField)) return;
boolField = value;
OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
ViewModel:
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<SomeModel> models;
public ObservableCollection<SomeModel> Models
{
get { return models; }
set
{
if (Equals(value, models)) return;
models = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
Models = new ObservableCollection<SomeModel>();
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
So now you can bind BoolField of your Model to the CheckBox's Value and TextBlock's Style Setters in View:
MainView.cs:
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
var mv = new MainViewModel
{
Models = { new SomeModel { BoolField = true, TextField = "One" }, new SomeModel { TextField = "Two" } },
};
DataContext = mv;
}
}
MainView.xaml:
<Window x:Class="WpfDataGridCols.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainView" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding Models}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding TextField}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="TextAlignment" Value="Center" />
<Style.Triggers>
<!--Pay attention on this:-->
<DataTrigger Binding="{Binding BoolField}" Value="True">
<Setter Property="TextDecorations" Value="Strikethrough"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridCheckBoxColumn Binding="{Binding BoolField}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
| {
"pile_set_name": "StackExchange"
} |
Q:
c# Generics help - how to pass params to new T()
Possible Duplicate:
Create instance of generic type?
How can I pass a param to a generic contstructor?
public class Payment<T> where T: HostFunctionContext, IClaimPayment, new()
{
public IResultEntity Display(MyUser user, string claim, int? cert)
{
**HostFunctionContext func = new T(user) as HostFunctionContext;** <~doesn't compile
IClaimPayment payment = new T();
payment.ClaimNumber = claimNumber;
payment.CertificateSequence = certSequence;
return payment.DisplayEntity();
}
}
public sealed partial class CardPayment : HostFunctionContext
{
public CardPayment(MyUser user) : base(user) { }
}
constructor for abstract HostFunctionContext
public HostFunctionContext(MyUser user) {
_hostConnection = HostConnectionAssembler.GetHostConnection();
_functionParams = FunctionParamsAssembler.GetFunctionParams();
if (user != null) {
_hostConnection.Login = user.Login;
}
}
I need to pass the user to the baseclass of T. How can I do this? Do I create a parameterless constructor, then a property of type MyUser, then on the set of that property push that to the baseclass? The abstract baseclass has no myUser property and no parameterless constructor. I am really stuck here.
Thanks for any help,
~ck
A:
The new() keyword by definition restricts your generic parameter to be a reference type with a public, parameterless constructor. When you instantiate a "new T()", it has to use reflection to create an instance of it.
You may want to use a factory pattern to create your objects instead of trying to do it through a generic constructor. You could pass the type into the factory and have the factory logic pass you back the correct object type, initialized with the user.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are reflections in higher dimensions commutative?
If $~r_1, r_2 ,\cdots, r_t~$ are a sequence of reflections about $~x_1=\frac{1}{2},\cdots,x_n=\frac{1}{2}~$ respectively in n dimensions does the sequence of reflections matter?
A:
Absolutely! The order matters.
In $\Bbb{R}^n$ the orthogonal reflection $s_{ij}$ with respect to the hyperplane $x_i=x_j$ interchanges the two involved coordinates:
$$s_{ij}:(x_1,\ldots,x_i,\ldots,x_j,\ldots,x_n)\mapsto
(x_1,\ldots,x_{i-1},x_j,x_{i+1},\ldots,x_{j-1},x_i,x_{j+1},\ldots,x_n).
$$
In other words, it permutes the coordinates according to the 2-cycle $(ij)$.
But from an encounter with permutation groups you probably remember that 2-cycles don't always commute. For they generate the entire symmetric group $S_n$, which is non-commutative when $n\ge3$.
As Lee Mosher explained, an even simpler case of non-commuting reflections is with respect to two parallel hyperplanes. In that case the commutator of the two reflections is a translation.
But, if two hyperplanes, $H_1$ and $H_2$, in $\Bbb{R}^n$ are orthogonal to each other (= if their respective normal vectors are orthogonal), then they do commute.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't access form values in a $modalInstance
I'm opening a $modalInstance in which user has to choose an option from radio inputs (values loaded dynamically) and return chosen value.
I have this function to open the $modalInstance:
$scope.openAddFriendGroup = function () {
var addFriendGroupModal = $modal.open({
templateUrl: "addFriendGroupModal.html",
controller: ModalAddFriendGroupCtrl,
resolve: {
myDetails: function () {
return $scope.info;
}
}
});
};
Then this is the $modalInstance controller:
var ModalAddFriendGroupCtrl = function ($scope, $modalInstance, myDetails, groupsSvc) {
$scope.addableFriends = [];
$scope.chosenFriend = null;
//here goes a function to retrieve value of $scope.addableFriends upon $modalInstance load
$scope.addFriend = function () {
$scope.recording = true;
groupsSvc.addFriend($scope.chosenFriend, myDetails).then(function (response) {
if(response.status && response.status == 200) {
$modalInstance.close($scope.userid);
}
}, function (err) {
$modalInstance.dismiss(err);
});
};
};
And this is addFriendGroupModal.html, the HTML for the modal itself:
<div id="add-friend-group-modal">
<div class="modal-header">
<h3 class="modal-title">Add friend</h3>
</div>
<div class="modal-body">
<form class="form" role="form" ng-hide="loading">
<div class="form-group">
<label class="control-label">Friend:</label>
<div class="radio" ng-repeat="thisFriend in addableFriends">
<label>
<input type="radio" id="friend{{thisFriend.id}}" name="chosenFriend" ng-model="$parent.chosenFriend" ng-value="thisFriend" /> {{thisFriend.name}} {{thisFriend.surname}}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="addFriend()">Add friend</button>
</div>
</div>
Now, the problem comes when I try to retrieve the value that has been selected in the radio buttons of the form in the modal. I can't seem to retrieve this value in $scope.addFriend. The value of $scope.chosenFriend stays at null and does not get updated when selecting a radio option.
What am I doing wrong?
A:
Retrieved answer from a related question, by gertas
Angular-UI modals are using transclusion to attach modal content, which means any new scope entries made within modal are created in child scope. This happens with form directive.
This is known issue: https://github.com/angular-ui/bootstrap/issues/969
I proposed the quick workaround which works for me, with Angular 1.2.16:
<form name="$parent.userForm">
The userForm is created and available in modal's controller $scope. Thanks to scope inheritance userForm access stays untouched in the markup.
<div ng-class="{'has-error': userForm.email.$invalid}"}>
So, in my form I would have to set a name="$parent.friendForm" attribute to <form>, and then bind the radio button model to it, ng-model="friendForm.chosenFriend" to be able to read it from the modal scope at $scope.friendForm.chosenFriend.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to unpack the contents of a JavaScript file?
You know how those packed js files look like, right?
eval(function(p,a,c,k,e,d){ ... } ('obfuscated-string'.split('|'),0,{}))
It just so happens to be that i have to tweak some large legacy code that looks like that and I want to find a way to turn this into a more readable version.
If that's not possible, can i at least get rid of the eval?
A:
JS Beautifier will both reformat and unpack:
http://jsbeautifier.org/
A:
You can with online unpackers: try one of these, find one that suits you:
Dean Edwards Unpacker
JSUnpack
| {
"pile_set_name": "StackExchange"
} |
Q:
NSXMLParser iPhone Question
I have an XMLParser class which uses NSXMLParser (event-driven) This is being called by an external class (MyVC.m), passing the web service API URL each time.
Here is my question; I have 2 options to parse
If I pass URL as http://xyz.com/sub1/ I get a complete XML file and then will have to parse for some specific nodes
If pass URL as http://xyz.com/sub1/data I get only the data that I require
While option 2 seems to be good, the problem is I am looking for 3-4 data points and so is it better if NSXMLParser is called least no. of times, as in option 1 OR it is not that expensive to have it called multiple times, like in option 2.
A:
Although it's not possible to answer your question based on what you've said, a key part of your question is 'I am looking for 3-4 data points' which implies you can't just ask for the specific items you're looking for without some sort of search through the data.
In general, you should minimise both the number of requests, and the amount of data transferred. There isn't enough information here to say whether the signal/noise ratio (so to speak) means that it's more efficient to transfer the whole lot, or just the items of interest.
If you're interested in most of the data returned, I'd go with returning the whole caboodle. If you're interested in a small subset, and can identify it reasonably efficiently (without returning the whole set) then I might try just fetching those items.
If you wanted to get really fancy, you could adapt the approach based on whether you're on wifi or EDGE, but the return on that is unlikely to be worth the investment of coding / maintenance required ;-)
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to get each element from variable "coin" to dictionary as key
How do I get dictionary from variable coin which I have define in my code. There are 32 elements in variable coin but I'm getting only one key and value which is TUSD in last line.
import requests
import json
r=requests.get('https://koinex.in/api/ticker')
koinexData=r.json()
koinexprice = koinexData['stats']['inr']
for coin in koinexprice:
print(coin)
coindata={}
coindata["koinex"]={
coin:{
"SellingPrice":koinexprice[coin]["highest_bid"],
"buyingPrice":koinexprice[coin]["lowest_ask"]
}
}
# data.append(coindata)
# print(data)``
# s = json.dumps(coindata)
print(s)
A:
You keep overwriting your coindata dictionary inside the loop, which is why only the last value remains. The second issue with your code is that you keep overriding the coindata['koinex'] dictionary inside the loop. This should be a list not a dictionary because you'll keep adding values to it.
If you move the initialization code outside the loop, you will not have this problem:
coindata = {}
coindata['koinex'] = [] # this should be a list, not a dictionary
for coin in koinexprice:
print(coin)
# Create a temporary dictionary d to hold the data you want
# to add to coindata
d = {coin: {'SellingPrice': koinexprice[coin]['highest_bid'],
'buyingPrice': koinexprice[coin]['lowest_ask']}
}
coindata["koinex"].append(d) # add the new dictionary to the list
print(coindata)
| {
"pile_set_name": "StackExchange"
} |
Q:
issue KeyStroking in mac OS X vs windows
public void keyStrokeActions(){
screen.setFocusable(true);
screen.getInputMap().put(KeyStroke.getKeyStroke("pressed SPACE"),"attackAction");
screen.getActionMap().put("attackAction",attackAction);
screen.getInputMap().put(KeyStroke.getKeyStroke("pressed P"),"pauseAction");
screen.getActionMap().put("pauseAction",pauseAction);
}
I am trying to make this work, as you can see it's a simple keyStroking where screen's a JPanel. The actions attackAction and pauseAction are defined before as global variables.
In windows everything works perfectly, however in mac it doesn't. No matter the key I press, it doesn't react. I also tried
screen.getInputMap().put(KeyStroke.getKeyStroke(' ',0),"attackAction");
and
screen.getInputMap().put(KeyStroke.getKeyStroke(' '),"attackAction");
But I couldn't make it work. Not with ' ' or 'P' or any other sort of char. Anyone could bring some light?
Thanks,
Sergi.
A:
After a lot of time working on it, I found out that if it worked on Mac it didn't on windows, and if it worked in windows it didn't on Mac. So, basically, java's multi-platform as long as the virtual machine's fine with it.
| {
"pile_set_name": "StackExchange"
} |
Q:
One column (boolean) defines the other (boolean) but not vice versa
Let's assume life is not only existent on earth but there are also other living things in the universe. I have a table that shows all kinds of species of the whole world
+----+---------------+-------+-------+
| id | name | green | forgn |
+----+---------------+-------+-------|
| 1 | belgian horse | false | false |
| 2 | polar bear | false | false |
| 3 | andromeda dog | true | true |
| 4 | cosmos cat | true | true |
| 5 | amazon parrot | true | false |
...
We also know that every extraterrestrial being (in this case andromeda dog and cosmos cat) has a green color. So I'd like to define a constraint that if forgn is true, green must also be true, but it doesn't apply the other way around, so for example an amazon parrot is a green animal still it doesn't live outside the earth.
I think I should do it somehow using CHECK but I'm not quite sure how.
A:
if you use boolean type then true > false
In this case you can use
CREATE TABLE tablename (
..........
CHECK (green >= forgn)
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Prohibiting an IP range from going out to the Internet in Red Hat/CentOS Linux
I have a VPN, and my server frequently sends data to a private IP address that routes over the VPN. When the OpenVPN gets established or dies, it enables/disables the routes.
I want to null-route that private IP range from going out over the main Internet interface (eth0). Is there an easy way to do that without interfering with the route commands coming from the VPN software?
Iptables won't do it. I tried
iptables -A OUTPUT -i eth0 -p tcp -d 192.168.0.0/16 -j REJECT
But iptables does not work when specifying an interface in the output chain.
Anyone know if there is a way to add a dummy route onto a specific interface (eth0) only, without interfering with other interfaces that may be using that route?
Ps- I am aware 192.168.0.0/16 is not INTERNET routeable, but for security reasons, want to ensure no data gets out in the rare chance another local server or network device starts listening on the private subnet.
A:
Your interface specification in the iptables rule is backward.
You specified:
iptables -A OUTPUT -i eth0 -p tcp -d 192.168.0.0/16 -j REJECT
Using -i matches traffic that enters the system on the named interface.
Instead, you want to match traffic leaving the system on the named interface, which is done with -o.
iptables -A OUTPUT -o eth0 -p tcp -d 192.168.0.0/16 -j REJECT
(And you probably don't want -p tcp in there, otherwise non-TCP traffic might pass.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing malloc to new operator
I am changing a path planning code from C to C++. The code dynamically allocates the states in map. I don't clearly understand the difference between new and malloc. I get an error for following snippet of code.
typedef struct cell
{
int x,y;
struct cell *n[5];
}cell_t;
typedef struct pq
{
cell_t **heap;
int len,cap;
}pq_t;
//for C version
func(pq_t *pq,50)
{
pq->heap = malloc(sizeof(cell)*50);
pq->len = 0;
pq->cap = 0;
}
//for C++ version
func(pq_t *pq,50)
{
pq->heap = (cell_t*)::operator new(sizeof(cell_t)*50);
pq->len = 0;
pq->cap = 0;
}
The error I get is :
cannot convert ‘cell_t* {aka cell*}’ to ‘cell_t** {aka cell_s**}’ in assignment
pq->heap =(cell_t*) ::operator new (sizeof(cell_t) * (50));""
What do I need to change?
A:
Instead of this:
pq->heap = (cell_t*)::operator new(sizeof(cell_t)*50);
You want this:
pq->heap = new cell_t[50];
That said, it's clear that the code you've posted is not quite your real code, so there could be some additional mistake in there. Maybe update your question with real code that compiles.
A:
new takes the type or an array of types, the size is then calculated i.e.
cell_t* p = new cell_t // allocate one cell
cell_t* p = new cell_t[50] // allocate 50 cells.
However I think you would be much better off with using one of the standard containers in your program like std::vector
#include <vector>
..
std::vector<cell_t> myarray(50); // allocate 50 cell_t
then you do not need to concern yourself with freeing the memory, std::vector handles that for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set monday as first day of week in SQL Server
I am running SQL Server 2008 on a machine with regional settings that have Monday as the first day of the week. If I create a computed column in a table to compute the day of week for a date field then I get 2 for a Monday date instead of 1.
Is there some property for the table or database or server that I need to set ?
A:
The first day of the week is based on your language settings of the server. The default setting for us_english is 7 (Sunday)
You can find the current first day of the week by using SELECT @@DATEFIRST
However, you can use DATEFIRST for this. Just put it at the top of your query
SET DATEFIRST 1; this sets Monday to the first day of the week for the current connection.
http://technet.microsoft.com/en-us/library/ms181598.aspx
A:
Just set in query
SET DATEFIRST 1;
Value
First day of the week is
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 (default, U.S. English) Sunday
| {
"pile_set_name": "StackExchange"
} |
Q:
unable to receive UDP broadcast in Xamarin.Forms app
I created a test Xamarin.Forms project, tabbed app, with support for iOS, Android, and UWP. The app with the boilerplate starter code builds and and runs correctly on all 3 platforms.
Am trying to test receiving UDP broadcast in the app. The UDP broadcast is being sent from another machine on the same subnet (have tested broadcasting from another machine and from the same machine, results are the same). If I run a standalone, unmanaged UDP listener test tool on this machine (one we wrote internally), I can see all the messages coming through from the other machine.
I added the code (shown below) to the Xamarin.Forms project and ran the UWP build on this machine. What I'm seeing is that in the debug output I get the "started receiving" message, then nothing else. I'm not actually receiving the messages (or at least, the callback is not being invoked). I checked netstat and can see that when my Xamarin.Forms app is running, it is bound to the specified UDP port. But my OnUdpDataReceived never gets called.
EDIT: I double-clicked the UWP project's Package.appxmanifest file in solution explorer which brought up a UI and in that I checked "Capabilities >> Internet (Client & Server)" thinking it was a permissions thing, but this did not help.
EDIT: I verified connectivity by creating two console projects, a sender and a receiver. The sender just loops forever sending a test UDP broadcast each second. The receiver uses the same code shown here. These projects work as expected. So the same receiver code is working in the console project, but not in the Xamarin.Forms project.
First, a simple UDP receiver class.
public class BaseUdpReceiver
{
private UdpClient _udpClient;
public BaseUdpReceiver()
{
}
public void Start()
{
_udpClient = new UdpClient()
{
ExclusiveAddressUse = false,
EnableBroadcast = true
};
_udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, Constants.Network.SOME_CONSTANT_PORT_INTEGER));
_udpClient.BeginReceive(OnUdpDataReceived, _udpClient);
Debug.WriteLine($">>> started receiving");
}
private static void OnUdpDataReceived(IAsyncResult result)
{
Debug.WriteLine($">>> in receive");
var udpClient = result.AsyncState as UdpClient;
if (udpClient == null)
return;
IPEndPoint remoteAddr = null;
var recvBuffer = udpClient.EndReceive(result, ref remoteAddr);
Debug.WriteLine($"MESSAGE FROM: {remoteAddr.Address}:{remoteAddr.Port}, MESSAGE SIZE: {recvBuffer?.Length ?? 0}");
udpClient.BeginReceive(OnUdpDataReceived, udpClient);
}
}
Then, the code in App.xaml.cs which uses this class.
public partial class App : Application
{
private BaseUdpReceiver _udpReceiver;
public App()
{
InitializeComponent();
DependencyService.Register<MockDataStore>();
MainPage = new MainPage();
_udpReceiver = new BaseUdpReceiver();
_udpReceiver.Start();
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
version info
Visual Studio 2019 Enterprise v16.4.5
Xamarin 16.4.000.322 (d16-4@ddfd842)
Windows 10 64-bit v1909 (OS Build 18363.657)
Microsoft.NETCore.UniversalWindowsPlatform, v6.2.9
NETStandard.Library, v2.0.3
Xamarin.Essentials, v1.5.0
Xamarin.Forms, v4.5.0.356
A:
Got it working for both UWP and Android with help from MS support.
Note that the code provided in the original post is correct and works, given the following considerations.
UWP
Due to network isolation with UWP, you can't broadcast and receive on the same machine, while this works fine with the console apps, it doesn't work with Xamarin.Forms UWP, so the trick is you just have to broadcast from a different machine
Need to adjust Package.appxmanifest >> Capabilities settings
On 2 machines (a wifi laptop and wired desktop), I found it was sufficient to have "Internet (Client)" and "Internet (Client & Server)" checked
On a 3rd desktop machine with 2 NICs, one plugged in and one unplugged, it still didn't work with the above options, it was necessary to also check the "Private Networks (Client & Server)"
Android
The emulator appears to create its own subnet, you can see this by checking the emulator's network settings, it clearly isn't on the same subnet as the desktop machine on which its running
As a result, you can't get UDP broadcasts in the Android emulator in an easy way (aside from some sort of forwarding scheme which I did not experiment with)
Verified that with a physical Android tablet (tested with Samsung Galaxy Tab A 8"), it works and I'm able to receive UDP broadcasts
Note that on Android I didn't have to change any permissions from the defaults as with UWP, it worked without issue
iOS
As of yet, have not tested on a physical iOS device, I have an iPhone, but I'm using a cloud Mac build server so can't test on my device
When it comes time to deal with iOS, it looks like I'll probably need to get a local Mac
| {
"pile_set_name": "StackExchange"
} |
Q:
WindowsIdentity.Impersonate in ASP.NET randomly "Invalid token for impersonation - it cannot be duplicated"
I have an ASP.NET app that requires users to sign in with their domain accounts using Basic Authentication. The user can make a selection, then press a button.
At some point after pressing the button is this code: WindowsIdentity.Impersonate(userIdentity.Token). userIdentity is of type WindowsIdentity, and it was previously set to (WindowsIdentity)User.Identity.
userIdentity is stored as a session variable, and I think that's because, after the button is pressed, the page containing this code is called via AJAX.
When I hit this code, it works about 2/3 of the time, but 1/3 of the time, I get this exception: Invalid token for impersonation - it cannot be duplicated. I think the biggest head scratcher for me is why does it work sometimes but not other times? On some sessions, it works several times before failing. On others, it fails right away.
Here's the stack trace:
at System.Security.Principal.WindowsIdentity.CreateFromToken(IntPtr userToken)
at System.Security.Principal.WindowsIdentity..ctor(IntPtr userToken, String authType, Int32 isAuthenticated)
at System.Security.Principal.WindowsIdentity.Impersonate(IntPtr userToken)
at Resource_Booker.BLL.ReservationAgent.SubmitReservationRequest(Reservation reservation, Patron patron) in C:\dev\RoomRes\Resource Booker\BLL\ReservationAgent.cs:line 101
at Resource_Booker.Reserve.reserve_Click(Object sender, EventArgs e) in C:\dev\RoomRes\Resource Booker\Reserve.aspx.cs:line 474
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Here's a confounding factor: I cannot reproduce this problem on my local Windows 7 x64 workstation--albeit my authentication is passed implicitly here since I am using localhost--or on a Windows 2003 32-bit IIS 6.0 environment. It only happens on a pretty vanilla Windows 2008 R2 environment. All these environments are domain members.
A:
Basically what you are seeing is not a security problem as the logon session is cached by IIS for the lifetime of the TCP connection, but HTTP will occasionally cut the TCP connection requiring re-authentication. This will happen seamlessly and invisibly (handled by the browser) but it will invalidate the token, as the logon session will be destroyed when the TCP connection ends.
I.e. for the benefit of @usr, it only works sometimes because the logon session is the same so the token is the same, so the token stored in the session works because it happens to be the same actual token as User.Identity. It's not a way of avoiding the security check it is an implementation detail of the security check.
You shouldn't be storing the identity in the session - it is unnecessary since it is an authenticated connection.
Just use (WindowsIdentity)User.Identity every single time and your problem should go away.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the best method for forcing cache expiration in ASP.NET?
Suppose I have an ASP.NET application running across several web servers behind a load balancer:
Can I:
Force OutputCache (Page and/or Control level) to expire globally?
Force Data Cache (i.e. Cache.Insert) to expire?
Monitor ASP.NET caching usage (keys, RAM, etc) from a central location?
One possible solution would be to have every usage of cache check a file dependency for changes. The file could be touched which would expire all cache. However, this requires developers to include the dependency in all their code. Is their a better solution?
A:
There are many ways to make these caching expire, like page outputcache by
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Time-based dependency simply expires the item at a defined point in time.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(360));
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Cache.SetSlidingExpiration(true);
Now when it comes to monitoring cache, unless there is an API on the cache to tell you, then there is no direct way.
You could of course enumerate the cache,key-value pairs and then calculate the size of each item stored. Doesnt sound easy right??
So here's to make your cache monitoring easy. Frankly saying i never used it myself, but you can give it a try, just the matter of adding a dll to your application.
And here's something for your cache keys view,
' display contents of the ASP.NET Cache
If Cache.Count > 0 Then
cc.Append("<b>Contents of the ASP.NET Cache (" _
& Cache.Count.ToString() & " items):</b><br />")
For Each item As Object In Cache
cc.Append("Key:'" & item.Key & "' Type:" _
& item.Value.GetType().ToString() & "<br />")
Next
Else
cc.Append("<b>ASP.NET Cache is empty</b>")
End If
| {
"pile_set_name": "StackExchange"
} |
Q:
Best Practices for installing PHP5 and MySQL5 on Red Hat Enterprise Linux 4
On an existing iPlanet webserver, we now have to install PHP5 and MySQL 5 on Red Hat Enterprise Linux 4. Are there any recommended guides or best practices for safely installing these 2 tools and hardening them from hackers on this public facing server?
A:
First of all, note that doing this will basically make the server unsupportable by Red Hat, so you're on your own if trouble comes up.
Now that that's out of the way, you'll find MySQL 5 and PHP 5 packages for EL4 in the CentOS Plus repository. Despite the name, these packages will work on both CentOS and RHEL.
A:
First on my list would be to pick a platform which has full support from the distributor - not just legacy support (RHEL4 is now five and half years old and about to go into 'production 3' support mode).
Next on my list would be NOT INSTALLING SOFTWARE WHICH VOIDS the support warranty.
Then I'd have a long hard look at hardening the Operating System - but since you only asked about specific applications I'll skip over that.
Regarding hardening the 2 services....the very basic introduction to Linux hardening from Sans is 15 pages - so I'd strongly recommend you look elsewhere for answers - a quick post on SF will not provide you with a fraction of the questions you need to ask. There are some more guides here.
Do have a look at the suhosin website - even if you stick with the standard distributions of PHP there's a lot of information about why suhosin exists from which you can make informed decisions.
As for mysql - it certainly should not be public facing. In addition to firewalling, you should be disabling all network access if possible - or moving it to a separate server not routable from the internet.
Similarly for mod_security
| {
"pile_set_name": "StackExchange"
} |
Q:
Update a table after inserting records with an Inner Join
I insert into TableA using a Select/Inner Join from TableB and TableC.
Insert into TableA (C,S,M,C100)
SELECT C,S,M,group_concat(CID) FROM TableB
INNER JOIN TableC
ON TableB.CID= TableC.CID and P>=100 group by C,S,M
Now I need to update those records in two ways. One is identical to the first but now I want to update a different field with P<100, in essence:
Insert into TableA (C,S,M,C0)
SELECT C,S,M,group_concat(CID) FROM TableB
INNER JOIN TableC
ON TableB.CID= TableC.CID and P<100 group by C,S,M
Except I don't want new records I want to update where TableA C,S,M match
The second thing I want to do is similar, but involves updating from a different table but in almost an identical manner
Insert into TableA (C,S,M,C100)
SELECT C,S,M,group_concat(CID) FROM TableD
INNER JOIN TableE
ON TableD.CID= TableD.CID and P>=100 group by C,S,M
In other words I could create each pass as separate inserts but would end up with duplicate records of C,S,M.
Is there a way to do the passes after the first insert as Updates OR is there a way to do them each as Inserts and afterwards combine the records where C,S,M are identical?
A:
Use an update with join :
UPDATE TableA
join (select C,S,M,group_concat(CID) as newCol
FROM TableB
where P<100
group by C,S,M) t
ON (tableA.c = t.c and tableA.s = t.s and TableA.M = t.m)
SET <YourColumn> = t.newCol
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need to run AudioServicesCreateSystemSoundID in Thread
I'm using AudioServicesCreateSystemSoundID to play sound, it works fine except I'm not sure if I need to run it on a thread block or, by itself it run on it's own thread.
I'm just afraid it might make my application not responsive if it's run on main thread.
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: @"mysound"
withExtension: @"aiff"];
// Store the URL as a CFURLRef instance
// soundFileURLRef = (__bridge CFURLRef) tapSound ;
// Create a system sound object representing the sound file.
SystemSoundID soundFileObject;
AudioServicesCreateSystemSoundID (
(__bridge_retained CFURLRef) tapSound,
&soundFileObject
);
// AudioServicesPlayAlertSound (soundFileObject);
AudioServicesPlaySystemSound (soundFileObject);
A:
The sound will play asynchronously. You do not need to run it in its own thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any particular technique to shoot down your opponent during Flash bomb in Counter Strike?
How are some players able to precisely shoot opposite team players during a Flash Bomb blast? Normally, it is impossible to see anything in the close proximity. But, it bemuses me that some players can manage to shoot you down even if you are hiding behind the wooden boxes or even if you are in sitting position. They haven't seen you taking that particular position, but they will never miss to kill you.
Is there any particular technique to shoot down your opponent during Flash bomb?
A:
Hitting someone with a flash does not guarantee them to be blind.
It is possible that they turn away or take cover behind an obstacle in time or that the grenade explodes behind them for some other reason. If that happens they're not blind and will still be able to see you.
Remembering a position is a good advantage.
When I know where I looked at before I got flashed I can still use that information to move accordingly. This also includes hiding, shooting at known targets, etc. If a grenade comes your way it is not that hard to guess where it came from (and shoot in that direction if you have the chance). It's also possible to see an opponent just before it goes off. In that case it's not hard to shoot them either.
Knowing popular positions.
Hiding behind a crate does make you invisible, but not invincible. It is common practice to shoot at popular hideouts and depending on the map and situation there are a few spots where almost always someone is hiding. Shooting or throwing grenades there first even without seeing someone is no real magic... just common sense.
Cheating.
Cheats (or "hacks") exist almost everywhere. Counter-Strike is no exception. A "wall hack" as mentioned in the comments is one of these that give the cheater the possibility to see other people through walls. Most of these cheats also include other options, like not being blind when hit by a flash grenade or seeing through smoke, etc. But beware, cheating is a bannable offense and Steam will ban accounts of caught cheaters, so they can no longer join servers protected by Steam (e.g. VAC).
Guessing / Luck
I've had some kills that actually looked like cheating, but they were just luck and/or good timing. There are some situations where you know they're coming. You get flashed, hear their steps and just open fire, because there is only one way they can come from (e.g. Dust2 B site or Nuke ramp). Counter the flash with yours and spray and pray - works for both sides.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exchange data across Cloud Foundry orgs
Our Pivotal Cloud Foundry installation is separated into several organizations (orgs). I am looking for a way to exchange data between apps running in separate orgs via services like Redis or RabbitMQ.
a) What would be the proper way to create a "shared" service instance of Redis or RabbitMQ that can be reached from separated orgs and spaces?
b) How would credentials be provided for accessing the shared service instance for the individual spaces?
A:
So it is an external service for each of the orgs - you can add it via CUPS to both instances within different orgs.
Actual Redis/RabbitMQ service instance could be hosted separately or deployed/bound to interim/service app instance using existing service brokers.
| {
"pile_set_name": "StackExchange"
} |
Q:
For Loop Doesn't Work Without printf
I have two questions.
I wanted to write a function that solves an equation:
int equation() {
int n, r, s;
printf("\nEnter the value of N: ");
scanf("%d", &n);
printf("Enter the value of R: ");
scanf("%d", &r);
printf("Enter the value of S: ");
scanf("%d", &s);
int i, j, k;
int c = 0;
int a[r], b[s];
a[0] = 1;
for (i = 1; i <= r; i++) {
a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));
}
for (j = 1; j <= s; j++) {
b[j] = b[j-1] + sqrt(3 * (j * j * j) + j + 2) / (2 * j);
}
// The last for loop
for (k = 1; k <= n; k++) {
c += a[k] / b[k];
}
printf("Result: %d \n \n", c);
return c;
}
It works well if the last for loop has this line in it:
printf("%d, %d, %d", c, a[k], b[k]);
But if the last one doesn't have the line above, it returns 0. What can be the problem?
Expected values:
n, r, s = 1 the result should be 8.
n, r, s = 2 the result should be 36.
n, r, s = 3 the result should be 204.
I get these values if I write the printf line into the last for.
Also I want to ask another question. When I change this line
a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));
to this
a[i] = a[i-1] * ((((pow(i, 3) * 3) + 5) / (i * i));
it gives me a different result. Why?
Thanks.
A:
Integer arithmetic vs floating point arithmetic.
The first expression ((((i * i * i) * 3) + 5) / (i * i)) uses integer arithmetic, therefore integer division. The second expression ((((pow(i, 3)) * 3) + 5) / (i * i)), because pow() is defined to return a double will be evaluated using floating point arithmetic and therefore will return a floating point value. This value multiplied by integer a[i-1] likely gives a different result, itself converted back to int for storage into a[i].
The second loop refers to b[0] that has not been initialized. The whole computation depends on this value, changing the code before or after that may change the random value that happens to be there in the absence of any initialization and cause the code to appear to work. Initialize b[0] to what it should be and run your tests again. Use my version below with double arithmetic for that.
For your problem, you should use double type instead of int for a[], b[] and c, convert the integers to double with a cast (double) and use floating point constants 3.0 and 5.0 to force floating point computation:
double equation(void) {
int n, r, s;
printf("\nEnter the value of N: ");
if (scanf("%d", &n) != 1) return -1;
printf("Enter the value of R: ");
if (scanf("%d", &r) != 1) return -1;
printf("Enter the value of S: ");
if (scanf("%d", &s) != 1) return -1;
if (r < n || s < n) {
printf("Invalid values, N must be greater or equal to noth R and S\n");
return -1;
}
int i, j, k;
double c = 0.0;
double a[r+1], b[s+1];
a[0] = 1.0;
for (i = 1; i <= r; i++) {
a[i] = a[i-1] * (((((double)i * i * i) * 3.0) + 5.0) /
((double)i * i));
}
b[0] = 1.0; // you forgot to initialize b[0], what should it be?
for (j = 1; j <= s; j++) {
b[j] = b[j-1] + sqrt(3.0 * ((double)j * j * j) + j + 2.0) / (2.0 * j);
}
// The last for loop
for (k = 1; k <= n; k++) {
c += a[k] / b[k];
}
printf("Result: %f\n\n", c);
return c;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a system icon in a UIButton, in a UIToolbar?
I am trying to have a button, in a toolbar, use a system icon, by modifying its appearance in the XCode 7 interface builder. If I do this at the toolbar item level, then this just becomes a regular UIButtonBarItem, removing the button underneath. This means it won't send any press items, from what I can see.
I don't see a way on the UIButton, in the interface builder, to specify a system icon. Ideally I would like to avoid having to do this programmatically. Can anyone suggested a way?
Note, Apple indicates:
iOS provides a lot of small icons—representing common tasks and types
of content—for use in tab bars, toolbars, navigation bars, and Home
screen quick actions. It’s a good idea to use the built-in icons as
much as possible because users already know what they mean.
Unfortunately it is not clear how to leverage them? Some sources indicate using "iOS-Artwork-Extractor", but I would hope there is another way to address this, maybe via some API call?
XCode 7.2.1, targeting iOS.
A:
For the UIButtonBarItem and the subset of icons available there (see table 41-1 in the iOS Human Interface Guidelines), to have it notify the code that it was pressed, then it is simply a question of adding an 'IBAction' function to the class corresponding to the view, for example (Swift):
@IBAction func flashItemActioned (sender: UIButton) {
//
}
and then linking the "sent actions" of the item with the function in the first responder.
For UIButton based implementations I haven't found a solution beyond the "iOS-Artwork-Extractor".
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails - RSpec NoMethodError: undefined method
I'm trying to test a very simple method that takes in 2 numbers and uses them to work out a percentage. However, when I try and run the tests it fails with the following error:
NoMethodError: undefined method `pct' for Scorable:Module
./spec/models/concerns/scorable_spec.rb:328:in `block (2 levels) in
<top (required)>'
./spec/rails_helper.rb:97:in `block (3 levels) in <top (required)>'
./spec/rails_helper.rb:96:in `block (2 levels) in <top (required)>'
-e:1:in `<main>'
Here's my spec file for the module:
require 'rails_helper'
RSpec.describe Scorable, :type => :concern do
it "pct should return 0 if den is 0 or nil" do
expect(Scorable.pct(nil, 15)).to eq(0)
expect(Scorable.pct(0, 15)).to eq(0)
end
end
Here is the pct method located in Scorable.rb:
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
And here's my rspec_helper:
if ENV['ENABLE_COVERAGE']
require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
add_filter "/config/"
add_filter '/vendor/'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Views', 'app/views'
end
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions =
true
end
config.raise_errors_for_deprecations!
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
I'm very new to RSpec and have been puzzling over this one for more than a day. It's definitely pointing to an existing method, as when I use Go To Declaration in RubyMine it opens the method declaration. Can anyone maybe shed some light for me on this one? I'm sure I'm overlooking something incredibly simple.
A:
To make the module method callable with Module.method notation is should be declared in module scope.
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
or:
module Scorable
class << self
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
end
or with Module#module_function:
module Scorable
module_function
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
Note, that the latter declares both module method and normal instance method within this module.
Sidenote: using return in the very last line of the method is considered a code smell and should be avoided:
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
(100.0 * num / den).round
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
The specified argument is outside the range of valid values - C#
I keep getting this error:
The specified argument is outside the range of valid values.
When I run this code in C#:
string sourceURL = "http://192.168.1.253/nphMotionJpeg?Resolution=320x240&Quality=Standard";
byte[] buffer = new byte[200000];
int read, total = 0;
// create HTTP request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sourceURL);
req.Credentials = new NetworkCredential("username", "password");
// get response
WebResponse resp = req.GetResponse();
// get response stream
// Make sure the stream gets closed once we're done with it
using (Stream stream = resp.GetResponseStream())
{
// A larger buffer size would be benefitial, but it's not going
// to make a significant difference.
while ((read = stream.Read(buffer, total, 1000)) != 0)
{
total += read;
}
}
// get bitmap
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));
pictureBox1.Image = bmp;
This line:
while ((read = stream.Read(buffer, total, 1000)) != 0)
Does anybody know what could cause this error or how to fix it?
Thanks in advance
A:
Does anybody know what could cause this error?
I suspect total (or rather, total + 1000) has gone outside the range of the array - you'll get this error if you try to read more than 200K of data.
Personally I'd approach it differently - I'd create a MemoryStream to write to, and a much smaller buffer to read into, always reading as much data as you can, at the start of the buffer - and then copying that many bytes into the stream. Then just rewind the stream (set Position to 0) before loading it as a bitmap.
Or just use Stream.CopyTo if you're using .NET 4 or higher:
Stream output = new MemoryStream();
using (Stream input = resp.GetResponseStream())
{
input.CopyTo(output);
}
output.Position = 0;
Bitmap bmp = (Bitmap) Bitmap.FromStream(output);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any reliable jQuery multiselect that is searchable AND has clickable optgroups?
I've been using the jquery multiselect with the enableClickableOptGroups: true option enabled and its fine. However it does not allow me to search though the values.
Tried Select2. That is searchable and has optgroups, but unfortunately the workarounds if found to make them clickable were laggy and unreliable.
Is there any alternative I didn't see?
A:
In the end found a component that did the job:
https://springstubbe.us/projects/jquery-multiselect/
| {
"pile_set_name": "StackExchange"
} |
Q:
Why won't my Cocos2d test app fire "touchesBegan" events?
In my app delegate, I made sure I have the line:
[glView setMultipleTouchEnabled: YES];
And I have a simple layer meant only to figure out how multi touch works. The .mm file looks like:
#import "TestLayer.h"
@implementation TestLayer
-(id) init
{
if( (self=[super init])) {
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
return self;
}
-(void) draw{
[super draw];
glColor4f(1.0, 0.0, 0.0, 0.35);
glLineWidth(6.0f);
ccDrawCircle(ccp(500,500), 250,CC_DEGREES_TO_RADIANS(360), 60,YES);
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"got some touches");
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"some touches moved.");
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
NSLog(@"a touch began");
return FALSE;
}
@end
When I touch the screen, I always see "a touch began", but no matter how I touch it (simulator or actual device), I never see "some touches moved" or "got some touches".
Is there something further I need to do to make multi touch work?
Specifically, I'm just trying to do basic pinch-to-zoom functionality... I heard there is some sort of gesture recognizer for iPhone...does it work for Coco2ds? Would it work even if I can't get simple multi touch events to fire?
A:
UIGestureRecognizers absolutely work for Cocos2D, I personally used them, you just need to add them to the correct view by using:
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:myGestureRecognizer];
Regarding your touches, I guess you enabled them for the scene you are working in?
scene.isTouchEnabled = YES;
In any case you shouldn't use the addTargetDelegate method, take a look here
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace elements in numpy matrix by taking average of neighboring elements
I am trying to replace values in a numpy matrix which are below a certain threshold with the average of the values of matrix cells which are near the concerned cells (i.e. the ones with values below the threshold.
As an example, let's consider this 10*10 matrix (say matrx):
matrx = np.array([[1,4,9,2,2,5,1,1,9,1],[2,4,3,5,2,2,1,2,1,1],
[3,4,-2,-3,4,2,3,5,1,2],[2,3,-3,-5,3,3,7,8,-4,1],[3,4,2,3,4,2,3,7,3,2],
[1,4,9,3,4,3,3,2,9,4],[2,1,3,5,2,2,3,2,3,3],
[3,6,8,3,7,2,3,5,3,2],[5,-2,-3,5,2,3,7,8,4,3],[4,-2,-3,1,1,2,3,7,3,5]])
print matrx
[[ 1 4 9 2 2 5 1 1 9 1]
[ 2 4 3 5 2 2 1 2 1 1]
[ 3 4 -2 -3 4 2 3 5 1 2]
[ 2 3 -3 -5 3 3 7 8 -4 1]
[ 3 4 2 3 4 2 3 7 3 2]
[ 1 4 9 3 4 3 3 2 9 4]
[ 2 1 3 5 2 2 3 2 3 3]
[ 3 6 8 3 7 2 3 5 3 2]
[ 5 -2 -3 5 2 3 7 8 4 3]
[ 4 -2 -3 1 1 2 3 7 3 5]]
And, let's suppose that the threshold is zero. Presently, I am finding the (2d) locations of the cells where the values are below zero using the following:
threshold = 0
mark_x = np.where( matrx<0 )[0]
mark_y = np.where( matrx<0 )[1]
Below, is a picture of the aforesaid matrix.
In my work, cells whose values are below the threshold mostly occur in blocks (as one can see in the matrix). At present, I am replacing all the cells where the values are below the threshold with the mean of the matrix (matrx).
But, I would like do better and replace the values of elements which are below the threshold with the mean values of good neighboring elements adjoining the concerned cells. Here, "good" neighboring cells will be those neighboring cells whose values are above the threshold. I am a bit flexible with the selection of sizes of neighboring cells around cells which are below the threshold (the size of the neighboring cell will be the same for each cell which is below the threshold.)
The picture below gives a pictorial idea of what I want to achieve. In the picture given below, the red boundaries around each blob with values below the threshold, represent nearest neighbors. Inside each of these bounded boxes, cells with red tick marks are the ones whose average we will like to consider while replacing the values of the cells whose values are below the threshold.
When we find cells with values below the threshold, we are expecting to see blobs of unequal sizes; and also blobs which are near the boundary.
In Python, what is the best way to achieve this desired aim? I will very much appreciate any answer.
A:
This might work, however, you may prefer to keep the original matrix and make changes to a copy to make it more precise:
for x, y in zip(mark_x, mark_y) :
slice = matrx[max(0, x-2):x+2, max(0,y-2):y+2] # assuming you want 5x5 square
matrx[x,y] = np.mean([i for i in slice.flatten() if i > 0]) # threshold is 0
gives the result:
array([[1, 4, 9, 2, 2, 5, 1, 1, 9, 1],
[2, 4, 3, 5, 2, 2, 1, 2, 1, 1],
[3, 4, 3, 3, 4, 2, 3, 5, 1, 2],
[2, 3, 3, 3, 3, 3, 7, 8, 3, 1],
[3, 4, 2, 3, 4, 2, 3, 7, 3, 2],
[1, 4, 9, 3, 4, 3, 3, 2, 9, 4],
[2, 1, 3, 5, 2, 2, 3, 2, 3, 3],
[3, 6, 8, 3, 7, 2, 3, 5, 3, 2],
[5, 4, 3, 5, 2, 3, 7, 8, 4, 3],
[4, 4, 4, 1, 1, 2, 3, 7, 3, 5]])
| {
"pile_set_name": "StackExchange"
} |
Q:
installing GoogleMaps module in python
I installed GoogleMaps module via pip
pip install GoogleMaps
above command installed module in /usr/lib/python2.6/site-packages
but when I try load it gives me following error
>>> from googlemaps import GoogleMaps
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "googlemaps.py", line 1, in <module>
from googlemaps import GoogleMaps
ImportError: cannot import name GoogleMaps
Does anyone know why this is happening?
A:
It looks like you have a python file called googlemaps.py?
This is causing a circular import and is repeatedly trying to import GoogleMaps from itself.
Try renaming your file to something else and see if that fixes your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
WebBrowser and BackgroundWorker VB
Can a WebBrowser.DocumentCompleted event executes the BackgroundWorker.RunWorkerAsync() correctly? Because my program doesn't seem to execute the codes under BackgroundWorker.
Code:
Dim Status As String = ""
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If Status = "Enabled" Or Status = "Disabled" Then
Else
Status = WebBrowser1.Document.GetElementById(Account & "Flag").InnerText.ToString
If Status = "Enabled" Then
BackgroundWorker1.RunWorkerAsync()
ElseIf Status = "Disabled" Then
MessageBox.Show("disabled. Contact admin for more information.", "JKLorenzo", MessageBoxButtons.OK, MessageBoxIcon.Information)
Close()
End If
End If
End Sub
A:
I finally made it to work
Here is the code i've used:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.ReportProgress(10)
Dim mysqlconnection As MySqlConnection = New MySqlConnection("server=85.10.205.173;port=3306;username='" & User & "';password='" & Pass & "'")
BackgroundWorker1.ReportProgress(20)
Dim mysqlcommand As MySqlCommand = Nothing
BackgroundWorker1.ReportProgress(30)
Dim mysqldatareader As MySqlDataReader = Nothing
BackgroundWorker1.ReportProgress(40)
mysqlconnection.Open()
BackgroundWorker1.ReportProgress(50)
Using table As DataTable = New DataTable
BackgroundWorker1.ReportProgress(60)
Using command As MySqlCommand = New MySqlCommand("Select * from my.accounts where Username = 'Ray';", mysqlconnection)
BackgroundWorker1.ReportProgress(70)
Using adapter As MySqlDataAdapter = New MySqlDataAdapter(command)
BackgroundWorker1.ReportProgress(80)
adapter.Fill(table)
BackgroundWorker1.ReportProgress(90)
End Using
End Using
For Each row As DataRow In table.Rows
If row("Flag") = "enable" Then
e.Result = "1"
BackgroundWorker1.ReportProgress(100)
Else
e.Result = "0"
BackgroundWorker1.ReportProgress(100)
End If
Next
End Using
mysqlconnection.Close()
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If e.ProgressPercentage = 10 Then
Label1.Text = "Status: Checking"
Label1.ForeColor = Color.FromKnownColor(KnownColor.Highlight)
End If
ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Refresh()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Threading.Thread.Sleep(500)
ProgressBar1.Value = 0
If e.Result = "1" Then
Label1.Text = "Status: Enabled"
Label1.ForeColor = Color.Green
Button1.Enabled = False
Button2.Enabled = True
ElseIf e.Result = "0" Then
Label1.Text = "Status: Disabled"
Label1.ForeColor = Color.OrangeRed
Button1.Enabled = True
Button2.Enabled = False
Else
MessageBox.Show("Unknown output: " & e.Result & " . Closing", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
Close()
End If
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Missing bluetooth applet on 16.04
I once messed up with rfkill command, which cause my bluetooth applet to disappear. Re-enable from system setting doesn't seem to work, it will stay disappear.
This question is similar to Bluetooth indicator disappears on turning off bluetooth, but this workaround appear to be worked for 13.04 user only.
A:
Just solved this issue by reinstalling blueman (bluetooth manager) and some rfkill tweak, now the bluetooth applet should be reappear:
sudo apt-get install --reinstall blueman
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing values of second 's as comma separated just before deletion
I have a table having 2 <td>'s one is having a checkbox and other having a value:
My table as follows:
<table border="1" id="table_sundry">
<tr>
<td><input type="checkbox" id="chk_1"></td>
<td id="val1">a</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_2"></td>
<td id="val2">b</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_3"></td>
<td id="val3">c</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_4"></td>
<td id="val4">d</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_5"></td>
<td id="val3">e</td>
</tr>
</table>
<input type="button" id="btn_del" value="deleterow">
I have a button to delete the rows after checking that particular row.
In delete What I doing is as follows:
$("#btn_del").click(function(){
var checked = $("#table_sundry tr input:checked").size();
var total = $("#table_sundry tr").size()-1;
var rowcnt = document.getElementById("table_sundry").rows.length-1;
var flag = 0;
if($("#chk_"+rowcnt).prop('checked') == true){ //if delete contains last row
$("#table_sundry tr input:checked").parents('tr').remove();
flag =1;
//updateRowCount(flag);
}
else{
$("#table_sundry tr input:checked").parents('tr').remove();
//updateRowCount(flag);
}
});
I need to store the values of second column as comma separated.
Suppose if I delete first and last column I should get a,e in the variable.
Refer fiddle : FIDDLE
A:
JS Fiddle: https://jsfiddle.net/7ft6qtja/2/
HTML
<table border="1" id="table_sundry">
<tr>
<td><input type="checkbox" id="chk_1"></td>
<td id="val1">a</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_2"></td>
<td id="val2">b</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_3"></td>
<td id="val3">c</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_4"></td>
<td id="val4">d</td>
</tr>
<tr>
<td><input type="checkbox" id="chk_5"></td>
<td id="val3">e</td>
</tr>
</table>
<input type="button" id="btn_del" value="deleterow">
JavaScript
var values = [];
var csv = ""; // Store Comma separated values in this variable;
$(document).ready(function(){
$("#btn_del").click(function(){
var checkboxes = $("#table_sundry tr input:checked");
if (checkboxes.length > 0) {
$.each(checkboxes, function (index, checkbox) {
var tr = $(checkbox).closest("tr");
var value = tr.find("td:eq(1)").html();
values.push(value);
csv = values.join();
tr.remove();
});
alert(csv);
}
else {
alert("Please select an item.");
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Google sheets query - Cartesian join between two ranges
How can we achieve the following join between two ranges on Google Spreadsheet using the query function?
Range 1
Model Style
Nissan Coupe
Nissan Truck
Honda Sedan
Honda Hatchback
Toyata Truck
Honda Coupe
Range 2
Style Engine
Coupe 1200 cc
Coupe 1500 cc
Sedan 1000 cc
Truck 2000 cc
Sedan 1800 cc
Hatchback 800 cc
Output
Model Style Engine
Nissan Coupe 1200 cc
Nissan Coupe 1500 cc
Honda Sedan 1000 cc
Nissan Truck 2000 cc
Honda Sedan 1800 cc
Honda Hatchback 800 cc
Honda Coupe 1200 cc
Honda Coupe 1500 cc
Toyata Truck 2000 cc
A:
The Data Visualization Language, which we use via the query command, does not support joins of any kind. The desired result can be obtained with a custom function.
Its format is =cartesianJoin(arr1, arr2, col1, col2) where the first two arguments are ranges to be joined, and the other two are column numbers (relative to the range) on which the join is to be made. For example, in your case the first array could be in A2:B8 and the second in D2:E8. Then the formula would be
=cartesianJoin(A2:B8, D2:E8, 2, 1)
indicating that we join by the second column of first array (B) being equal to the first column of the second array (D).
function cartesianJoin(arr1, arr2, col1, col2) {
var output = [];
for (var i = 0; i < arr1.length; i++) {
var r1 = arr1[i];
var matching = arr2.filter(function(r2) {
return r1[col1 - 1] === r2[col2 - 1];
}).map(function(r2) {
var copyr2 = r2.slice(0);
copyr2.splice(col2 - 1, 1);
return r1.concat(copyr2);
});
output = output.concat(matching);
}
return output;
}
Logic: for each row of first array (r1), filter the second array by the equality requirement, then concatenate each of the matching rows to r1, first removing the matched column so it does not appear twice.
Screenshot:
| {
"pile_set_name": "StackExchange"
} |
Q:
Set Cruise Controls build number to start at a certain value for renamed project?
I have a project that uses CruiseControl.NET, and as a versioning scheme we have 3.0.[ccnetbuild].[svnrevision]. CCNetBuild is the internal build number cruise control uses to keep track of how many builds of a project it has done. Now I have had to rename one of the CCNet project (rename in CCNets config file) and the [build] number now starts again from zero. Is there any way I can set it to start at a particular value (the last value I had with the original name) and make it increment from there? It must be stored in some internal CCNet database or something like that.
A:
You need to edit the .state file of the CCNET project. Either you explicitly set its path using the State Manager Block in CCNET configuration or - if omitted - you'll find it in CCNET installation directory.
| {
"pile_set_name": "StackExchange"
} |
Q:
output and input dictionary
Hi I want to save a dictionary to csv, then input it. However on both output and input, I met some issues.
For output I tried: (D_FINAL is the dictionary)
f = open("D_FINAL.csv", "w")
writer = csv.writer(f)
for k, v in D_FINAL.items():
writer.writerow([k, v])
f.close
It works fine but when I want to open the csv, it says the file is locked from editting
For input I tried
import csv
dict = {}
r = open('D_FINAL3.csv', 'r')
for k, v in csv.reader(r):
dict[k] = v
r.close()
but I got error
ValueError Traceback (most recent call last)
<ipython-input-92-d3e2b3081317> in <module>()
3 dict = {}
4 r = open('D_FINAL2.csv', 'r')
----> 5 for k, v in csv.reader(r):
6 dict[k] = v
7
ValueError: not enough values to unpack
(expected 2, got 0)
What's the correct way to do these ?
A:
on windows (python 3), if you don't use open("D_FINAL.csv", "w",newline=""), the resulting csv file has extra blank lines (because of the extra carriage return char inserted making end of lines like \r\r\n).
Unfortunately, those double carriage return chars are read back not the same way: it generates a blank row after each valid data row. So unpacking fails because there aren't any elements in the row.
More on this nasty side-effect: CSV file written with Python has blank lines between each row
So when reading, you get a blank line.
Just do (and upgrade your python skills a notch):
with open("D_FINAL.csv", "w", newline="") as f: # python 2: use: "wb"
writer = csv.writer(f)
writer.writerows(D_FINAL.items())
(write in one go with writerows, use a with block so you don't miss the call to close and the file isn't locked anymore)
Note that json module is best suited to read & write dictionaries (if your need is serialization)
Aside: it's better to read back using a better technique too (it seems that the newline thingy isn't really necessary when reading):
with open("D_FINAL.csv", "r", newline="") as f: # python 2: use: "rb"
writer = csv.reader(f)
output = {k:v for k,v in writer} # unpack+dictionary comprehension
| {
"pile_set_name": "StackExchange"
} |
Q:
Alter each for-loop in a function to have error handling executed automatically after each failed iteration
This question follows from catch errors within generator and continue afterwards
I have about 50 similar (but different) functions which try to extract URLs and such from websites. Because each website is different, each function is different and because websites tend to change over time this code is messy and cannot be trusted.
Here's a simplified sample, or look at the sample in the first question
def _get_units(self):
for list1 in self.get_list1():
for list2 in self.get_list2(list1):
for unit in list2:
yield unit
What I want to do with this function is essentially change the behavior to match this:
def _get_units(self):
for list1 in self.get_list1():
try:
for list2 in self.get_list2(list1):
try:
for unit in list2:
try:
yield unit
except Exception as e:
log_exception(e)
except Exception as e:
log_exception(e)
except Exception as e:
log_exception(e)
In short, I want to turn this
for x in list:
do_stuff(x)
to this:
for x in list:
try:
do_stuff(x)
except Exception as e:
log_exception(e)
for each for in my functions.
But I want to do it in a pythonic way. I don't want try:except blocks scattered all over the 50 functions I need to alter. Is this possible? If so, how can I do it in the most DRY way, and can I do this with the error handling in one place?
UPDATE: this question formerly included a continue statement along with the logging, but as mgilson pointed out, this isn't necessary.
UPDATE 2 with georgesl's answer the function becomes as follows:
from contextlib import contextmanager
@contextmanager
def ErrorManaged():
try:
yield
except Exception as e:
log_exception(e)
def _get_units(self):
for list1 in self.get_list1():
with ErrorManaged():
for list2 in self.get_list2(list1):
with ErrorManaged():
for unit in list2:
with ErrorManaged():
yield unit
which is a lot cleaner indeed. though, a mere decorator would be even better. can anyone tell me if this is possible? if not, i'll accept georgesl's answer.
A:
You might want to use decorators or better, the context manager :
from contextlib import contextmanager
def HandleError(func):
def wrapped(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception:
print "Bug on node #", args[0]
return wrapped
@contextmanager
def ErrorManaged():
try:
yield
except Exception:
print "Oh noes, the loop crashed"
@HandleError
def do_something(x):
print x
if x==5:
raise('Boom !')
with ErrorManaged():
for x in range(10):
do_something(x)
if x == 7 :
raise('aaaah !')
A:
I gave this some more thought, the only solution to really suit my needs seems to be to modify the code itself. So here goes:
from contextlib import contextmanager
import inspect
@contextmanager
def ErrorManaged():
try:
yield
except Exception as e:
print e
def get_units():
for x in range(-5,5):
print(x)
if x % 3 == 0:
raise Exception("x nope")
for y in range(-5,5):
print("\t{}".format(y))
if y % 3 == 0:
raise Exception("y nope")
for z in range(-5,5):
print("\t\t{}".format(z))
if z % 3 == 0:
raise Exception("z nope")
import re
def modify_get_units(get_units):
lines = inspect.getsourcelines(get_units)[0]
add = "with ErrorManaged():\n"
new = []
tabsize = 0
for c in lines[1]:
if c == " ":
tabsize += 1
else:
break
count = 0
for line in lines:
new.append(" " * tabsize * count + line)
m = re.match(r"^(\s+)for\s[()\w,]+\sin\s[^ :\n]+:\n$",line)
if m:
count += 1
new.append(m.group(1) + " " * tabsize * count + add)
return "".join(new)
oldfunc = inspect.getsource(get_units)
newfunc = modify_get_units(get_units)
#printing function bodies to show results
print(oldfunc)
print("\n\n\n")
print(newfunc)
#re-declare get_units
exec newfunc
#execute, but now now
#get_units()
output:
toon@ToonAlfrinkPC ~ $ python test.py
def get_units():
for x in range(-5,5):
print(x)
if x % 3 == 0:
raise Exception("x nope")
for y in range(-5,5):
print("\t{}".format(y))
if y % 3 == 0:
raise Exception("y nope")
for z in range(-5,5):
print("\t\t{}".format(z))
if z % 3 == 0:
raise Exception("z nope")
def get_units():
for x in range(-5,5):
with ErrorManaged():
print(x)
if x % 3 == 0:
raise Exception("x nope")
for y in range(-5,5):
with ErrorManaged():
print("\t{}".format(y))
if y % 3 == 0:
raise Exception("y nope")
for z in range(-5,5):
with ErrorManaged():
print("\t\t{}".format(z))
if z % 3 == 0:
raise Exception("z nope")
Thanks for helping me get there!
| {
"pile_set_name": "StackExchange"
} |
Q:
What to use as session id in application insights
I am considering adding some support in our app-backend to enable users and sessions to enable the analytics features in application insights.
As far as my understanding goes, i need to annotate the telemetry I send with user id and a session id.
For user id we have an id that is static for a user over time.
For the session id i am a bit puzzled on what to do.
Will I, in the Azure portal, benefit from just inserting the user Id in the telemetry, without a sessionId
What can i use as a sessionkey that is meaningfull? The backend is used by some apps that can not easily be modified
A:
Application Insights have fields for three different identifiers. Expectations:
UserId - user identifier, either stable id [never changes for this user] or at least same id across many sessions
SessionId - session identifier [think about one browser session]
OperationId - operation identifier [think about one operation, such as "login" or "buy a car"], multiple operations per session
If data in these identifiers follow above guidelines - this will result in the best user experience.
On another side, if, for instance, all three identifiers are initialized with UserId, then Transaction view will become unusable since it will show everything what user did ever and individual transactions (such as "buy a car") will be very hard to troubleshoot using this particular view.
| {
"pile_set_name": "StackExchange"
} |
Q:
Switching Differential Equation in NDSolve
I am trying to solve the following system of differential equations using NDSolve:
$\dot{z}_t=.5(1-z_t)$
$\dot{y}_t=.05y_t+z_t-x_t$
subject to the following constraint:
$-y_t-z_t\le0$
where $z_t$ essentially follows a predetermined path, and $x_t=0.75$ until the constraint becomes binding, then dynamically adjusts to keep $y_t$ at the level constrained by $z_t$.
I am using the following code:
zdot=.5*(1-z[t]);
ydot=.05*y[t]+z[t]-x[t];
xdotbind=D[Solve[-ydot-zdot==0,x[t]][[1,1,2]],t];
xdot=Piecewise[{{0,bind==0},{xdotbind,bind==1}}];
bind=0;
sol=NDSolve[{x'[t]==xdot,y'[t]==ydot,z'[t]==zdot,x[0]==.75,y[0]==0,z[0]==0.1,WhenEvent[-y[t]-z[t]==0,{x[t]->.05*y[t]+z[t],bind=1,"RemoveEvent"}]},{x,y,z},{t,0,25}];
Grid[{{Plot[Evaluate[x[t]/.sol],{t,0,2.5},PlotRange->All,AxesLabel->{"t","x"}],Plot[{Evaluate[y[t]/.sol],-Evaluate[z[t]/.sol]},{t,0,2.5},PlotRange->All,AxesLabel->{"t","y"},PlotStyle->{Automatic,{Gray,Dashed}}],Plot[Evaluate[z[t]/.sol],{t,0,25},PlotRange->All,AxesLabel->{"t","z"}]}}]
which generates the following:
Basically, I am using a WhenEvent trigger to change the value of $x_t$ once $y_t$ hits the constraint (represented by the dotted line). This works fine, but then I try to force NDSolve to switch the expression used for $\dot{x}_t$ to the one that would make $y_t$ follow the constraint path going forward by using a Piecewise function, but this doesn't seem to work for some reason.
Alternatively, I've been able to achieve what I want using "StopIntegration" in a WhenEvent trigger to shut down NDSolve when it hits the constraint, then using the values of the state variables at this point as the initial values in a second NDSolve with the appropriate constraint expression for $\dot{x}_t$. However, I then have to stitch together the two sets of results from the two NDSolve commands, which is a bit cumbersome, so I'm hoping there's a way to do this within a single NDSolve.
Any ideas?
A:
Changing parameter values during integration works better with DiscreteVariables.
But I think the problem with OP's code, in the question and the OP's answer, has more to do with Mathematica numerics.
My solution
Clear[bind];
zdot = 1/2 (1 - z[t]);
ydot = 1/20*y[t] + z[t] - x[t];
xdotbind =
D[Solve[-ydot - zdot == 0, x[t]][[1, 1, 2]], t] /. {y'[t] -> ydot,
z'[t] -> zdot};
xdot = Piecewise[{{0, bind[t] == 0}, {xdotbind, bind[t] == 1}}];
{sol, {data}} = Reap@NDSolve[{
x'[t] == xdot, y'[t] == ydot, z'[t] == zdot,
bind[0] == 0, x[0] == 3/4, y[0] == 0, z[0] == 1/10,
WhenEvent[-y[t] - z[t] == 0,
{x[t] -> 1/20*y[t] + z[t] + 1/2*(1 - z[t]), bind[t] -> 1,
"RemoveEvent"}]},
{x, y, z}, {t, 0, 5},
DiscreteVariables -> {bind \[Element] {0, 1}},
StepMonitor :>
Sow[{bind[t], t, {x[t], y[t], z[t]}, {xdot, ydot, -zdot}}]];
Grid[{{Plot[Evaluate[x[t] /. sol], {t, 0, 5}, PlotRange -> All,
AxesLabel -> {"t", "x"}],
Plot[{Evaluate[y[t] /. sol], Evaluate[-z[t] /. sol]}, {t, 0, 5},
PlotRange -> All, AxesLabel -> {"t", "y"},
PlotStyle -> {Automatic, {Gray, Dashed}}],
Plot[Evaluate[z[t] /. sol], {t, 0, 5}, PlotRange -> All,
AxesLabel -> {"t", "z"}]}}]
Numerical issues
The OP puts a finger on the problem with the observation in the OP's answer:
if I change the region condition in the definition of xdot from y[t] > -z[t] to y[t]+z[t] > 0 (which seems equivalent to me...)
The inequalities are mathematically equivalent but not numerically equivalent. This can be demonstrated by the following:
1. + $MachineEpsilon > 1.
(* False *)
(1. + $MachineEpsilon) - 1. > 0
(* True *)
This is because there is a tolerance in comparing numbers. If they are approximately equal, as defined by Internal`$EqualTolerance, then strict comparison will return False.
Block[{Internal`$EqualTolerance = 0.},
1. + $MachineEpsilon > 1.
]
(* True *)
The documentation page for Less points out another problem,
rounding error:
0.00001 < 2.00006 - 2.00005
(* True *)
0.00001 + 2.00005 == 2.00006
(* True *)
The problem is almost bound to arise in the OP's answer with the variant
xdot = Piecewise[{{0, y[t] + z[t] > 0}}, xdotbind]
because NDSolve is trying to tiptoe along the path where y[t] == z[t].
If we look at the two forms of the condition in xdot for the OP's first solution (the correct one), we can see that the comparison is an issue:
grid = x["Grid"] /. sol // Flatten; (* the times of the steps *)
x'["ValuesOnGrid"] /. sol // First; (* values of the derivative x' *)
Split[Flatten@Position[%, 0.], (* positions where x'[t] == 0 *)
Subtract[##] == -1 &] /. {a_Integer, ___, b_Integer} :> a ;; b
(* {1 ;; 38} *)
y[grid[[38 ;; -1]]] > -z[grid[[38 ;; -1]]] /. sol // First // Thread
y[grid[[38 ;; -1]]] + z[grid[[38 ;; -1]]] > 0 /. sol // First // Thread
(* y[t] > -z[t] from the correct solution
{True, False, False, False, False, False, False, False, False, False,
... 30 False's ...
False, False, False, False, False, False, False}
y[t] + z[t] > 0 from the alternative
{True, False, False, False, False, False, False, False, False, True,
... 33 True's ...
True, True, True, True}
*)
The first True to False change is where the jump in x[t] occurs around t == 0.73. In the correct solution, the condition is False at all subsequent steps, which means the x'[t] == xdotbind and the solution has y track z. The alternative condition is False for a few steps and then is True. This would set x'[t] == 0 and y would stop tracking z. This is what happens when NDSolve is run with the alternative condition defining xdot.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linear Layout:How to fill the whole width of screen?
I've following layout file, which creates linear layout inside the relative layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#eeeeee">
<LinearLayout // I want this to fill the whole width of screen.
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="50px"
android:background="#666666"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/newEvent"
android:hint="Enter the Name of Event"
android:layout_below="@+id/textView2"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Location"
android:id="@+id/pickerButton"
android:layout_alignTop="@+id/newEvent"
android:layout_toEndOf="@+id/newEvent" />
</LinearLayout>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Remainder"
android:id="@+id/submit"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View All"
android:id="@+id/view"
android:layout_below="@+id/submit"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Location Will Appear Here"
android:id="@+id/textView4"
android:layout_above="@+id/submit"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp" />
</RelativeLayout>
Using this code, I got following layout:
But There are spaces left in left, right and top of the gray color (linear-Layout). I don't want these space. I want to fill the whole width with gray color. What changes should I make in my xml to achieve this?
Thanks in advance!
EDIT:
Thanks for the answers. But after resolving this, I'm getting my text box and button at the bottom of the gray box, as shown in following figure:
For this, I've already tried "android:gravity="center_horizontal" , "android:gravity="center_vertical" and "android:gravity="center". I've also tried padding-bottom.
But this is not working.
A:
Remove
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
lines from parent RelativeLayout
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="50px"
android:background="#666666"
android:orientation="horizontal"
android:gravity="center_vertical"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/newEvent"
android:hint="Enter the Name of Event"
android:layout_gravity="center_vertical" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Location"
android:id="@+id/pickerButton"
android:layout_gravity="center_vertical" />
</LinearLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
factory floor simulation
I would like to create a simulation of a factory floor, and I am looking for ideas on how to do this. My thoughts so far are:
• A factory is a made up of a bunch of processes, some of these processes are in series and some are in parallel. Each process would communicate with it's upstream and downstream and parallel neighbors to let them know of it’s through put
• Each process would it's own basic attributes like maximum throughput, cost of maintenance as a result of through put
Obviously I have not fully thought this out, but I was hoping somebody might be able to give me a few ideas or perhaps a link to an on line resource
update:
This project is only for my own entertainment, and perhaps learn a little bit alnong the way. I am not employed as a programmer, programming is just a hobby for me. I have decided to write it in C#.
A:
Simulating an entire factory accurately is a big job.
Firstly you need to figure out: why are you making the simulation? Who is it for? What value will it give them? What parts of the simulation are interesting? How accurate does it need to be? What parts of the process don't need to be simulated accurately?
To figure out the answers to these questions, you will need to talk to whoever it is that wants the simulation written.
Once you have figured out what to simulate, then you need to figure out how to simulate it. You need some models and some parameters for those models. You can maybe get some actual figures from real production and try to derive models from the figures. The models could be a simple linear relationship between an input and an output, a more complex relationship, and perhaps even a stochastic (random) effect. If you don't have access to real data, then you'll have to make guesses in your model, but this will never be as good so try to get real data wherever possible.
You might also want to consider to probabilities of components breaking down, and what affect that might have. What about the workers going on strike? Unavailability of raw materials? Wear and tear on the machinery causing progressively lower output over time? Again you might not want to consider these details, it depends on what the customer wants.
If your simulation involves random events, you might want to run it many times and get an average outcome, for example using a Monte Carlo simulation.
To give a better answer, we need to know more about what you need to simulate and what you want to achieve.
A:
Since your customer is yourself, you'll need to decide the answer to all of the questions that Mark Byers asked. However, I'll give you some suggestions and hopefully they'll give you a start.
Let's assume your factory takes a few different parts and assembles them into just one finished product. A flowchart of the assembly process might look like this:
Factory Flowchart http://img62.imageshack.us/img62/863/factoryflowchart.jpg
For the first diamond, where widgets A and B are assembled, assume it takes on average 30 seconds to complete this step. We'll assume the actual time it takes the two widgets to be assembled is distributed normally, with mean 30 s and variance 5 s. For the second diamond, assume it also takes on average 30 seconds, but most of the time it doesn't take nearly that long, and other times it takes a lot longer. This is well approximated by an exponential distribution, with 30 s as the rate parameter, often represented in equations by a lambda.
For the first process, compute the time to assemble widgets A and B as:
timeA = randn(mean, sqrt(variance)); // Assuming C# has a function for a normally
// distributed random number with mean and
// sigma as inputs
For the second process, compute the time to add widget C to the assembly as:
timeB = rand()/lambda; // Assuming C# has a function for a uniformly distributed
// random number
Now your total assembly time for each iGadget will be timeA + timeB + waitingTime. At each assembly point, store a queue of widgets waiting to be assembled. If the second assembly point is a bottleneck, it's queue will fill up. You can enforce a maximum size for its queue, and hold things further up stream when that max size is reached. If an item is in a queue, it's assembly time is increased by all of the iGadgets ahead of it in the assembly line. I'll leave it up to you to figure out how to code that up, and you can run lots of trials to see what the total assembly time will be, on average. What does the resultant distribution look like?
Ways to "spice this up":
Require 3 B widgets for every A widget. Play around with inventory. Replenish inventory at random intervals.
Add a quality assurance check (exponential distribution is good to use here), and reject some of the finished iGadgets. I suggest using a low rejection rate.
Try using different probability distributions than those I've suggested. See how they affect your simulation. Always try to figure out how the input parameters to the probability distributions would map into real world values.
You can do a lot with this simple simulation. The next step would be to generalize your code so that you can have an arbitrary number of widgets and assembly steps. This is not quite so easy. There is an entire field of applied math called operations research that is dedicated to this type of simulation and analysis.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby WIN32OLE excel chart seriescollection values
I am trying to change the values of an Excel (actually PowerPoint) chart.
I tried doing this by passing an array but it doesn't seem to work.
Although as mentioned on this page it should work...: http://msdn.microsoft.com/en-us/library/office/ff746833.aspx
So how does my code looks like at the moment:
require 'win32ole'
mspp_app = WIN32OLE.new("Powerpoint.Application")
mspp = mspp_app.Presentations.Open(pathToFile)
slide = mspp.Slides(1)
shapes = slide.shapes
chartshape = shapes(3) #the chart happens to be shape n°3
chart = chartshape.chart
# now get the seriescollection
sc = chart.SeriesCollection
sc3 = sc.Item(3)
values = sc3.values #returns the current values as an array example: [1.0, 1.0, 5.0, 2.0]
# now set the values
sc3.values = [2.0, 2.0, 5.0, 1.0] # returns no error
# see if the values are set
values = sc3.values # returns an empty Array []
Anyone tried this before?
A:
For manipulating the diagram data you have to change the underlying worksheet:
ws = myChart.Chart.ChartData.Workbook.Worksheets(1)
ws.Range("A2").Value = "Coffee"
ws.Range("A3").Value = "Soda"
ws.Range("A4").Value = "Tea"
ws.Range("A5").Value = "Water"
ws.Range("B1").Value = "Amount" # used as label for legend
ws.Range("B2").Value = "1000"
ws.Range("B3").Value = "2500"
ws.Range("B4").Value = "4000"
ws.Range("B5").Value = "3000"
It is important to change the SourceData-Range if dimension has changed. Take care of the different notion known from Excel: "=Tabelle1!A1:B5" instead of "A1:B5".
For english office version change "Tabelle1" to "Sheet1"
myChart.Chart.SetSourceData("=Tabelle1!A1:B5")
myChart.Chart.ChartData.Workbook.Close
Don't forget to close the worksheet afterwards.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where was Hermione's time turner after the Prisoner of Azkaban?
In Harry Potter, Hermione's Time turner saves the day in the Prisoner of Azkaban.
But then we don't see it in the rest of the series.
Where did it go?
A:
She returned it.
Hermione Granger got one from Professor McGonagall to attend more classes in her third year than time would allow. Since McGonagall made her swear to not tell anyone about it, she did not mention it to Harry Potter or Ron Weasley until the end of the school year, when she and Harry used it to travel back in time and save Sirius Black and Buckbeak from certain death.
They took special permission from the Ministry of Magic to allow Hermione to use one, but her academic record ensured that permission was given.
Hermione found her third year stressful with the extra class load, and therefore dropped Divination and Muggle Studies. So, she was back to normal schedule and she returned her Time-Turner.
| {
"pile_set_name": "StackExchange"
} |
Q:
Apply multiple filters based on user input (VBA)
I want to ask the user:
Which field/column to apply filters to?
How many filters are to be applied?
I want to take those n filters as input and apply them to the field of that column.
Refer these images:
Before applying filters,
After applying filters to Column A
Code:
Sub MultiFilter()
Dim colNumber As Integer, numberOfFilters As Integer
Dim filters(10) As String
'Column number to apply filters to
colNumber = InputBox("Enter column number to apply filter to (Column A = 1, B = 2, etc.)")
'Number of filters to apply
numberOfFilters = InputBox("Number of filters to apply to Column " & colNumber)
'Take multiple filters as input
For i = 0 To numberOfFilters - 1
filters(i) = InputBox("Filter #" & i + 1)
Next i
'Apply multiple filters
With ThisWorkbook.Sheets("Sheet1")
.Activate
.Range("A1").Select
.Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFilter
For i = 0 To numberOfFilters - 1
'ISSUE!
Selection.AutoFilter field:=colNumber, Criteria1:=filters(i)
Next i
End With
End Sub
Inputs: 1, 2, A, B
I realise that I'm selecting over Criteria1 multiple times. I've come across the following code:
Range("A1:D10").AutoFilter Field:=1, Criteria1:=Array("A", "B"), Operator:=xlFilterValues
The above code works perfectly, but I have to hard code the values "A" and "B". Is there a way to replace that with n user inputs?
Any help would be appreciated!
EDIT:
Going a step further, how do I take number of columns as a user input and apply multiple filters to multiple columns?
Example:
(Refer images)
Columns: 1, 2 ("Doc Type", "Year")
Filters: 2 in column 1 ("A", "C"), 2 in column 2 ("2016", "2017")
A:
Try replacing all the With bloc by the simple:
'Apply multiple filters
Sheets("Sheet1").Cells.AutoFilter colNumber, Filters, xlFilterValues
Besides, as noted by @Jeeped you need to resize the filters array according to user input
Dim filters() As String ' <--- dont specify size here
....
'Number of filters to apply
numberOfFilters = InputBox("Number of filters to apply to Column " & colNumber)
Redim filters(0 to numberOfFilters - 1) As String '<-- resize according to user input
| {
"pile_set_name": "StackExchange"
} |
Q:
I am having problems running the command bundle exec guard init rspec
I am going through the railstutorial.org book.
I am receiving this error:
$ bundle exec guard init rspec
c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard/interactor.rb:1:in
require': cannot load such file -- pry (LoadError)
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard/inter
actor.rb:1:in'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard/dsl.r
b:2:in require'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard/dsl.r
b:2:in'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard.rb:6:
in require'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/lib/guard.rb:6:
in'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/bin/guard:3:in
require'
from c:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/guard-2.0.3/bin/guard:3:in
'
from c:/Ruby200-x64/bin/guard:23:in load'
from c:/Ruby200-x64/bin/guard:23:in'
My gem file is:
1. source 'https://rubygems.org'
ruby '2.0.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0'
group :development, :test do
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
gem 'rspec-rails', '2.13.1'
gem 'guard-rspec', '2.0.0'
gem 'guard', '2.0.3'
end
group :test do
gem 'selenium-webdriver', '2.35.1'
gem 'capybara', '2.1.0'
gem 'rb-notifu', '0.0.4'
gem 'win32console', '1.3.2'
gem 'wdm', '0.1.0'
end
# Use SCSS for stylesheets
gem 'sass-rails', '4.0.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '2.1.1'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks', '1.1.1'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '1.0.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '0.3.20', require: false
end
group :production do
gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
Am I missing something? Thanks for any help!
A:
Looks like guard requires pry be installed.
gem install pry
A:
Explicitly add pry or similar to your Gemfile. I use pry-nav which will automatically bundle pry when bundle install is run.
# Gemfile
gem 'pry-nav', group: [:development, :test]
Cite:
http://pryrepl.org/
https://github.com/nixme/pry-nav
https://github.com/nixme/pry-debugger
https://github.com/rweng/pry-rails
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery validate .resetForm() not clearing form, validation messages firing on manual reset
Ive got several buttons, passing different params to the same function. That function will eventually do lots of client side processing but first it needs to validate. Validation is working fine, but upon success, I need to reset the form. In my fiddle below, you can see that the .resetForm() call does nothing, and if I manually clear the field, it throws validation errors like I was trying to submit.
see my fiddle: http://jsfiddle.net/uT6pw/10/
html:
<form id="frm" method="post" onsubmit="return false;">
<input type="text" id="FName" class="required">
<span class="field-validation-valid" data-valmsg-for="FName" data-valmsg-replace="true"></span>
<button id="btn1" onclick="addContact('1')">1</button>
<button id="btn2" onclick="addContact('2')">2</button>
<button id="btn3" onclick="addContact('3')">3</button>
</form>
javascript:
function addContact(num){
var v = $("#frm").validate()
if (v.form())
{
v.resetForm();
//$("#frm").validate().resetForm()
$("#FName").val('');
}
}
Thanks!
A:
I have not heard about resetForm, try this:
form.reset();
Update: You have button tags that post form, this is the reason form gets validated when you click them. Instead change <button> to <input type="button"/>
See fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
send key strokes to a window in vb.net while it is still minimized
I used to know vb6 and I need to make a quick application. I hope someone can help me with how to send keys to a minimized window in vb.net
thanks
A:
Normally you can send keys with the SendMessage API function, but I'm not sure if it would be affected in any way by the window being minimized, I don't think so but I haven't tried.
To use a Windows API function from VB.Net you need to use PInvoke to call it, you can find information about how to do that on this page.
The MSDN page for SendMessage might also be useful for information about how it works.
Btw, you probably want to use the WM_CHAR message which is 0x0102.
| {
"pile_set_name": "StackExchange"
} |
Q:
returning the ArrayList cast to List vs no casting
What is the difference, if any, between the two:
@ModelAttribute(value = "attendanceStatuses")
public List<Code> getAttendanceStatusCodes() {
List<Code> attendanceStatuses= new ArrayList<Code>(
cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
return attendanceStatuses;
}
and
@ModelAttribute(value = "attendanceStatuses")
public List<Code> getAttendanceStatusCodes() {
return cacheService.getValidCodesOfCodeGroup(CODE_GROUP);
}
The cacheService method is:
List<Code> getValidCodesOfCodeGroup(CodeGroupName codeGroupName);
A:
The first snippet returns a copy of the List returned by cacheService.getValidCodesOfCodeGroup(CODE_GROUP):
new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP))
The second snippet does not - it simply returns cacheService.getValidCodesOfCodeGroup(CODE_GROUP).
There is no casting in any of these snippets though.
Note that assigning the List to a local variable before returning it makes no difference. You can change the first snippet to:
public List<Code> getAttendanceStatusCodes() {
return new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
}
without changing the behavior.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reactor: function creating Monos to Flux
Basically, I'm making a queue processor in Spring Boot and want to use Reactor for async. I've made a function needs to loop forever as it's the one that pulls from the queue then marks the item as processed.
here's the blocking version that works Subscribe returns a Mono
while(true) {
manager.Subscribe().block()
}
I'm not sure how to turn this into a Flux I've looked a interval, generate, create, etc. and I can't get anything to work without calling block()
Here's an example of what I've tried
Flux.generate(() -> manager,
(state, sink) -> {
state.Subscribe().block();
sink.next("done");
return state;
}));
Being a newbie to Reactor, I haven't been able to find anything about just loop and processing the Monos synchronously without blocking.
Here's what the Subscribe method does using the AWS Java SDK v2:
public Mono Subscribe() {
return Mono.fromFuture(_client.receiveMessage(ReceiveMessageRequest.builder()
.waitTimeSeconds(10)
.queueUrl(_queueUrl)
.build()))
.filter(x -> x.messages() != null)
.flatMap(x -> Mono.when(x.messages()
.stream()
.map(y -> {
_log.warn(y.body());
return Mono.fromFuture(_client.deleteMessage(DeleteMessageRequest.builder()
.queueUrl(_queueUrl)
.receiptHandle(y.receiptHandle())
.build()));
}).collect(Collectors.toList())));
}
Basically, I'm just polling an SQS queue, deleting the messages then I want to do it again. This is all just exploratory for me.
Thanks!
A:
You need two things: a way to subscribe in a loop and a way to ensure that the Subscribe() method is effectively called on each iteration (because the Future needs to be recreated).
repeat() is a baked in operator that will resubscribe to its source once the source completes. If the source errors, the repeat cycle stops. The simplest variant continues to do so Long.MAX_VALUE times.
The only problem is that in your case the Mono from Subscribe() must be recreated on each iteration.
To do so, you can wrap the Subscribe() call in a defer: it will re-invoke the method each time a new subscription happens, which includes each repeat attempt:
Flux<Stuff> repeated = Mono
.defer(manager::Subscribe)
.repeat();
| {
"pile_set_name": "StackExchange"
} |
Q:
convert BufferedImage to JPG byte array
I'm working on a processing platform for images and my server is currently accepting images as byte arrays from the client using pythons PIL.Image methods. I'm also currently using Java as a front end to grab image frames from video with the FrameGrab utility and returning them as a BufferedImage object. What I don't understand is how I am meant to convert from this buffered image object to a jpg byte array and could use some help.'
I've found an example of writing out a
Here is the base portion of my code.
BufferedImage frame;
for (int i = 1; i < 100; i++) {
try {
frame = AWTUtil.toBufferedImage(FrameGrab.getFrameAtSec(videoFile, i * .3));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (JCodecException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
My python server backend is currently just attempting to save the file with the aforementioned library like so:
img = Image.open(io.BytesIO(data))
img.save('test.jpg')
A:
The easy way:
public static byte[] toJpegBytes(BufferedImage image) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", baos);
return baos.toByteArray();
}
If you want more control over the conversion (compression level, etc) see Setting jpg compression level with ImageIO in Java.
| {
"pile_set_name": "StackExchange"
} |
Q:
MFC App loading dialog from another DLL
We have a very big MFC application that have 16 projects in the solution. Each project is a DLL. Four(4) of these projects are what we call "Network". In each network, there is a dialog that we will call X. This dialog is VERY different in each of the network but the name of the dialog itself is the same in each of the resource.h. In resource.h, they also have the same ID (value).
What happend right now is that when I'm on the network 1 and load the class with the dialog X, it try to use the dialog from Network 2. Since they don't have all the same control in it, it crash in the DoDataExchange trying to find controls that don't exist in the other network.
Does anybody know what can cause this? Attemps at changing the name in the network that do not work didn't change anything since it use the ID...
I always think that the DLL was using it's own resource.h but now it's seems that it's not the case...
Can anybody help?
Thanks
A:
It sounds like you need to call AfxSetResourceHandle to specify the DLL from which to load the dialog.
Edit: Given your description, you'll basically need to call this with the right value every time you display a dialog. Changing things like the DLL load order isn't going to fix the problem -- at any given time, MFC is going to try to use one order for the DLLs/EXE to load all dialogs, and this is modal, so it stays the same until you change it. Given the same resource ID needing to refer to different resources at different times, you need to tell it which one at any given time -- otherwise, you get the first thing it finds with the right ID, and almost no control over which that will be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell v2 :: Load a COM Interop DLL
I have this DataLink DLL on my system - Interop.MSDASC.dll I am trying to load the same from Powershell like this -
[Reflection.Assembly]::LoadFile("C:\Interop.MSDASC.dll") | out-null
But, I get the following error -
Exception calling "LoadFile" with "1" argument(s): "Could not load file or assembly 'Interop.MSDASC.dll' or one of its dependencies. is not a
valid Win32 application. (Exception from HRESULT: 0x800700C1)"
At line:1 char:32
+ [Reflection.Assembly]::LoadFile <<<< ("C:\Interop.MSDASC.dll") | out-null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How do I correctly load this ?
A:
This is a 32 bit COM object and therefore you must load it from a 32 bit instance of PowerShell. To do this on a 64 bit version of Windows you can execute powershell.exe or powershell_ISE.exe in this folder:
%SYSTEMROOT%\SysWow64\windowspowershell\v1.0
And, this is the complete code:
[Reflection.Assembly]::LoadFile("C:\Interop.MSDASC.dll")
$dataLinkInstance = new-object MSDASC.DataLinksClass
$dataLinkInstance.WriteStringToStorage("C:\\FrmPowershell.udl", "Provider=SQLOLEDB.1;", 2)
A:
I've just downloaded it from http://datadictionary.codeplex.com/ and load assembly in the same way you use and no issue come:
[System.Reflection.Assembly]::LoadFile( "c:\Program Files\DataDictionaryCreator\Interop.MSDASC.dll")
GAC Version Location
--- ------- --------
False v2.0.50727 c:\Program Files\DataDictionaryCreator\Interop.MSDASC.dll
Are you maybe on a x64 operative system?
if yes read here http://datadictionary.codeplex.com/workitem/28807
| {
"pile_set_name": "StackExchange"
} |
Q:
CF query remove empty string results for total sum
I am trying to fix my query so that my total sum column will equal the correct number. I tried changing this line <cfset columnSum = ArraySum(allLocCode['locationCount'])> to <cfset columnSum = ArraySum(trim(allLocCode['locationCount']))> But it through an error. I want the empty string like in the picture below to not be counted for the total just like it does not show in the table. Is there another way to pull off this trim for my total column?
<cfset result = {} />
<cftry>
<cfquery datasource="#application.dsn#" name="GetLocationInfo">
SELECT *
FROM cl_checklists
</cfquery>
<cfcatch type="any">
<cfset result.error = CFCATCH.message >
<cfset result.detail = CFCATCH.detail >
</cfcatch>
</cftry>
<table border="1" id="Checklist_Stats">
<thead>
<th><strong>Location</strong></th>
<th><strong>Percent of Total Checklists</strong></th>
<th><strong>Location Total</strong></th>
</thead>
<tbody>
<cfquery name="allLocCode" dbtype="query">
SELECT DISTINCT trans_location, COUNT(*) AS locationCount FROM GetLocationInfo GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfloop query="allLocCode">
<cfset thisLocationName = trim(allLocCode.trans_location) />
<cfquery name="allLocCodeForLocationQry" dbtype="query">
SELECT trans_location,count(*) AS locCntr FROM GetLocationInfo WHERE trans_location='#thisLocationName#' GROUP BY trans_location ORDER BY trans_location
</cfquery>
<cfoutput query="allLocCodeForLocationQry">
<tr>
<td><strong>#thisLocationName#</strong></td>
<td>#NumberFormat((allLocCodeForLocationQry.locCntr/allLocCode.locationCount) * 100, '9.99')#%</td>
<td>#allLocCodeForLocationQry.locCntr#</td>
</tr>
</cfoutput>
</cfloop>
<cfset columnSum = ArraySum(allLocCode['locationCount'])>
<tr>
<td><strong>Total</strong></td>
<td></td>
<td><cfoutput>#columnSum#</cfoutput></td>
<cfdump var="#allLocCode#">
<cfdump var="#allLocCodeForLocationQry#">
<cfdump var="#thisLocationName#">
</tr>
</tbody>
<!--- Total of All Sum of each column --->
</table>
The correct answer should reflect 334 not 340
A:
As requested, here's an answer with the relevant code isolated:
<cfquery name="allLocCode" dbtype="query">
SELECT DISTINCT trans_location, COUNT(*) AS locationCount
FROM GetLocationInfo
WHERE trans_location is not null
GROUP BY trans_location
ORDER BY trans_location
</cfquery>
If you need more help with the percentage stuff I'd recommend starting a new post. I see from your history you already have several threads kind of related to this feature, and as it gets more complicated it'll help to separate everything.
| {
"pile_set_name": "StackExchange"
} |
Q:
File for xi:include does not exist because parser is looking from project root
I currently have an xml resource file that has XML inclusions.
stream = Main.class.getResourceAsStream("resource/Resource.xml");
within the xml file:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.w3.org/1999/xhtml"
xmlns:xi="http://www.w3.org/2001/XInclude">
<element />
<xi:include href="resource/1.xml"/>
</semantics>
However, after parsing Resource.xml, I get an error that the file being included does not exist.
After checking, it seems that the path was concatenated with the root directory of my project, however my problem is that the resource file 1.xml will be inside a jar file later on.
Is it possible to make the DocumentBuilder to load inclusion as a reasource as well?
A:
You need to set a custom EnitityResolver2 on your DocumentBuilder so that you can return the correct InputSource when then xi:include is processed.
final DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new EntityResolver2() {
@Override
public InputSource getExternalSubset(String string, String string1) throws SAXException, IOException {
return null;
}
@Override
public InputSource resolveEntity(String string, String string1, String string2, String string3) throws SAXException, IOException {
final String resourceName = string3;
final InputSource is = new InputSource();
is.setSystemId(resourceName);
is.setByteStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName));
return is;
}
@Override
public InputSource resolveEntity(String string, String string1) throws SAXException, IOException {
return null;
}
});
This will now return an InputSource of the InputStream of the resource as loaded by the classloader. You may need to manipulate the String to get the right path.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested quantifiers in English translation
I'm having a hard time grasping how to express english statements with quantifiers; specifically when trying to show "exactly 1" or "exactly 2" or etc. The introduction of numerous variables throws me off guard.
Let $F(x, y)$ be the statement: "$x$ can fool $y$", where the domain consists
of all people in the world. Use quantiers to express each of these
statements.
Example: "There is exactly one person whom everybody can fool":$$\exists y(\forall xF(x,y)\land(\forall z((\forall wF(w,z))\rightarrow y=z))
$$
I understand: $\exists y(\forall F(x,y))$ which means that there's a person $y$ that everyone can fool. However, this doesn't show that he's the only peron that everyone can fool.
Is there a way "systematic" way to build such expressions? And in this case above,why is it that we bring $z,w$ as variables. I'm not quite understanding what is happening after the first part.
A:
Let's start with the given wff as that seems to be causing difficulty, and work towards its translation into English. Then we've reverse the process!
$$\exists y(\forall xF(x,y)\land(\forall z((\forall wF(w,z))\rightarrow y=z))$$
It can help a great deal to go from logic to English (or vice versa) in stages, via "Loglish" -- that unholy mixture of English and symbolism which we cheerfully use in the classroom! So ....
There is someone $y$ such that $(\forall xF(x,y)\land(\forall z((\forall wF(w,z))\rightarrow y=z))$
can be read
There is someone $y$ such that (everyone $x$ is such that $x$ can fool $y$) and (everyone $z$ is such that ($(\forall wF(w,z))\rightarrow y=z))$
i.e.
There is someone $y$ such that everyone can fool $y$ and everyone $z$ is such that (if everyone $w$ can fool $z$, then $z$ is the same person as $y$).
i.e.
There is someone $y$ such that everyone can fool $y$ and anyone whom everyone can fool is none other than $y$ again.
i.e.
There is someone whom everyone can fool, and no one other then he can be fooled by everyone.
i.e.
There is exactly one person whom everyone can fool.
Read this from top to bottom to translate the formal wff into English.
And now read the same sequence from bottom to top to translate in the other direction!!
Taking things in stages like this helps a great deal when first learning to translate in either direction. There are lots more worked examples of this kind involving nested quantifiers in my Introduction to Formal Logic (Ch. 24), with more exercises and answers online. For practice quickly makes perfect: but it does take a bit of practice to make this all seem as easy as it really is. I recall Paul Teller's A Modern Formal Logic Primer is also quite good on translation (his book, now out of print, is freely available from his website).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to merge many MDBs?
I have many MDBs files with the same structure and two tables each.
Is there any way how to merge this bases in huge one?
I try to use special utilit "Simple MDB Merge", but it doesn't see mdb files on my computer...
A:
You can open up one of the MDBs, and import tables into it from all the other MDBs. If there are really a lot of MDBs and it would be impractical to do it by hand, you can write some VBA code to open each MDB in turn and copy over the tables into your destination MDB. Look up the Access and DAO references for working with databases and tables.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make jquery mobile custom theme generated with themeroller work?
I created a custom jquery theme on jquery themeroller and downloaded it, as the instructions said, I have included the following line on the head part of the html file, should I also tranfer the css file to my server? if so should it be all files?
<meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="themes/MyCustomTheme.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
A:
I will tell you what to do but lets go from the beginning, I will talk from a perspective of jQuery Mobile 1.3.2, same logic works for older versions. To work with jQuery Mobile two files are needed (I am not counting basic jQuery):
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile.structure-1.3.2.min.css" />
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css"></script>
jQuery Mobile CSS files can also be split to theme file and structure file and they can be found in a compressed framework file. What you already know if you want to add new themes over the classic ones you will need to use
If you want to add new themes (or swatches) you will need to use jquery.mobile.theme-1.3.2.css file, import it into theme builder tool and add new themes/swatches. Minimized theme CSS file can't be used here, it must be uncompressed.
When new themes are finished you will be prompted to download zip file containing your new theme file. Now we are ready to implement new themes. First unzip downloaded file and save it somewhere (specially if you intend to modify it later). There you will find 1 HTML file, 2 css files and images directory. Pick a CSS file (anyone will do, but if possible use minified file) and upload it to your server.
Now open your HTML files and add a link to your new CSS file (link that points to your server) and add it after the original CSS file, because new themes also have old ones you will not need to use structure.css file.
But this is not over, from your comment I can see you have already uploaded your file but you cant access it. If your server is Linux/Unix based you will need to give your new CSS file new permissions so they can be accessed from outside.
This line can be used to give it correct permissions (again in case of Linux and Unix):
sudo chmod 666 <filename>
Working example: http://jsfiddle.net/Gajotres/PMrDn/35/
In the end you will only need these files:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<link rel="stylesheet" href="http://socialmedia.mobilevelocity.co.uk/CS408/MySocialStream.min.css" />
<!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the value of $a \in R$ such that $\langle x_n \rangle$ converges to a positive real number when $x_n=\frac{1}{3}\frac{4}{6}...\frac{3n-2}{3n}n^a$
Find the value of $a \in \mathbb{R}$ such that $\langle x_n \rangle$ converges to a positive real number when $x_n=\dfrac{1}{3}\dfrac{4}{6}\cdots\dfrac{3n-2}{3n}n^a$
Here is my approach. First of all, let $a_n=\dfrac{x_n}{n^a}=\dfrac{1}{3}\dfrac{4}{6}\cdots\dfrac{3n-2}{3n}$
Then, let $b_n=\dfrac{2}{4}\dfrac{5}{7}\cdots\dfrac{3n-1}{3n+1}$ and $c_n=\dfrac{3}{5}\dfrac{6}{8}\cdots\dfrac{3n}{3n+2}$
Since $0<a_n<b_n$ and $0<a_n<c_n$
$0<a_n^3<a_nb_nc_n=\dfrac{1}{3}\dfrac{2}{4}\dfrac{3}{5}\cdots\dfrac{3n-2}{3n}\dfrac{3n-1}{3n+1}\dfrac{3n}{3n+2}=\dfrac{2}{(3n+1)(3n+2)}$
Therefore,
$0<x_n^3<\dfrac{2n^{3a}}{(3n+1)(3n+2)}$
So, since the limit of $x_n^3$ should be greater than 0 and less than some positive real number,
the limit of $\dfrac{2n^{3a}}{(3n+1)(3n+2)}$ should be neither 0 nor infinity. Therefore, 3a=2, a=2/3.
Anything wrong? Or better idea?
A:
Expand $$\log(3n-2) - \log(3n) = \log(1 - \frac23 \frac1n) = - \frac23 \frac1n + \frac49 \epsilon_n \frac1{n^2}$$
where $\epsilon_n$ is a bounded sequence.
Then :
$$\log x_n = -\frac23 \sum_{k = 1}^n \frac1k + a \log n + \frac49 \sum_{k = 1}^n \epsilon_k \frac1{k^2}$$
Le last sum converges : $$\big|\epsilon_k \frac1{k^2} \big| \leq (\max_m |\epsilon_m|) \times \frac1{k^2}$$
The harmonic serie satisfies :
$$\sum_{k = 1}^n \frac1k = \log n - \gamma + \epsilon^1_n$$
where $\epsilon^1_n$ converges to $0$.
(to prove that write $\log n = \sum_{k = 1}^n \log(k+1) - \log k = \sum_{k = 1}^n \log(1+\frac1k)$ and expand)
Thus, $\log x_n$ converges to a finite limite iff :
$$-\frac23 \sum_{k = 1}^n \frac1k + a \log n = (a - \frac23) \log n + \frac23 \gamma + \frac23 \epsilon^1_n$$
converges to a finite limit. Finally $a = 2/3$, as you expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get mean of values for each tuple in a list in the format (string, value) in Python
I have a list of tuples like: (A, 1), (B, 2), (C, 3), (A, 9), (B, 8).
How to get the mean of each value referred to the first element of the tuples, not knowing the number of occurences of the first element of tuples?
I want something like:
(A, 5), (B, 5), (C, 3).
A:
Using groupby and itemgetter:
from itertools import groupby
from operator import itemgetter
from statistics import mean
s = [('A', 1), ('B', 2), ('C', 3), ('A', 9), ('B', 8)]
s2 = sorted(s, key=itemgetter(0)) # sorting the tuple based on 0th index
print([(k, int(mean(list(zip(*g))[1]))) for k, g in groupby(s2, itemgetter(0))])
OUTPUT:
[('A', 5), ('B', 5), ('C', 3)]
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing a var from one Extended function to another
I am having trouble passing the url of $.PhotoUpdater.doUpdate(url) to do the doUpdate function.
Firefox returns this error :
useless setTimeout call (missing quotes around argument?)
[Break on this error] timer = setTimeout($.PhotoUpdater.doUpdate(url), 5000)
my code:
$.extend({
PhotoUpdater: {
startUpdate: function(organization, gallery){
url = "/organizations/" + organization + "/media/galleries/" + gallery + "/edit_photo_captions"
timer = setTimeout($.PhotoUpdater.doUpdate(url), 5000)
},
stopUpdate: function(){
clearTimeout(timer);
timer = 0;
},
doUpdate: function(url){
$.ajax({type: "GET", url: url, dataType: "script"});
}
}
});
How I call it:
$.PhotoUpdater.startUpdate("#{@organization.id}", "#{@gallery.id}");
A:
You need to pass a function into window.setTimeout, not the result of calling a function:
startUpdate: function(organization, gallery){
url = "/organizations/" + organization + "/media/galleries/" + gallery + "/edit_photo_captions";
timer = window.setTimeout(function() {
$.PhotoUpdater.doUpdate(url)
}, 5000);
},
| {
"pile_set_name": "StackExchange"
} |
Q:
compare 2 parameters with 1 coloumn while passing parameters in SQL Server 2008
i have to pass two parameters (month var-char(2),year var char(4)),but these two parameters pointing towards one coloumn 'Myear'(values will be like this '03/14') now after passing parameters then i should compare with the coloumn 'Myear' then have to get data.kindly please any one help me out..thanks in advance
A:
If Myear is varchar, then try this:
SELECT Myear
FROM TableName
WHERE SUBSTRING(Myear,1,2)=@month
AND SUBSTRING(Myear,4,2)=SUBSTRING(@year,3,2)
Suppose @Myear=03/14 and given parameters are @month=05 and @year=2013, then it will check
if 03=05 AND 14=13.
The syntax of SUBSTRING():
SUBSTRING ( expression ,start , length )
| {
"pile_set_name": "StackExchange"
} |
Q:
Count the list items times of occurances
Let's assume I have the following list
names = ['tan','2','alp','3','tan','4','alp','3','tan','1']
the odd indexed elements are some values and even indexed elements are their number of occurrences (so alp happened 3+3 = 6 times for example)
I am trying to make code to do that.
enter code here
names = ['tan','2','alp','3','tan','4','alp','3','tan','1']
i = 1;
dd = names[0::2]
nn = names[1::2]
ct = [0 for cc in range(len(dd))];
le = len(dd);
for i in range(0, le):
ct[i] = int(nn[i])
for j in range(i+1, le):
if (j < le) and (dd[i] == dd[j]):
ct[i] += int(nn[j]);
del(dd[j])
# del(nn[j])
le -= 1
the output i get for ct is [9, 7, 4, 3, 1]
however it should be [7, 6]
--- 7 for tan and 6 for alp
if i uncommented del(nn[j])
--- i will be equal to le and code will stop
but i should delete the element and the number of occurrences it happened any time after first time (after adding it in ct for sure) so the counting process doesn't get repeated
any idea how to do that?
A:
That's relatively easy - build a lookup map from your odd elements and then sum the matching even values. You can use collections.defaultdict() to make your life easier:
import collections
names = ['tan', '2', 'alp', '3', 'tan', '4', 'alp', '3', 'tan', '1']
lookup_map = collections.defaultdict(int)
for element, value in zip(names[0::2], names[1::2]):
lookup_map[element] += int(value)
print(dict(lookup_map)) # {'tan': 7, 'alp': 6}
If you really need only the values and need to keep the order, you can add an additional step:
result = [lookup_map.pop(element) for element in names[0::2] if element in lookup_map]
print(result) # [7, 6]
If you're after the occurrences / total occurrences per element calculation, you can just apply the sum-total over the whole lookup map:
sum_total = sum(lookup_map.values())
for name in lookup_map:
lookup_map[name] /= sum_total
print(dict(lookup_map)) # {'alp': 0.46153846153846156, 'tan': 0.5384615384615384}
| {
"pile_set_name": "StackExchange"
} |
Q:
web scraping to csv file getting only the first row
I am trying to get a bunch of tables from Wikipedia,this is my code
from urllib import urlopen
from bs4 import BeautifulSoup
import csv
url="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F"
html=urlopen(url)
soup=BeautifulSoup(html,'html.parser')
table=soup.find('table',class_='wikitable sortable')
rows=table.findAll('tr')
csvFile=open("colors.csv",'w+')
writer=csv.writer(csvFile)
try:
for row in rows:
csvRow=[]
for cell in row.findAll(['td','th']):
csvRow.append(cell.get_text().decode("utf-8"))
try:
writer.writerow(csvRow)
except AttributeError:
print "--"
continue
except UnicodeEncodeError:
print "=="
finally:
csvFile.close()
I wanted to write a simple code but i got so many errors so i added some exceptions to fix,but i am still getting only the first row,any help is appreciated
A:
You want to encode, not decode.
from urllib import urlopen
from bs4 import BeautifulSoup
import csv
url="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F"
html=urlopen(url)
soup=BeautifulSoup(html,'html.parser')
table=soup.find('table',class_='wikitable sortable')
rows=table.findAll('tr')
csvFile=open("colors.csv",'w+')
writer=csv.writer(csvFile)
for row in rows:
csvRow=[]
for cell in row.findAll(['td','th']):
csvRow.append(cell.get_text().encode("utf-8"))
print(cell.get_text())
writer.writerow(csvRow)
csvFile.close()
| {
"pile_set_name": "StackExchange"
} |
Q:
Switching tab using conemu GuiMacro Tab() function does not work
I have the following conemu GuiMacro's defined
<F9> - Tab(3)
<F10> - Tab(2)
When I press the keys, I see the previous/next tab being highlighted in the tab bar, but the highlighted tab is not being activated - i.e. keyboard input remains in the current tab. I want F10 & F9 to work like CtrlTab and CtrlShiftTab - i.e. the contents of the new tab should be shown and it should receive keyboard input. How would I do that?
A:
May be the Tab() GuiMacro function does what it's supposed to. Looks like there is a distinction between Tab and Console in ConEmu. To do what I want you need to switch console, not tab.
There is a simple workaround. Simply map F9 and F10 to the Switch next console and Switch previous console User hotkeys.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prove whether $x^{2}+y^{2}+1$ is irreducible over $\mathbb{C}$ or not?
Let's consider a 2-variable polynomial $f(x, y)= x^{2}+y^{2}+1$. It can be established that it's irreducible over $\mathbb{R}$.
For example, if it's irreducible over $\mathbb{R}$ as a polynomial of two variables, then if we assume $y=1$ the polynomial must be irreducible too, whereas $x^{2}+2$ doesn't look so (By the Eisenstein's criterion, for example).
The situation becomes slightly more interesting over $\mathbb{C}$. How to prove, in particular, that the $x^{2}+y^{2}+1$ is irreducible over $\mathbb{C}$ or not and which technique may be applied in order to cope with such kind of problems in general cases?
Any piece of advice would be much appreciated.
A:
Consider the ring $R=\mathbb{C}[x]$, which is a PID. The polynomial $y^2+(x+i)(x-i)$ is irreducible in $R[y]$ by Eisenstein's criterion, as $x+i$ is irreducible in $R$ and $x-i$ doesn't divide $x+i$.
Note that Eisenstein's criterion applies to any PID, with the same proof as in the case for integers.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I add 40 weeks to the current date I get from the date picker
I have this code, I want to add 40 weeks to the date I get from the date Picker and get the new date after the 40 weeks (280 days) has been added to the date from the date picker.
Code:
public class MainActivity extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ eText.getText());
}
});
}
}
A:
Joda time is a very convenient library for handling such cases. Add this to your project:
dependencies {
compile 'joda-time:joda-time:2.10.2'
}
And then you can manipulate the dates like this:
DateTime dt = DateTime.now();
DateTime laterDate = dt.withYear(2020)
.withMonthOfYear(3)
.withDayOfMonth(14)
.plusWeeks(40);
Remember that in JodaTime date objects are immutable (which is a very good idea), so each manipulation produces a new object.
A:
First, convert the current format to milliseconds and then add specific days milliseconds and then again get it in the desired format. Like this way:
new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year,monthOfYear + 1,dayOfMonth);
long timeInMilliseconds =
calendar.getTimeInMillis()+TimeUnit.DAYS.toMillis(280);
calendar.setTimeInMillis(timeInMilliseconds);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
eText.setText(mDay + "/" + mMonth + "/" + mYear);
}
}, year, month, day);
picker.show();
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
"I've been doing this (for) a week" -- When do you leave out the 'for' when talking about duration, and when do you not?
The other day I heard someone say:
They've been going out a week; I mean, that's not (a) serious (relationship).
I wondered if she was speaking correctly, which is presumable, since she was a native American English speaker. But more often I here the for when people talk about duration. So is it also possible to leave out for? Maybe only in the informal register?
EDIT: There was a heavy stress on the word week. Does it play a role in this matter?
EDIT#2: ... OK. It's more suitable as an answer.
A:
Short answer: I would say that for can be omitted, but everyone may not agree with me. Its felicity may depend on context.
My answer focuses on the question you overheard, but my comments apply also to the question in your title ('I've been doing this (for) a week').
As a native speaker (AmE), I tend to think that whether for is necessary depends on the construction, context, and current usage, as well of course on the speaker's dialect or idiolect.
I certainly would rarely say
[Can you] wait for a second/a minute, I need to tie my shoe.
I would omit for in the sentence above. This is true whether I express it as an imperative (not using can you) or a question. Ngrams seems to back me up on this:
A search using second in both phrases returns a flat line (comparatively zero results) for the expression with for.
Another construction where the omission of for seems well suited is
I'm gone ten minutes/two days and (come back) and this is what happens?
Again, a short(er) period of time seems to work better here.
Thus
They've been going out a week and this is what happens?
seems fine.
As for the original sentence
They've been going out a week; I mean, that's not (a) serious (relationship),
in general, it might sound better with some qualifier such as only or now:
They've been going out a week now; I mean, that's not (a) serious (relationship).
You know, a lot depends on delivery (how it is said).
If it is said with no stress on any word or meaningful pauses in delivery, it seems a bit 'iffy' to me, but I would not judge it substandard but only say that for would improve it.
However, if week is stressed, it is definitely well suited or 'felicitous'.
Likewise if there were a meaningful pause between the two clauses, as in
They've been going out a week;...I mean, that's not (a) serious (relationship),
One assumes the first clause is a statement of fact, and if it is followed by a meaningful pause (a few moments is long enough) and then the second clause is stated as a 'commentary' on the first, that sounds fine also.
Used on its own the first clause sounds especially felicitous without for in answer to the question:
How long have they been going out?
and the reply
They've been going out a week.
Note we sometimes use the grammar or construction of the question in our responses.
So if the question had been
How long have they been going out for?
(whose felicity seems questionable, or at least to depend on dialect)
the response with for would not be unexpected.
Thus, since the interrogative form seems better to me (and I would think, most native speakers) without for, I'm not surprised I can accept the like response.
| {
"pile_set_name": "StackExchange"
} |
Q:
Batch file to find all images and copy to a folder
Not even sure if this is possible, but I'd figured i'd give it a try.
So here's my problem. I need to search multiple big hard drives (1TB and bigger) for all images and move them to one folder. My issue i'm having is no matter what language I try to write this in I can't seem to figure out a answer. I either want it to be vbs or bat related not using the robocopy command. Some of my drives are all different formats such as fat32 and ntfs. My issue with a few scripts I tried with the batch file was my file names are too long. So the main functions I need it to do is find the images, copy them, rename them with a _001 _002 if they exist, count how many files are moved, and then finally delete them or move them to a seperate folder for deleting ( a little more safe in my eyes ). Any help would be appreciated because I am totally stumped on this.
Here is one script that I was working on but just stopped on. The problem with this is it copied the files, but did not keep the extension for some reason. This was one I found online and modified the code on a little. I'm very familiar with code, but for some reason can't seem to figure this out.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set TESTFOLDER=allpictures
md "%TESTFOLDER%"
set /a counter=0
FOR /F "tokens=*" %%i IN ('DIR /S /B /A-D C:\Users\user1\Desktop\*.jpg') DO FOR /F "tokens=*" %%j IN ('DIR /B "%%i"') DO IF EXIST ".\%TESTFOLDER%\%%j" (
set /a counter=!counter!+1
echo folder: %TESTFOLDER%
copy "%%i" ".\%TESTFOLDER%\%%j_!counter!"
) ELSE copy /B "%%i" ".\%TESTFOLDER%\%%j"
:eof
Edit: VBScript Code Below
Set fso = CreateObject("Scripting.FileSystemObject")
testfolder = ".\allpictures"
'fso.CreateFolder(testfolder)
CopyFiles fso.GetFolder("E:\")
Sub CopyFiles(fldr)
For Each f In fldr.Files
basename = fso.GetBaseName(f)
extension = fso.GetExtensionName(f)
If LCase(extension) = "jpg" Then
dest = fso.BuildPath(testfolder, f.Name)
count = 0
Do While fso.FileExists(dest)
count = count + 1
dest = fso.BuildPath(testfolder, basename & "_" & count & "." _
& extension)
Loop
f.Copy dest
End If
Next
For Each sf In fldr.SubFolders
CopyFiles sf
Next
End Sub
A:
What you shouldn't do: Don't let you be hoodwinked into
producing code before you have understood the problem in full and have a detailed plan about the procedure. (Nobody likes "give me a program to solve my problem" type of questions, and sometimes a code snippet may clarify a problem, but asking people to try what they admittedly can't do is poor didactic.)
start with a new language to solve the problem at hand (plan or no plan). (If you are stuck writing a love letter in your native language, what are the chances to get it right with a grammar and a vocabulary of a foreign one?)
What you should do:
Think about your problem with a focus on the ultimate aim: organizing your images (if I understand your comment correctly). How would that look like? Certainly not one folder with thousands of files with mangled names. I would strive to end with a folder tree containing .jpgs with decent names, or a database with suitable meta-info about my pictures (videos?) and pathes to their storage, or even an upload to some cloud storage. From that ultimate aim work backwards: what do you need in the previous step.
I assume, the very first step is a list of all your .jpgs. What is - given your knowledge, skills, and tools - the easiest way to get this list? Probably some variation of dir /s [/b] c:\*.jpg > jpglist.txt. For many drives or other extensions that come up later, you can combine many such lines in one .cmd file (>/>>). This list and a text editor or a bit of filtering and a spreadsheet can give you valuable information about your task: How many files? Sum of all sizes? Duplicate files names? Possible classifications?
Buy a new external drive (you know the size by now). That way you can postpone the deleting to the step after you presented your beautifully organized collection to the astonished audience. [And this last task would be trivial: Just feed your jpglist.txt thru a "delete" filter script or use the search and replace facility of your text editor to put "del /Q " at the beginning of the lines.]
Depending on your needs and skills you can transform the basic jpglist.txt into new .csv files with pertinent information, that can be manually scanned/checked via a spreadsheet program and/or programmatically use to generate file or folder names (appending numbers should be the last fallback). If you'd like some JPG metadata and don't know how, you can ask here (and then even show the code you used to get sizes or dates for those files).
Make each step repeatable and as non-destructive as possible (e.g. don't move or delete files you can't recreate with one command before you are all done). Use the techniques/tools you know; that definitely rules out "code found on the internet"); if you want to learn something new/more interesting then do it in a toy project.
| {
"pile_set_name": "StackExchange"
} |
Q:
java.lang.ClassCastException: org.bouncycastle to error while creating wallet using web3j
I am using web3j to create account.
String walletFileName = WalletUtils.generateFullNewWalletFile("
<password>",new File("some/path"));
But getting this error:
java.lang.ClassCastException: org.bouncycastle.jce.provider.JCEECPrivateKey cannot be cast to org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey
My setup in pom.xml is as follows:
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.54</version>
</dependency>
Please let me know where I am going wrong.
A:
Your code seem to be OK, I just created a project and I can run it:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.gjeanmart.sandbox.web3j</groupId>
<artifactId>Web3jCreateWallet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
</project>
PS: You don't really need to add bouncycastle as dependancy as it is pull by web3j:core directly.
TestCreateWallet.java
package io.gjeanmart.stackexchange.web3j.test;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.junit.Test;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.WalletUtils;
public class TestCreateWallet {
@Test
public void createWallet() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CipherException, IOException {
String folder = "/tmp/wallet/";
String password = "secr3t";
File folderFile = new File(folder);
folderFile.mkdirs();
String walletFileName = WalletUtils.generateFullNewWalletFile(password, folderFile);
System.out.println("Wallet generated: " + walletFileName);
}
}
Result:
Wallet generated:
UTC--2018-12-18T16-41-35.32000000Z--cdf77e5fbee401d12f394f4f47f883407e883bd1.json
Code:
Code available on Github
| {
"pile_set_name": "StackExchange"
} |
Q:
Rally Rest Api C# ToolKit
I am trying to use the C# toolkit for RallyRest API. I want to display the number of user stories for each release, and the number of tasks by a team. The hierarchical requirement request doesn't return all the data.
Moreover, how can I filter the data based on a particular release and the owner of the User story? Below is my code. Can you please suggest where I should look? I saw the API.
RallyRestApi restApi = new RallyRestApi(username, password, "https://rally1.rallydev.com", "1.40");
bool projectScopingUp = false;
bool projectScopingDown = true;
try
{
Request storyRequest = new Request("HierarchicalRequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"FormattedID",
"Project",
"Release",
"ScheduleState",
"State",
"Owner",
"Tasks"
};
QueryResult queryStoryResults = restApi.Query(storyRequest);
int totalUS = 0;
foreach (var s in queryStoryResults.Results)
{
if (s["Release"] != null)
{
Release = s["Release"]["Name"];
string word = "July 2014";
if (Release.Equals(word))
{
string tempOwner = s["Owner"]["_refObjectName"];
if (tempOwner.Contains("development")
{
Owner = s["Owner"]["_refObjectName"];
paragraph.AddFormattedText("ID : " + Id + " Name : " + Name + " Owner : " + Owner + "Release :" + Release + "Number of Tasks : " + count, TextFormat.NotBold);
}
}
}
}
A:
Here is an example that filters stories by a particular release and story owner. It also gets the Tasks collection on each story and hydrates it with a separate request.
static void Main(string[] args)
{
int storyCount = 0;
int taskCount = 0;
RallyRestApi restApi;
restApi = new RallyRestApi("[email protected]", "secret", "https://rally1.rallydev.com", "v2.0");
String workspaceRef = "/workspace/1234"; //replace this OID with an OID of your workspace
Request sRequest = new Request("HierarchicalRequirement");
sRequest.Workspace = workspaceRef;
sRequest.Fetch = new List<string>() { "FormattedID", "Name", "Tasks", "Release", "Project", "Owner" };
sRequest.Query = new Query("Release.Name", Query.Operator.Equals, "r1").And(new Query("Owner", Query.Operator.Equals, "[email protected]"));
QueryResult queryResults = restApi.Query(sRequest);
foreach (var s in queryResults.Results)
{
Console.WriteLine("FormattedID: " + s["FormattedID"] + " Name: " + s["Name"] + " Release: " + s["Release"]._refObjectName + " Project: " + s["Project"]._refObjectName + " Owner: " + s["Owner"]._refObjectName);
storyCount++;
Request tasksRequest = new Request(s["Tasks"]);
QueryResult queryTaskResult = restApi.Query(tasksRequest);
foreach (var t in queryTaskResult.Results)
{
Console.WriteLine("Task: " + t["FormattedID"] + " State: " + t["State"]);
taskCount++;
}
}
Console.WriteLine(storyCount + " stories, "+ taskCount + " tasks ");
}
I noticed you are using 1.40 of WS API which is no longer supported. If you have older code it has to be re-factored to work with v2.0. In v2.0 it is not possible to hydrate the collection in the same request. There are many examples on StackOverflow rally tag on this subject, e.g. here Download latest dll for the toolkit here.
| {
"pile_set_name": "StackExchange"
} |
Q:
spring controller could not retrive a data from $http angular
I have a $http function in angular and a controller, but the controller do not retrieve data send from angular, in the log print
Skip CORS processing: response already contains
"Access-Control-Allow-Origin" header
I have configurate my filter in web.xml file to the headers
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
my angular function is this
app.controller('LoadCardController', function($scope, $http) {
$scope.executor = function() {
var person = {
name : 'Prueba',
todayDate : 1469679969827
};
console.log("DATA=> ", data);
$http({
method : 'POST',
url : 'http://localhost/myWeb/addPerson',
data : person,
headers : {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
console.log("success");
console.log(response);
}, function errorCallback(response) {
console.log("error");
console.log(response);
});
}
});
and my controller is this...
@ResponseBody
@RequestMapping(path = "/addPerson", method = RequestMethod.POST)
public Person addPerson(final Person person) throws CustomException {
person.setAge("18");
person.setBithDay("15");
LOGGER.trace("Add person with data {}", person);
return person;
}
});
}
when come in controller, data of person is null, for name and todayDate attributes, that is send by me in angular.
my controller is very simple now, because only return the same person objet
A:
From what you've shown here, it seems like the request is going through, but the data isn't making it onto your person parameter in the Spring controller method. There could be a few different causes.
First, It could be that the request body isn't getting mapped to your Spring controller method's person parameter. You can tell Spring to do this automatically by using the @RequestBody annotation (details here) before the method parameter. In your example:
@ResponseBody
@RequestMapping(path = "/addPerson", method = RequestMethod.POST)
public Person addPerson(@RequestBody Person person) throws CustomException {
person.setAge("18");
person.setBithDay("15");
LOGGER.trace("Add person with data {}", person);
return person;
}
If that doesn't solve it, it could be a problem with the Person class. At the minimum, it needs to have:
public class Person {
private String name;
private String age;
private String bithday;
private Date todayDate;
public Person() {
// this depends how your serialization is set up
}
// getters and setters...
}
One convention is to use a separate data-transfer-object class (i.e. PersonDto), which takes the data from the request body and builds a Person object with it (and vice versa), so that you can control how the submission gets mapped to the backend. More info on that pattern here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Example of non-interference in Java 8
According to this question, we can modify the source and it's not called interference:
you can modify the stream elements themselves and it should not be called as "interference".
According to this question, the code
List<String> list = new ArrayList<>();
list.add("test");
list.forEach(x -> list.add(x));
will throw ConcurrentModificationException.
But my code,
Employee[] arrayOfEmps = {
new Employee(1, "Jeff Bezos"),
new Employee(2, "Bill Gates"),
new Employee(3, "hendry cavilg"),
new Employee(4, "mark cuban"),
new Employee(5, "zoe"),
new Employee(6, "billl clinton"),
new Employee(7, "ariana") ,
new Employee(8, "cathre"),
new Employee(9, "hostile"),
new Employee(10, "verner"),
};
Employee el=new Employee(1, "Jeff Bezos");
List<Employee> li=Arrays.asList(arrayOfEmps);
li.stream().map(s->{s.setName("newname");return s;}).forEach(System.out::print);
doesn't throw ConcurrentModificationException, even though it in fact changes the source.
And this code,
Employee[] arrayOfEmps = {
new Employee(1, "Jeff Bezos"),
new Employee(2, "Bill Gates"),
new Employee(3, "hendry cavilg"),
new Employee(4, "mark cuban"),
new Employee(5, "zoe"),
new Employee(6, "billl clinton"),
new Employee(7, "ariana") ,
new Employee(8, "cathre"),
new Employee(9, "hostile"),
new Employee(10, "verner"),
};
Employee el=new Employee(1, "Jeff Bezos");
List<Employee> li=Arrays.asList(arrayOfEmps);
li.stream().map(s->{s.setName("newname");li.add(s);return s;}).limit(10).forEach(System.out::print);
throws
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at java8.Streams.lambda$0(Streams.java:33)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.forEach(Unknown Source)
So, I don't exactly understand what type of modifications are allowed to the source and what are not. It would be very helpful to see an example which interferes and have a stateful and side-effect producing stream, with proper indication that which is which.
A:
When you do this:
li.stream().map(s->{s.setName("newname");return s;})
you didn't alter the list itself but an element within this list; so it doesn't trigger a ConcurrentModificationException as you expected.
In the last code snippet, you are using Array.asList.
You have to know that Array.asList returns a mere read-only wrapper over an array (a specific inner ArrayList class) explaining why add is not supported.
Indeed this inner class does not override AbstractList#add method by design; causing UnsupportedOperationException; and still not ConcurrentModificationException as you expected again.
Here's an example similar to your last snippet that does throw a ConcurrentModificationException:
public static void main(String[] args) {
Employee[] arrayOfEmps = {
new Employee(1, "Jeff Bezos")
};
Employee el = new Employee(11, "Bill Gates");
List<Employee> li = new ArrayList<>(Arrays.asList(arrayOfEmps)); // to avoid read-only restriction
li.stream().peek(s -> li.add(el)).forEach(System.out::print);
}
Note that I'm wrapping the Arrays.List return with a "true" ArrayList, allowing writing because this one implements the add method ;)
A:
Your first example changes the existing elements of the Stream, but doesn't add or remove elements from the source. Therefore it's not an interference.
Your second example attempts to do interference, by adding an element to the source during the Stream pipeline. However, you get UnsupportedOperationException instead of ConcurrentModificationException, since you try to add elements to a fixed sized List (which is returned by Arrays.asList).
Change your second example to:
List<Employee> li=new ArrayList<>(Arrays.asList(arrayOfEmps));
li.stream().map(s->{s.setName("newname");li.add(s);return s;}).limit(10).forEach(System.out::print);
and you should get ConcurrentModificationException.
A:
This is called a structural on non-structural change of the source of the Stream. For example ArrayList doc says:
merely setting the value of an element is not a structural modification...
So in your example this means that changing Employee per-se, does not changes the List itself (does not remove or add an element). But changing the List itself, will fail with a ConcurrentModificationException:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.stream().forEach(x -> list.remove(x));
But there are sources where interference is more than OK, called weakly consistent traversal, like ConcurrentHashMap:
ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<>();
chm.put(1, "one");
chm.put(2, "two");
chm.put(3, "three");
chm.entrySet().stream()
.forEach(x -> chm.remove(x.getKey()));
This will not fail with ConcurrentModificationException.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to approve user registrations via email link
Since the latest update of Joomla I can no longer approve a user via the link in the registration approval email.
As of 3.8.13, Joomla is securing the process on approving an user after an email notification by requesting the administrator, who is going to approve the request, to login into the frontend. After the administrator logged in, they are redirected to the activation URL and the account is activated.
However this does not work. I click the link and get the message:
Please log in to confirm that you are authorised to activate new accounts.
When I then log in as Super User I get the message:
You are not authorised to view this resource
and the user remains unapproved.
Any suggestions as to how to get around this issue?
A:
I think I have discovered my issue. It appears to be due to ACL (access level) for the login menu item. It has to be public.
I followed the steps for the first answer in this post and now it works perfectly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android HTTP exception
I am using following code to log in to Dropbox, but it throws an exception.
Code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.dropbox.com/login");
// set values you'd like to send
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("login_email", "my email id"));
pairs.add(new BasicNameValuePair("login_password", "******"));
/*'login_email' and 'login_password' i found html form fields name by viewing the page source of https://www.dropbox.com/login */
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
// set ResponseHandler to handle String responses
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(post, responseHandler);
Log.v("HttpPost", "Response: " + response);
if (response.contains("SUCCESS")){
// express your joy here!
} else {
// pop a sad Toast message here...
}
} catch (Exception e) {
Log.e("", String.valueOf(e));
}
}
Logcat
11-14 23:17:35.734: E/Trace(900): error opening trace file: No such file or directory (2)
11-14 23:17:38.793: D/dalvikvm(900): GC_CONCURRENT freed 251K, 4% free 8194K/8519K, paused 126ms+9ms, total 234ms
11-14 23:17:39.895: E/(900): org.apache.http.client.HttpResponseException: Forbidden
11-14 23:17:40.364: I/Choreographer(900): Skipped 75 frames! The application may be doing too much work on its main thread.
11-14 23:17:40.394: D/gralloc_goldfish(900): Emulator without GPU emulation detected.
11-14 23:17:40.784: I/Choreographer(900): Skipped 62 frames! The application may be doing too much work on its main thread.
11-14 23:17:43.614: W/chromium(900): external/chromium/net/disk_cache/backend_impl.cc:1829: [1114/231743:WARNING:backend_impl.cc(1829)] Destroying invalid entry.
A:
I/Choreographer(900): Skipped 75 frames! The application may be doing too much work on its main thread.
It is always suggested to do Network activity on separate thread instead of main thread by using AsyncTask.
Here is android tutorial on Connecting to the Network
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't this working? It doesn't even call the onClick
<script type="text/javascript">
$("a.filef").click(function(e){
alert('hi, it works');
return false;
});
</script>
<a class="filef" href="" rel="1">A</a>
<a class="filef" href="" rel="2">V</a>
A:
You need to make sure the elements exist first. Try this instead:
$(function(){
$("a.filef").click(function(e){
e.preventDefault();
alert("Hi, it works.");
});
});
Placing your code within:
$(function(){
/* here */
});
Causes it to wait until the DOM is finished loading before it runs. In your case, it waits until the links exist before it attempts to bind logic to them.
In some scenarios you will need to run the code before the object exists. This is the case with many ajax-enabled websites. In those cases, jQuery has the $.live() method, which is of a similar look:
$(function(){
$("a.filef").live("click", function(e){
e.preventDefault();
alert("Hi, it works.");
});
});
Using this, it doesn't matter if the elements already exist, or will show up sometime in the future. Unless you're working with ajax or late-created elements, I would suggest sticking with the first solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get all elements whose id contains a particular substring?
I'm building a chat with firebase realtime database.
Let's say user1 has uid1 and user2 has uid2, their chatId will be uid1_uid2 (ordered asc).
So the database chat/ looks like this:
chat {
uid1_uid2: [message, message...],
uid4_uid2:[message, message...],
uid5_uid1:[message, message...],
uid11_uid8:[message, message...]
}
Firebase rules are the following to allow only the interlocutors to have access to the conversation:
"chat": {
"$chatId": {
".write": "$chatId.contains(auth.uid)",
".read": "$chatId.contains(auth.uid)"
}
}
I want to get elements having uid1 in the chatId. So the expected return would be
{
uid1_uid2: [message, message...],
uid5_uid1:[message, message...]
}
Is there a way to get elements whose id contains a particular substring ? Something like...
databaseChat.child("contains uid1").on("value", snapshot => {
})
A:
This is not possible. Realtime Database doesn't have substring queries. The best you can do is find prefix strings in values.
How to query firebase keys with a substring
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an add-on to auto compress files while uploading into Plone?
Is there any add-on which will activate while uploading files into the Plone site automatically? It should compress the files and then upload into the files. These can be image files like CAD drawings or any other types. Irrespective of the file type, beyond a specific size, they should get compressed and stored, rather than manually compressing the files and storing them.I am using plone 4.1. I am aware of the css, javascript files which get compressed, but not of uploaded files. I am also aware of the 'image handling' in the 'Site Setup'
A:
As Maulwurfn says, there is no such add-on, but this would be fairly straightforward for an experienced developer to implementing using a custom content type. You will want to be pretty sure that the specific file types you're hoping to store will actually benefit from compression (many modern file formats already include some compression, and so simply zipping them won't shrink them much).
Also, unless you implement something complex like a client-side Flash uploader with built-in compression, Plone can only compress files after they've been uploaded, not before, so if you're hoping to make uploads quicker for users, rather than to minimize storage space, you're facing a somewhat more difficult challenge.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert Uploaded Files To .pdf
I'm reviewing a spec. that calls for all files uploaded via a file field to be automatically converted to PDF format. I have two questions:
Is this wise? Files would be uploaded by anonymous customers. Allowed file extensions (.doc, .xls, .png, .jpg, etc) would be provided as per normal file field use.
(Edited to clarify my main concern is security)
Are there any conversion tools you would recommend? Paid or free is fine. Remote service is fine, local server-based is preferable. I can't find anything in the Drupal-verse, but have uncovered tools such as unoconv and JODConverter that look promising.
A:
Personally, I would store the file as it was uploaded, and then render it as a PDF for users when they download it. Your spec may say PDF now, but you want to have the flexibility should things change in the future.
Is this a good idea? That is a tough question, and really depends on the exact scenario. Personally, I would push back on this requirement. Format conversion can tax system resources, and I don't think you can really constrain the .doc and .xls formats enough, like you can with images, to be something reasonable.
Tools? The Printer, email and PDF versions module has a list of of the PHP-based PDF modules:
dompdf
mPDF
TCPDF
wkhtmltopdf
I am unaware if any of these will support .doc or .xls formats. I have used Ghostscript to convert images to PDF, and I am pretty sure it has some support for .doc. I am unaware of any Drupal-ready solution for this, though.
As for security implications, the scenario "makes my spidey sense tingle", but I can't point to anything in particular. I don't think you would have any problems with any of the malicious payloads in .doc and .xls files that normally affect Windows machines. However, if you go with a solution like GS, you will have to use a popen() or something similar, so you run the risk of an exploit there.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i display in a archive page a number of post i want
How can i display in a archive themplate ( post type) page a number of post,
Let say i want to display a number of 20 post....in archive page, under i want to display the pages...
Please look here :
http://cinema.trancelevel.com/trailer/aventuri/page/2/
I use post type pages... all the archive pages are now displayng 12 post..
I want to be able to display a number...
let say 20 post for trailers - for the trailers category
let say 10 post for actori- for actori category...
Now i use :
<?php is_tag(); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
Thanks in advance
A:
Just use the current_post property in the loop:
if ( have_posts() )
{
while( have_posts() )
{
global $wp_query;
the_post();
// Show current post number:
echo $wp_query->current_post;
} // endwhile;
} // endif;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle puppeteer exception on synchronous execution
I am trying to achieve a synchronous call:
puppeteer.launch().then(browser => {
let html = `
<!DOCTYPE html>
<html>
<body>
<div>
Hello
</div>
</body>
</html>
`;
let path = 'test.png';
browser.newPage().then(page => {
page.setContent(html).then(() => {
page
.screenshot({
path: path,
clip: {
x: 50,
y: 50,
width: 100,
height: 100
},
omitBackground: true
})
.then(() => {});
});
});
browser.close().then(() => {});
});
I get the following exception:
(node:22140) UnhandledPromiseRejectionWarning: Error: Protocol error (Target.createTarget): Target closed.
at Promise (C:\ImageServer\node_modules\puppeteer\lib\Connection.js:74:56)
at new Promise ()
at Connection.send (C:\ImageServer\node_modules\puppeteer\lib\Connection.js:73:12)
at Browser._createPageInContext (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:174:47)
at BrowserContext.newPage (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:367:26)
at Browser.newPage (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:166:33)
at Browser. (C:\ImageServer\node_modules\puppeteer\lib\helper.js:112:23)
at puppeteer.launch.then.browser (C:\ImageServer\imageServer.js:48:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:22140) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:22140) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How do I fix this?
A:
The problem is that you are closing the browser right after browser.newPage. You should move browser.close() to the then you have for screenshot.
page
.screenshot({
path: path,
clip: {
x: 50,
y: 50,
width: 100,
height: 100
},
omitBackground: true
})
.then(() => browser.close());
| {
"pile_set_name": "StackExchange"
} |
Q:
Double "1/3" as ConverterParameter
I have to convrt a double to other using a converter and a parameter:
This is my XAML stub:
Converter={StaticResource ToOtherDoubleConverter}, ConverterParameter=-1/2
this is the converter:
[ValueConversion(typeof(double), typeof(double))]
public class DoubleToOtherDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
return (double)value * double.Parse(parameter.ToString());
}
Now, this is useless to say that this is culture dependent, etc..
Is there a way to "hardcode" a double to be recognized as double?
Because the above variant could be written in different ways, by eg.:
ConverterParameter=-1/2
ConverterParameter=-0.5
ConverterParameter=-0,5
etc.
or also
double.Parse(parameter.ToString());
(double)parameter;
etc...
One more question:
How can I specify 1/3 in the floating format? something like
ConverterParameter=0.333333333333333333333333333333333333333333333333333333
A:
try this
public class DoubleToOtherDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var frac = ((string) parameter).Split('/');
if (frac.Length == 2)
return (double) value*double.Parse
(frac[0])/double.Parse(frac[1]);
return (double) value* double.Parse(((string) parameter)
.Replace(",", "."));
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
make tr visible depending on username all other unvisible
i have a table containing messages that are clickable links with the following structure:
<tr><td>#</td><td><a href='messages/". $file .".php'>$file</a></</td></tr>
...
$file always has this kind of structure as document name:
Date of submission [2014-02-19] - Subject [clean the garage] - To(everybody)
the table looks like this:
Date of submission [2014-02-19] - Subject [clean the garage] - To(Everybody)
Date of submission [2014-02-15] - Subject [clean the bathroom] - To(Annita)
Date of submission [2014-02-11] - Subject [clean the livingroom] - To(Rudy)
when a user logs in the $username echo's out for example Annita or Rudy or... Now what i would like to know if it is possible to make only the <tr> 's visible for the logged in user with according to(...) name
for example when Annita is logged in, she only gets to see the <tr>'s that has her name in it, and that for example the $file <tr> with Rudy becomes invisible. When the message is to(Everybody) all users can see the message
I hope my question is clear and somebody can help or explain me... thx in advance. breaking my head over this, and i cant change the structure of the message names...
A:
Why don't you use PHP to parse the file for $username? If $username exists in the file, then you include it.
See here: PHP - parsing a txt file
E.g., I'm logged in as Rudy, so $username = 'Rudy.' Now I use PHP to find all the files that match the regular expression /To\(Rudy\)$/ (which you'll write dynamically based on $username) and include them. Javascript is definitely not the right tool for the job here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Execute PHP script server side
Yesterday I created a script which is working fine, but only with an opened Web Browser which isn't that what I wanted. What I want is that the script runs all the time, even with closed Web Browser.
Could not upload a Picture, so its a short sketch:
(lookup.php) -> pass var data1 -> (run_code.php) -> pass var data1 ->
(check.php) = {{refreshes every 5 seconds till var data2 exists in
MySQl.}} -> goto -> lookup.php.....
The only problem is that I have no idea how to send a value from one .php file to another without GET,POST,COOKIE or SESSION. Session would be the best option but "lookup.php" is looking for a value, and if I start session I get the error "header is already set".
So, how should I pass these value from "lookup.php" to "run_code.php"?
Second problem is, "check.php" is a code that checks if value exists in mysql. This code refreshed and executes itself after 5 seconds using META REFRESH. But also this is not working without a browser.
How should I write the script that the script executes itself after a time?
A:
If i understand you want to write a script (and choose php probably because your familiar with its syntax) and you need it to run every X minutes.
Problem is that when you write a web site with PHP you can pass information using HTTP methods (get/post) and using the session
when running a script on a machine you don't have the HTTP traffic and no session (this can be simulated but its a bit complicated)
my suggestion is :
1) combine all the php files into 1 long php file that will be running (this way you can work with variables in the script with no problem) - you can copy past your code into 1 php file and you can include the needed files in your script so you can stile keep the original files
2) add a cron job (if its a Linux system) - http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/ - this way your script with run every X time (your choice)
| {
"pile_set_name": "StackExchange"
} |
Q:
Slick2D get image x and y
Ok, so i have a car that you can drive around in my game. It's basically an Image that drives around on a background, a and d turns it, w and s drives back and forth. But i want to make some borders on the screen edges so it doesnt just keep driving out into nothing, but to do that i think i have to get the x and y location of the Image. Does anyone know how to get this/know another way of making borders in Slick2D?
Thanks, Marco.
This is the GameplayState code:
package myprojects.main;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class GameplayState extends BasicGameState {
int stateID = -1;
Image imgBG = null;
Image player = null;
float scale = 1.0f;
Sound ding = null;
Sound gamemusic = null;
int height;
int width;
private static int rightSide = 1200;
private static int topSide = 800;
float startGameScale = 1;
float scaleStep = 0.001f;
int[] duration = { 200, 200 };
public Car car;
// Animation car, driveUp, driveDown, driveRight, driveLeft;
boolean hasWon;
GameplayState(int stateID) {
this.stateID = stateID;
}
@Override
public int getID() {
return stateID;
}
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
imgBG = new Image("myprojects/main/resources/land.png");
player = new Image("myprojects/main/resources/playercar.png");
ding = new Sound("myprojects/main/resources/ding.wav");
gamemusic = new Sound("myprojects/main/resources/gamemusic.wav");
car = new Car(300,300);
/**
* Image[] carUp = {new Image("myprojects/main/resources/carUp.png"),
* new Image("myprojects/main/resources/carUp.png")}; Image[] carDown =
* {new Image("myprojects/main/resources/carDown.png"), new
* Image("myprojects/main/resources/carDown.png")}; Image[] carRight =
* {new Image("myprojects/main/resources/carRight.png"), new
* Image("myprojects/main/resources/carRight.png")}; Image[] carLeft =
* {new Image("myprojects/main/resources/carLeft.png"), new
* Image("myprojects/main/resources/carLeft.png")};
*
* driveUp = new Animation(carUp, duration, false); driveDown = new
* Animation(carDown, duration, false); driveRight = new
* Animation(carRight, duration, false); driveLeft = new
* Animation(carLeft, duration, false); player = driveDown;
**/
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
imgBG.draw(0, 0);
gc.setSoundVolume(0.05f);
gamemusic.loop();
g.drawString("Pause Game", 1100, 775);
g.drawImage(car.getImage(), car.getX(), car.getY());
}
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
Input input = gc.getInput();
// Check if outside left border
if(car.x < 0) {
car.setX(0);
}
// Check if outside top border
if(car.y < 0) {
car.setY(0);
}
// Check if outside right border
if(car.x >= gc.getWidth() - car.getWidth()) {
car.setX(gc.getWidth() - car.getWidth());
}
// Check if outside bottom border
if(car.y >= gc.getHeight() - car.getHeight()) {
car.setY(gc.getHeight() - car.getHeight());
}
int mouseX = input.getMouseX();
int mouseY = input.getMouseY();
boolean hasWon = false;
if ((mouseX <= rightSide && mouseX >= rightSide - 100)
&& (mouseY <= topSide && mouseY >= topSide - 50)) {
hasWon = true;
}
if (hasWon) {
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
sbg.enterState(StarRacingGame.MAINMENUSTATE);
} else {
}
}
if (input.isKeyDown(Input.KEY_ESCAPE)) {
ding.play();
sbg.enterState(StarRacingGame.MAINMENUSTATE);
}
if (input.isKeyDown(Input.KEY_A)) {
car.rotate(-0.2f * delta);
}
if (input.isKeyDown(Input.KEY_D)) {
car.rotate(0.2f * delta);
}
if (input.isKeyDown(Input.KEY_S)) {
float hip = 0.4f * delta;
float rotation = car.getRotation();
car.x -= hip * Math.sin(Math.toRadians(rotation));
car.y += hip * Math.cos(Math.toRadians(rotation));
}
if (input.isKeyDown(Input.KEY_W)) {
if (input.isKeyDown(Input.KEY_LSHIFT)) {
float hip = 1.4f * delta;
float rotation = car.getRotation();
car.x += hip * Math.sin(Math.toRadians(rotation));
car.y -= hip * Math.cos(Math.toRadians(rotation));
} else {
float hip = 0.4f * delta;
float rotation = car.getRotation();
car.x += hip * Math.sin(Math.toRadians(rotation));
car.y -= hip * Math.cos(Math.toRadians(rotation));
}
}
}
}
Car code:
package myprojects.main;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Car {
public int x;
public int y;
public Image image;
public Car(int x, int y) throws SlickException{
this.x = x;
this.y = y;
image = new Image("myprojects/main/resources/playercar.png");
}
public org.newdawn.slick.Image getImage() {
return image;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return 100;
}
public int getHeight() {
return 100;
}
public int getY() {
return y;
}
public void rotate(float f) {
image.rotate(f);
}
public float getRotation() {
return image.getRotation();
}}
A:
What I would do is create a Car class that has an Image. With this class, you can have ints that hold the x and y values representing the car's location, as well as the image of the car. Then, you just set the values or x and y and rotate the image like you are doing in your example, except for the Car object. You may do this already, I am not sure though without more code than just the input handler. To draw it, do something like this in your render:
drawImage(car.getImage(), car.getX(), car.getY());
As far as borders, assuming you just don't want your Car to go off screen, you can do something like this:
// Check if outside left border
if(car.getX() < 0) {
car.setX(0);
}
// Check if outside top border
if(car.getY() < 0) {
car.setY(0);
}
// Check if outside right border
if(car.getX() >= SCREEN_WIDTH - car.getWidth()) {
car.setX(SCREEN_WIDTH - car.getWidth());
}
// Check if outside bottom border
if(car.getY() >= SCREEN_HEIGHT - car.getHeight()) {
car.setY(SCREEN_HEIGHT - car.getHeight());
}
In this context, get width and get height are getting the width and height of the image you use for the car, and SCREEN_HEIGHT and SCREEN_WIDTH are constants that hold the width and height of the screen. You may have to fine tune a bit depending on how your game works.
public Class Car {
private int x;
private int y;
private Image image;
public Car(int x, int y) {
this.x = x;
this.y = y;
image = new Image("location/car.png");
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Which derivative to use for an integral?
Does anyone know of a rule to tell which derivative to use when faced with an integral like this? (C is any constant, eg. 2400 or 4, etc).
$$\int \:\frac{C}{x}\mathrm{d}x$$
I know that $\ln(x) = \int\frac{1}{x}\mathrm{d}x$ so then $\int \:\frac{C}{x}\mathrm{d}x$ could equal $C\ln(x)$.
I also know that $\frac{1}{x}$ can be $x^{-1}$.
Both the $\ln(x)$ and $x^{-1}$ give different answers, so employing the wrong one is a problem. So how do we know which one to use and what situation?
An example, $\int \:\frac{2.6}{x}$. Which "derivatie method" (excuse my lack of proper terminology) would I use if I am trying to get the integral?
A:
If we try to integrate $x^{-1}$ using the power rule it replaces the function with a constant because $x^0=1$. Since it is a constant, its derivative is not actually $x^{-1}$ so we know it doesn't work. Since $-1$ is the only value that doesn't follow the power rule it's the only special case you have to remember.
| {
"pile_set_name": "StackExchange"
} |
Q:
Processing dependent elements that are in the wrong order
The following PHP example code only works if the "bar" elements come before the "foo" elements. If they are in the wrong order, I will get a "call to a member function on a non-object" error.
$data = array();
foreach($elems as $e) {
if($e['type'] == "foo") {
$data[$e["key"]->foo_data($e["data_foo"]);
}
elseif($e['type'] == "bar") {
$data[$e["key"]] = new Bar($e);
}
}
My solution at the moment is to iterate twice through $elems. Another solution would be to use usort with a custom sort function that puts "bar" elements before "foo" elements.
Are there any programming patterns or libraries that would allow me to process the elements in arbitrary order?
A:
Looping twice seems like the most sensible solution. Loop once to prepare your objects, loop a second time to let those objects process data. There may be an entirely different, better solution, but that's hard to say without seeing a more concrete use case.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.