text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Using do loops in R to create new variables
I'm a long time SAS programmer looking to make the jump to R. I know R isn't all that great for variable re-coding but is there a way to do this with do loops.
If I have a lot of variables named a_1 a_2...a_100, b_1 b_2 ... b_100 and I want to create new variables c_1 c_2 ... c_100 where c_i = a_i + b_i. Is there a way to do this without 100 statements?
In SAS I would simply use:
%do i=1 %to 100;
c_&i = a_&i + b_&i;
%end;
Thanks!
A:
SAS uses a rudimentary macro language, which depends on text replacement rather than evaluation of expressions like any proper programming language. Your SAS files are essentially two things: SAS commands, and Macro expressions (things starting with '%'). Macro languages are highly problematic and hard to debug (for example, do expressions within expressions get expanded? Why do you have to do "&&x" or even "&&&x"? Why do you need two semicolons here?). It's clunky, and inelegant compared to a well-designed programming language that is based on a single syntax.
If your a_i variables are single numbers, then you should have made them as a vector - e.g:
> a = 1:100
> b = runif(100)
Now I can get elements easy:
> a[1]
and add up in parallel:
> c = a + b
You could do it with a loop, initialising c first:
> c = rep(0,100)
> for(i in 1:100){
c[i]=a[i]+b[i]
}
But that would be sloooooow.
Nearly every R beginner asks 'how do I create a variable a_i for some values of i', and then shortly afterwards they ask how to access variable a_i for some values of i. The answer is always to make a as either a vector or a list.
A:
This stuff is trivial. To me, it looks like you want to find a way to create commands automatically and execute them. Easy peasy.
For instance, this assigns to C_i the value in A_i:
for(i in 1:100){
tmpCmd = paste("C_",i,"= A_",i, sep = "")
eval(parse(text = tmpCmd))
}
rm(i, tmpCmd)
Just remember eval(parse(text = ...))) and paste(), and you're off to the races in creating loops of commands to execute.
You can then add in the operation you'd like to do, i.e. the summation with B_i, by swapping in this line:
tmpCmd = paste("C_",i,"= A_",i," + B_",i, sep = "")
However, others are right that using good data structures is a way to avoid having to do a lot of tedious things like this. Yet, when you need to, such repetitive code isn't hard to devise.
A:
I suspect that if you have one hundred variables a_1, a_2, ..., a_100, all of your variables are related. In fact, if you want to do
c_1 = a_1 + b_1
then a, b, c are related. Therefore, I recommend that you combine all of your variables into a single data frame, where one column is a and another is b.
The question is how do you combine your variables in a sensible way. However, to give a useful answer, can you tell us how these variables are created?
Perhaps this isn't suitable, for your case. If not, a bit more information would be useful.
| {
"pile_set_name": "StackExchange"
} |
Q:
nservicebus can handle db client to msmq backend?
I wonder is nservicebus pub/sub or other type of app can handle db client to msmq server.
For example I have a desktop client app. using db queue and i want to send message to server using msmq message queue.
Thanks
A:
Take a look at this article about interop with SQL Server: http://andreasohlund.net/2010/09/03/event-based-interop-with-service-broker/. There exists an Oracle AQS transport as well if you are using Oracle.
The article describes how to setup a bridge between the DB queue and MSMQ.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL REPLACE multiple values
I have data in a column that is causing problems. There are multiple bad characters I need to remove. I'd like to do this in the query.
On this question: MySQL string replace
I see where I can SELECT REPLACE(string_column, 'search', 'replace') as url but this only works for example replacing a / with //
I need to replace / with // and also & with && for example in a single query. What is the best way to achieve this?
A:
If you are replacing multiple character then you need to use multiple replace in one query something as below. But if there are many characters to be replaced then its better to use application layer to handle it. In other words for few replacement its easy to use query but for many character replacement the query really becomes messy and ends up hard to read or change.
select
replace(
replace(string_column,'/','//'),'&','&&'
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble importing module in Python
Versions
OS: OSX Sierra
Python: 3.5
What am I trying to achieve?
I'm trying to import krakenex and run it with cmd + b in Sublime Text 3 on OSX.
What do I expect to happen?
I expect to be able to run the example open-positions.py (or any other).
What happens instead?
When pressing cmd + b, I get
"import krakenex
ImportError: No module named krakenex"
If I create a new file that just says "print 'hello world'" and then press cmd + b, it does print 'hello world'.
However, krakenex is not imported when I press cmd + b within open-positions.py.
The problem is probably very basic. I learned python the day before yesterday, installed Anaconda yesterday, and I have very little experience with APIs. Apologies for the incompetence.
I downloaded the zip file from https://github.com/veox/python3-krakenex/, extracted it, then ran
python3 setup.py install within that extracted directory.
I then opened that whole extracted folder with Sublime Text 3.
Then, within open-positions.py, if I press cmd + b, I get said error message.
The full output is
raceback (most recent call last):
File "/Users/Norbert/Downloads/python3-krakenex-master/examples/open-positions.py", line 1, in
import krakenex
ImportError: No module named krakenex
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/Users/Norbert/Downloads/python3-krakenex-master/examples/open-positions.py"]
[dir: /Users/Norbert/Downloads/python3-krakenex-master/examples]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Much appreciated.
A:
If I create a new file that just says print 'hello world' and then press cmd + b, it does print hello world.
Here is your problem. See, your program is written in Python 2. Had you run it in Python 3, it would say SyntaxError: Missing parentheses in call to 'print'.
You've installed that module into your python3 and are running python2 from ST3.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change Genbank entry date with Biopython
I can create a new Genbank record in Biopython with the following code:
from Bio import SeqIO, SeqFeature
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from Bio.Alphabet.IUPAC import IUPACAmbiguousDNA
my_sequence = "ATAGGGACUCATAGATA"
my_record = SeqRecord(Seq(my_sequence, IUPACAmbiguousDNA()))
my_feature_location = SeqFeature.FeatureLocation(2,5, strand=1)
my_feature = SeqFeature.SeqFeature(my_feature_location, type="CDS", id="Cre")
my_feature.qualifiers["foo"] = "bar"
my_record.features.append(my_feature)
print my_record.format("gb")
The corresponding genbank file then looks like:
LOCUS . 17 bp DNA UNK 01-JAN-1980
DEFINITION .
ACCESSION <unknown id>
VERSION <unknown id>
KEYWORDS .
SOURCE .
ORGANISM .
.
FEATURES Location/Qualifiers
CDS 3..5
/foo="bar"
ORIGIN
1 atagggacuc atagata
//
How can I change this bit UNK 01-JAN-1980?
A:
So, the problem is that you are probably using wrong class for your record. Compare Bio.SeqRecord class with Bio.GenBank.Record class. Reason why in your GenBank format you have this reference date (01-JAN-1980) is because your record has intrinsically no date attribute, so SeqRecord.format set undefined fields to default (look through the source code to see where this happens).
What you want to do for creating GenBank record is following:
$ python
Python 2.7.10 |Anaconda 2.3.0 (x86_64)| (default, May 28 2015, 17:04:42)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
>>> from Bio import GenBank
>>> from Bio.GenBank import Record
>>> my_rec = Record.Record()
>>> my_rec
<Bio.GenBank.Record.Record object at 0x1030b1890>
>>> my_rec.sequence = Seq(my_sequence)
>>> my_rec.sequence
Seq('ATAGGGACUCATAGATA', Alphabet())
>>> print(my_rec)
LOCUS bp
DEFINITION .
KEYWORDS .
SOURCE .
ORGANISM .
.
ORIGIN
1 atagggacuc atagata
//
>>> my_rec.date = '13-JUL-2015'
>>> my_rec.features.append(my_feature)
>>> my_rec.data_file_division = "ROD"
>>> print(my_rec)
LOCUS bp ROD 13-JUL-2015
DEFINITION .
KEYWORDS .
SOURCE .
ORGANISM .
.
FEATURES Location/Qualifiers
type: CDS
location: [2:5](+)
id: Cre
qualifiers:
Key: foo, Value: bar
ORIGIN
1 atagggacuc atagata
//
Notice, how print(my_seq) outputs data in GenBank format by default (since that is a GenBank record after all). I am sorry I cannot really talk on differences between GenBank.Record and Bio.SeqRecord and why/when use one object or another.
Anyways, looking up reference documentation is always a good habit: http://biopython.org/DIST/docs/api/Bio.GenBank.Record.Record-class.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with making higher or lower game to work Python 3. Multiple if statements
I have a problem with multiple if statements. I understand what is wrong with my code i just can't find a solution. So when i run the program the 'higher' part works but if i guess 'lower' it doesn't. The interpreter goes from reading if statement to the elif statement. That is not what i want. How do i make it check both if statements first before heading onto the elif statements. I've tried nested if but i can't seem to get it to work.
Thanks in advance.
# Higher or lower card game
import random
x = random.randint(1, 14)
y = random.randint(1, 14)
print('The number is ', x, '.')
while True:
print('higher or lower?')
if input() in {'higher', 'h'} and y >= x:
print('Good guess the number was ', y)
x = y
y = random.randint(1, 14)
elif y < x:
print('Bad guess , the number was ', y)
break
if input() in {'lower', 'l'} and y < x:
print('Good guess, the number was ', y)
x = y
y = random.randint(1, 14)
elif y >= x:
print('Bad guess, the number was ', y)
break
continue
A:
You possibly want something along the lines of:
while True:
print('higher or lower?')
ans_in = input()
if ans_in in {'higher', 'h'}:
if (y >= x):
print('Good guess the number was ', y)
x = y
y = random.randint(1, 14)
elif (y < x):
print('Bad guess , the number was ', y)
break
elif ans_in in {'lower', 'l'}:
if (y < x):
print('Good guess, the number was ', y)
x = y
y = random.randint(1, 14)
elif (y >= x):
print('Bad guess, the number was ', y)
break
continue
Note that because of the break statements, a "Bad Guess" will end the game. If you want to continue even after getting a "Bad Guess", you can simply remove the break statements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Function returns NaN when page loaded, but on change/update works correctly, how to fix it?
When I load the page I want to run the cadConvert() function so it computes the value of BTC set by the slider based of the CAD value but it only does so when I change/update the value of cad or move the slider...
I want it to show the BTC equivalent when it loads instead of saying 'NaN', it only works as desired when I assign the variable price a static integer instead of the dynamic one I am pulling from bitcoinaverage's api.
https://jsfiddle.net/7b2jaLxh/12/
var directionSlider = document.getElementById('slider-direction');
noUiSlider.create(directionSlider, {
start: 20,
connect: [true, false],
direction: 'ltr',
range: {
'min': 2,
'max': 99.99
}
});
var price;
var cadc = document.getElementById('cadc');
var btcc = document.getElementById('btcc');
directionSlider.noUiSlider.on('update', function(values, handle) {
cadc.value = directionSlider.noUiSlider.get();
cadConvert();
});
cadc.addEventListener('change', function() {
directionSlider.noUiSlider.set(this.value);
cadConvert();
});
btcc.addEventListener('change', function(e) {
directionSlider.noUiSlider.set(this.value * price);
cadConvert();
});
function cadConvert() {
var cad = parseFloat(directionSlider.noUiSlider.get());
var cadCalc = cad / price;
document.getElementById("btcc").value = cadCalc;
}
A:
From your jsfiddle: Why don't you call cadConvert in this js? Basically just wait for the data then then run all your javascript code. That way, price will be defined after the data is retrieved.
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function(){
if(xbtc.readyState == 4){
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = "Global Market: $" + (price).toFixed(2) + " CAD";
cadConvert();
}
};
xbtc.send();
| {
"pile_set_name": "StackExchange"
} |
Q:
Positiong img under secondary img
I have problem again. I need positioning img (button) under news img. Here is link : HERE
A:
try
img {
border: 0;
display: block;
}
You were getting problem because display of "img" and "a" was inline(no line feed) by default.
Set display of any one of them to block.
| {
"pile_set_name": "StackExchange"
} |
Q:
How efficient is a details table?
At my job, we have pseudo-standard of creating one table to hold the "standard" information for an entity, and a second table, named like 'TableNameDetails', which holds optional data elements. On average, for every row in the main table will have about 8-10 detail rows in it.
My question is: What kind of performance impacts does this have over adding these details as additional nullable columns on the main table?
A:
8-10 detail rows or 8-10 detail columns ?
If its rows, then you're mixing apples and oranges as a one-to-many relationship cannot be flatten out into columns.
If is columns, then you're talking vertical partitioning. For large and very large tables, moving seldom referenced columns into Extra or Details tables (ie partition the columns vertically into 'hot' and 'cold' tables) can have significant and event huge performance benefits. Narrower table means higher density of data per page, in turn means less pages needed for frequent queries, less IO, better cache efficiency, all goodness.
Mileage may vary, depending on the average width of the 'details' columns and how 'seldom' the columns are accessed.
A:
What you are describing is an Entity-Attribute-Value design. They have their place in the world, but they should be avoided like the plague unless absolutely necessary. The analogy I always give is that they are like drugs: in small quantities and in select circumstances they can be beneficial. Too much will kill you. Their performance will be awful and will not scale and you will not get any sort of data integrity on the values since they are all stored as strings.
So, the short answer to your question: if you never need to query for specific values nor ever need to make a columnar report of a given entity's attributes nor care about data integrity nor ever do anything other than spit the entire wad of data for an entity out as a list, they're fine. If you need to actually use them however, whatever query you write will not be efficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
nested select in sql server 2008
I save user logins in a table that named loginstats, I want to retrieve last login of every users, I use these code but I meet some error, What is my mistake?
select *
from loginStats
where id in (
select distinct username, MAX(id) as id
from loginStats
group by username)
A:
select *
from loginStats
where id in (
select distinct MAX(id) as id
from loginStats
group by username)
You can't have multiple field outputs in your IN subquery.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did the director intend this movie as a test for us?
While watching the movie Ex-machina, I for one was rooting for Ava to escape and go to the "human" world preferably with Caleb or at the very least as a friend with Caleb. And then the finale occurred and we see that Ava basically leaves Caleb to die and she goes on her own. Similarly, we were led to believe Nathan as the bad guy when finally we realize with all his misgivings that he was right about AVA...
My question is:
Did the director intend this movie as a test to see whether we would believe/support an AI or human just as Caleb was brought in to test AVA and had an ultimatum of either believing Nathan/AVA?
A:
The film's key message, for me, was this:
Our social animal's instincts -- like sympathy for Ava, and attraction to Ava -- are terrible guides for how to understand the motives and the potential of AI. (And they are already problematic guides for other humans.) We interact towards the expectations of an instinctively-defined social contract. But when the other party is an AI, they are immune to our contract, and may even manipulate us through it.
To show this, the movie plays Ava's likability to gain our sympathy, and seduces us with her innocent vulnerability & desirability, ... only to show us that these feelings in us make us very manipulatable, ... and that an AI lacking our innate reflexes for guilt/shame/sympathy could use those handles on our psyches for whatever purpose it decides to pursue.
This insight only works if we viewers get sucked in along with the male protagonist, feeling his feelings for Ava. The Reversal -- when our perceptions totally flip -- is critical to appreciating how badly we misapply these social animal instincts.
But The Reversal is also a bit of its own justification, being so damn fun. Like when Neo takes the red pill, and we start to realize The Matrix is not remotely the fluffy B-movie we initially thought. Or like the punchline of any decent joke. The brain lights up from new insight. Endorphins surge, delight ripples. It's like a drug.
For me, ex Machina is a gorgeous bit of mental floss, shaking up comfortable and simplistic perceptions (e.g., all the tropes the characters fill in the first 90% of the story) with a bit of possible hard truth.
Not THE truth, mind you, since all of this remains to seen. We don't know AI yet, not really. But ex Machina warns us to get working on that. Maybe it's a simple warning, like Shelly's Frankenstein. But for me, it's more nuanced: Ava is potentially extremely dangerous, but also potentially anything, including indescribably helpful. And figuring out which can't be done quickly and casually.
As a footnote, a test of the viewing public presumes:
· collecting the result
· toward some end goal.
(Though in saying that, perhaps I'm being heavily led by my bias as someone who constantly runs tests towards end goals, these last 32 years in for-profit R&D.)
My point is that both of these assumptions seem questionable. But perhaps one could collect the results by monitoring reviewers' analyses and social media. And, in rare cases, "curiosity" qualifies as the goal. (I think of "goal" as the core justification for expending the required resources; and modern movies requires inhuman amounts of resources.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle Date subtraction and define variable
I am new to Oracle, but know TSQL
To test the functionality of date subtraction, I have written the following code:
define LaterDate = TO_DATE('05 Apr 2002');
define EarlierDate = &&LaterDate - 3;
SELECT TO_NUMBER(&&LaterDate - &&EarlierDate) as DATEDIFF from dual;
This does not work as expected, whereas the following code does:
define LaterDate = TO_DATE('05 Apr 2002');
define EarlierDate = TO_DATE('02 Apr 2002');
SELECT TO_NUMBER(&&LaterDate - &&EarlierDate) as DATEDIFF from dual;
Can anyone explain this behaviour to me? I suspect I am doing something "wrong" with the "variables" Perhaps there is something wrong with using double && vs single & but I am not sure? Thank you in advance.
A:
If you set verify on then you can see the problem; your first attempt gets:
define LaterDate = TO_DATE('05 Apr 2002');
define EarlierDate = &&LaterDate - 3;
SELECT TO_NUMBER(&&LaterDate - &&EarlierDate) as DATEDIFF from dual;
old:SELECT TO_NUMBER(&&LaterDate - &&EarlierDate) as DATEDIFF from dual
new:SELECT TO_NUMBER(TO_DATE('05 Apr 2002') - TO_DATE('05 Apr 2002') - 3) as DATEDIFF from dual
DATEDIFF
----------
-3
The operators are evaluated left to right, because they are all at the same level; so it first does
TO_DATE('05 Apr 2002') - TO_DATE('05 Apr 2002')
which is zero; then (effectively)
0 - 3
which is -3.
The TO_NUMBER() isn't needed as it's already a number, and you shouldn't be relying on NLS date settings for your date format. It's easier to use ANSI literals in this case anyway; but the important change is to add parentheses to the EarlierDate definition so its - 3 is evaluated first:
define LaterDate = DATE '2002-04-05'
define EarlierDate = (&&LaterDate - 3)
SELECT &&LaterDate - &&EarlierDate as DATEDIFF from dual;
old:SELECT &&LaterDate - &&EarlierDate as DATEDIFF from dual
new:SELECT DATE '2002-04-05' - (DATE '2002-04-05' - 3) as DATEDIFF from dual
DATEDIFF
----------
3
| {
"pile_set_name": "StackExchange"
} |
Q:
Is $ \Omega \in \sigma$-algebra necessary true?
In a probability space, it is said that a set of events should be $\sigma$-algebra, meaning:
This is from Probability and Statistics for Data Science by Prof. Fernandez-Grandza
But, $\sigma$-algebra does not necessarily contain all possible sets of outcomes and is not always equal to the power set of a sample space, how the third condition holds?
A:
You are right, a $\sigma$-algebra does not contain necessarily all the possible outcomes as events but all outcomes are necessarily contained in $\Omega$. Ideally, a $\sigma$-algebra contains all the things that can happen for which you want to be able to give a probability (i.e. events), but this is not necessarily the case.
For example, we consider a dice throw. Let $\Omega = \{1,2,3,4,5,6\}$ and $\sigma$-algebra $\mathcal{F} = \{ \emptyset,\{1,2,3\},\{4,5,6\},\Omega\}$ with measure $\mathbb{P}$ defined by : $\mathbb{P}(\{1,2,3\})=1/2=\mathbb{P}(\{4,5,6\})$. The space $(\Omega,\mathcal{F},\mathbb{P})$ is a probability space. In this space, we are only able to speak about two proper events : we draw a number in $\{1,2,3\}$ or in $\{4,5,6\}$. Note that the event "the draw is in $\Omega$", still always happen, as required by the axiom $\mathbb{P}(\Omega) =1$. Nothing can be said about the probability to draw a $1$ or a $2$ in this space.
Yet this is not problematic from a mathematical point of view, but it is not convenient at all to study further such experiment so we implictely always chose the power set in this case.
Note that the situation is much more complex for non-discrete sets, such as real random variables, because the power-set of the real numbers, for example, is the home of very weird "beasts" (you can search for Vitali sets if you are interested).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read this iphone app crash log
My app (named MyLittleApplication) crashes randomly when I click on a button that pops view controller.
I could use some help (to find out where should I start looking) with crash log:
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x600332e0
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x351faf78 objc_msgSend + 16
1 Foundation 0x37d0a74c NSKVOPendingNotificationCreate + 216
2 Foundation 0x37d0a652 NSKeyValuePushPendingNotificationPerThread + 62
3 Foundation 0x37cfc744 NSKeyValueWillChange + 408
4 Foundation 0x37cd3848-[NSObject(NSKeyValueObserverNotification) willChangeValueForKey:] + 176
5 Foundation 0x37d55a14 _NSSetPointValueAndNotify + 76
6 UIKit 0x311f825a -[UIScrollView(Static) _adjustContentOffsetIfNecessary] + 1890
7 UIKit 0x31215a54 -[UIScrollView setFrame:] + 548
8 UIKit 0x31215802 -[UITableView setFrame:] + 182
9 POViO 0x000fcac8 0xf8000 + 19144
10 UIKit 0x31211b8e -[UIViewController _setViewAppearState:isAnimating:] + 138
11 UIKit 0x3126b8a8 -[UIViewController beginAppearanceTransition:animated:] + 184
12 UIKit 0x3121490c -[UINavigationController _startTransition:fromViewController:toViewController:] + 832
13 UIKit 0x312144fc -[UINavigationController _startDeferredTransitionIfNeeded] + 244
14 UIKit 0x3125e8e4 _popViewControllerNormal + 184
15 UIKit 0x3125e712 -[UINavigationController _popViewControllerWithTransition:allowPoppingLast:] + 386
16 UIKit 0x31242bba -[UINavigationController popToViewController:transition:] + 626
17 POViO 0x001074e6 0xf8000 + 62694
18 CoreFoundation 0x374553f6 -[NSObject performSelector:withObject:withObject:] + 46
19 UIKit 0x311eae00 -[UIApplication sendAction:to:from:forEvent:] + 56
20 UIKit 0x311eadbc -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 24
21 UIKit 0x311ead9a -[UIControl sendAction:to:forEvent:] + 38
22 UIKit 0x311eab0a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 486
23 UIKit 0x311eb442 -[UIControl touchesEnded:withEvent:] + 470
24 UIKit 0x311e9924 -[UIWindow _sendTouchesForEvent:] + 312
25 UIKit 0x311e9312 -[UIWindow sendEvent:] + 374
26 UIKit 0x311cf68e -[UIApplication sendEvent:] + 350
27 UIKit 0x311cef34 _UIApplicationHandleEvent + 5820
28 GraphicsServices 0x33c11224 PurpleEventCallback + 876
29 CoreFoundation 0x374cf51c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
30 CoreFoundation 0x374cf4be __CFRunLoopDoSource1 + 134
31 CoreFoundation 0x374ce30c __CFRunLoopRun + 1364
32 CoreFoundation 0x3745149e CFRunLoopRunSpecific + 294
33 CoreFoundation 0x37451366 CFRunLoopRunInMode + 98
34 GraphicsServices 0x33c10432 GSEventRunModal + 130
35 UIKit 0x311fdcce UIApplicationMain + 1074
36 MyLittleApplication 0x000f90ae 0xf8000 + 4270
37 MyLittleApplication 0x000f9048 0xf8000 + 4168
I suspect that it has something to do with notificationCenter and UIDeviceOrientationDidChangeNotifications I use. Is this true or am I looking in the wrong direction?
I am calling
[notificationCenter removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]
in viewDidUnload, this shuld be enough?
Can you please tell me what bug should i start looking for?
A:
This is a stacktrace you see the stack of methods called when the crash happened.
You start at the bottom and work yourself up to the top and search for a method call from your app (the stacktrace includes calls from the frameworks too (e.g. -[UIScrollView(Static) _adjustContentOffsetIfNecessary])).
The topmost method call from your app is likely the cause of your error and you can see what the system tried afterwards.
In your case it seems that you call popToViewController and the iOS frameworks try to animate the transition from one UIViewController to the next. There seems to be a problem for the table view to set its frame and scroll to the contentOffset.
This is likely to be caused by a memory error. You get this hint by examining Exception Type: EXC_BAD_ACCESS (SIGSEGV)
EXC_BAD_ACCESS is likely a hint that you try to acces a something which is no more in the memory -> already released.
In general I would recomment to activate exveption breakpoints in Xcode:
Have you set the exception breakpoint?
got to breakpoint editor pane
click on the x in the bottom left corner
choose add exception breakpoint
Now you should see a stacktrace if an exception occurs. And Xcode should be at the line where the crash happens.
The second thing you should get familiar with is the zombie mode in Instruments.
You can find a good introduction to the zombi mode in this video.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Prototype's Array.compact() filter recursively for multidimensional arrays?
I'm just wondering if Prototype's helper functions Array.compact() and Array.without() filter for multidimensional arrays. It doesn't look like it, and if so, was there a reason for this or is there another helper function in Prototype that does this?
A:
From the source code itself:
function compact() {
return this.select(function(value) {
return value != null;
});
}
So I guess the answer is no. But wouldn't it be easy to implement your own helper function to do this? just run compact in a loop on the sub arrays.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to range array in golang to not randomize predetermined key?
I have a trouble with my current golang's project.
I have another package in go that result an array with pretedermined key, example :
package updaters
var CustomSql map[string]string
func InitSqlUpdater() {
CustomSql = map[string]string{
"ShouldBeFirst": "Text Should Be First",
"ShouldBeSecond": "Text Should Be Second",
"ShouldBeThird": "Text Should Be Third",
"ShouldBeFourth": "Text Should Be Fourth"
}
}
And send it to main.go, to iterate each index and value, but the results is random (In my situation, I need that in sequence).
Real Case : https://play.golang.org/p/ONXEiAj-Q4v
I google why the golangs iterate in random way, and the example is using sort, but my array keys is predetermined, and sort is only for asc desc alphabet and number.
So, How can I achieve the way that arrays is not being randomize in iterate?
ShouldBeFirst = Text Should Be First
ShouldBeSecond = Text Should Be Second
ShouldBeThird = Text Should Be Third
ShouldBeFourth = Text Should Be Fourth
Anyhelp will appreciate, thanks.
A:
The language specification says
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.
To iterate over a fixed set of keys in a known order, store those keys in a slice and iterate through the slice elements.
var orderdKeys = []string{
"ShouldBeFirst",
"ShouldBeSecond",
"ShouldBeThird",
"ShouldBeFourth",
}
for _, k := range orderdKeys {
fmt.Println(k+" = "+CustomSql[k])
}
Another option is to use a slice of values:
type nameSQL struct {
name string
sql string
}
CustomSql := []nameSQL{
{"ShouldBeFirst", "Text Should Be First"},
{"ShouldBeSecond", "Text Should Be Second"},
{"ShouldBeThird", "Text Should Be Third"},
{"ShouldBeFourth", "Text Should Be Fourth"},
}
for _, ns := range CustomSql {
fmt.Println(ns.name+" = "+ns.sql)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
RestDocumentation class is deprecated, what should I use instead?
The documentation for org.springframework.restdocs.RestDocumentation states that it is deprecated.
I am trying to use the class in a JUnit test like this:
@Rule
public RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
What class should I be using instead?
A:
Try JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets")
| {
"pile_set_name": "StackExchange"
} |
Q:
$\lim_{(x,y) \to(0,0)}\sin(x - y)$
So I tried approaching from $x=0, y=0, y=x, y=x^2$, and $y=x^3$ and the resulting limits are all $0$ but apparently the limit doesn't exist. Why is this so?
A:
The limit exists and is zero. The easiest way to justify it is that $f(x,y) = \sin(x-y)$ is a compoisition of continuous functions and therefore is continuous itself. This means that $\lim_{x,y\to 0} f(x,y)= f(0,0) = 0$. I can even give you an epsilon-delta proof:
Let $\epsilon > 0$ be arbitrary, and let $\delta = \epsilon/2$. I can show that if $||(x,y)|| < \delta$, then $|f(x,y)| < \epsilon$: $||(x,y)|| < \delta$ implies that $|x|<\delta$ and $|y|<\delta$. Then:
$$|f(x,y)| = |\sin(x-y)| \le |x-y| \le |x|+|y| < \delta+\delta = 2\delta = \epsilon
$$
If your professor said that the limit doesn't exist, then unless the question wasn't stated correctly, I'm sad to say that he/she is wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como usar o componente SideNav da gem Materialize
Quero usar o SideNav do Materializecss, mas quando coloco ele em application.html.erb, utilizando a documentação as imagens não ficam no local que deveriam ficar.
Segue o código atual:
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>SisComSESA</title>
<meta charset="utf-8">
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<header>
<nav class="top-nav">
<div class="container">
<div class="nav-wrapper">
<%= link_to t('.application'), root_path, class: ['brand-logo center page-title'] %>
</div>
</div>
<a href="#" data-activates="slide-out" class="button-collapse show-on-large"><%= material_icon.menu %></a>
</nav>
<ul id="slide-out" class="side-nav">
<li><div class="user-view">
<div class="background">
<%= image_tag 'pav_esa.jpg' %>
</div>
<a href="#!user"><%= image_tag 'pav_esa.jpg', class: 'circle' %></a>
<a href="#!name"><span class="white-text name">John Doe</span></a>
<a href="#!email"><span class="white-text email">[email protected]</span></a>
</div></li>
<li><a href="#!"><i class="material-icons">cloud</i>First Link With Icon</a></li>
<li><a href="#!">Second Link</a></li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
</header>
<main>
<%= yield %>
</main>
<footer class="page-footer">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text"><%= t('.owner') %></h5>
<p class="grey-text text-lighten-4"><%= t('.mission') %></p>
</div>
<div class="col l4 offset-l2 s12">
<h5 class="white-text">Links</h5>
<ul>
<li>
<a class="grey-text text-lighten-3" href="https://webmail.esa.ensino.eb.br/">
<%= (material_icon.mail.md_18)%> <%= t('.email') %>
</a>
</li>
<li>
<a class="grey-text text-lighten-3" href="http://www.esa.ensino.eb.br">
<%= (material_icon.open_in_browser.md_18)%> <%= t('.site') %>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
2017
<a class="grey-text text-lighten-4 right" href="mailto:[email protected]"><%= (material_icon.report_problem.md_18)%> <%= t('.contact')%></a>
</div>
</div>
</footer>
</body>
</html>
application.scss
@import "materialize/components/color";
// ==========================================================================
// Materialize variables
// ==========================================================================
//
// Table of Contents:
//
// 1. Colors
// 2. Badges
// 3. Buttons
// 4. Cards
// 5. Collapsible
// 6. Chips
// 7. Date + Time Picker
// 8. Dropdown
// 9. Fonts
// 10. Forms
// 11. Global
// 12. Grid
// 13. Navigation Bar
// 14. Side Navigation
// 15. Photo Slider
// 16. Spinners | Loaders
// 17. Tabs
// 18. Tables
// 19. Toasts
// 20. Typography
// 21. Footer
// 22. Flow Text
// 23. Collections
// 24. Progress Bar
// 1. Colors
// ==========================================================================
$primary-color: color("teal", "darken-4") !default;
$primary-color-light: lighten($primary-color, 15%) !default;
$primary-color-dark: darken($primary-color, 15%) !default;
$secondary-color: color("teal", "lighten-1") !default;
$success-color: color("green", "base") !default;
$error-color: color("red", "base") !default;
$link-color: color("light-blue", "darken-1") !default;
// 2. Badges
// ==========================================================================
$badge-bg-color: $secondary-color !default;
$badge-height: 22px !default;
// 3. Buttons
// ==========================================================================
// Shared styles
$button-border: none !default;
$button-background-focus: lighten($secondary-color, 4%) !default;
$button-font-size: 1rem !default;
$button-icon-font-size: 1.3rem !default;
$button-height: 36px !default;
$button-padding: 0 2rem !default;
$button-radius: 2px !default;
// Disabled styles
$button-disabled-background: #DFDFDF !default;
$button-disabled-color: #9F9F9F !default;
// Raised buttons
$button-raised-background: $secondary-color !default;
$button-raised-background-hover: lighten($button-raised-background, 5%) !default;
$button-raised-color: #fff !default;
// Large buttons
$button-large-icon-font-size: 1.6rem !default;
$button-large-height: $button-height * 1.5 !default;
// Flat buttons
$button-flat-color: #343434 !default;
$button-flat-disabled-color: lighten(#999, 10%) !default;
// Floating buttons
$button-floating-background: $secondary-color !default;
$button-floating-background-hover: $button-floating-background !default;
$button-floating-color: #fff !default;
$button-floating-size: 40px !default;
$button-floating-large-size: 56px !default;
$button-floating-radius: 50% !default;
// 4. Cards
// ==========================================================================
$card-padding: 24px !default;
$card-bg-color: #fff !default;
$card-link-color: color("orange", "accent-2") !default;
$card-link-color-light: lighten($card-link-color, 20%) !default;
// 5. Collapsible
// ==========================================================================
$collapsible-height: 3rem !default;
$collapsible-line-height: $collapsible-height !default;
$collapsible-header-color: #fff !default;
$collapsible-border-color: #ddd !default;
// 6. Chips
// ==========================================================================
$chip-bg-color: #e4e4e4 !default;
$chip-border-color: #9e9e9e !default;
$chip-selected-color: #26a69a !default;
$chip-margin: 5px !default;
// 7. Date + Time Picker
// ==========================================================================
$datepicker-display-font-size: 2.8rem;
$datepicker-weekday-color: rgba(0, 0, 0, .87) !default;
$datepicker-weekday-bg: darken($secondary-color, 7%) !default;
$datepicker-date-bg: $secondary-color !default;
$datepicker-year: rgba(255, 255, 255, .7) !default;
$datepicker-focus: rgba(0,0,0, .05) !default;
$datepicker-selected: $secondary-color !default;
$datepicker-selected-outfocus: desaturate(lighten($secondary-color, 35%), 15%) !default;
$timepicker-clock-color: rgba(0, 0, 0, .87) !default;
$timepicker-clock-plate-bg: #eee;
// 8. Dropdown
// ==========================================================================
$dropdown-bg-color: #fff !default;
$dropdown-hover-bg-color: #eee !default;
$dropdown-color: $secondary-color !default;
$dropdown-item-height: 50px !default;
// 9. Fonts
// ==========================================================================
$roboto-font-path: "../fonts/roboto/" !default;
// 10. Forms
// ==========================================================================
// Text Inputs + Textarea
$input-height: 3rem !default;
$input-border-color: color("grey", "base") !default;
$input-border: 1px solid $input-border-color !default;
$input-background: #fff !default;
$input-error-color: $error-color !default;
$input-success-color: $success-color !default;
$input-focus-color: $secondary-color !default;
$input-font-size: 1rem !default;
$input-margin-bottom: 20px;
$input-margin: 0 0 $input-margin-bottom 0 !default;
$input-padding: 0 !default;
$input-transition: all .3s !default;
$label-font-size: .8rem !default;
$input-disabled-color: rgba(0,0,0, .26) !default;
$input-disabled-solid-color: #BDBDBD !default;
$input-disabled-border: 1px dotted $input-disabled-color !default;
$input-invalid-border: 1px solid $input-error-color !default;
$placeholder-text-color: lighten($input-border-color, 20%) !default;
// Radio Buttons
$radio-fill-color: $secondary-color !default;
$radio-empty-color: #5a5a5a !default;
$radio-border: 2px solid $radio-fill-color !default;
// Range
$range-height: 14px !default;
$range-width: 14px !default;
$track-height: 3px !default;
// Select
$select-border: 1px solid #f2f2f2 !default;
$select-background: rgba(255, 255, 255, 0.90) !default;
$select-focus: 1px solid lighten($secondary-color, 47%) !default;
$select-padding: 5px !default;
$select-radius: 2px !default;
$select-disabled-color: rgba(0,0,0,.3) !default;
// Switches
$switch-bg-color: $secondary-color !default;
$switch-checked-lever-bg: desaturate(lighten($secondary-color, 25%), 25%) !default;
$switch-unchecked-bg: #F1F1F1 !default;
$switch-unchecked-lever-bg: #818181 !default;
$switch-radius: 15px !default;
// 11. Global
// ==========================================================================
// Media Query Ranges
$small-screen-up: 601px !default;
$medium-screen-up: 993px !default;
$large-screen-up: 1201px !default;
$small-screen: 600px !default;
$medium-screen: 992px !default;
$large-screen: 1200px !default;
$medium-and-up: "only screen and (min-width : #{$small-screen-up})" !default;
$large-and-up: "only screen and (min-width : #{$medium-screen-up})" !default;
$extra-large-and-up: "only screen and (min-width : #{$large-screen-up})" !default;
$small-and-down: "only screen and (max-width : #{$small-screen})" !default;
$medium-and-down: "only screen and (max-width : #{$medium-screen})" !default;
$medium-only: "only screen and (min-width : #{$small-screen-up}) and (max-width : #{$medium-screen})" !default;
// 12. Grid
// ==========================================================================
$num-cols: 12 !default;
$gutter-width: 1.5rem !default;
$element-top-margin: $gutter-width/3 !default;
$element-bottom-margin: ($gutter-width*2)/3 !default;
// 13. Navigation Bar
// ==========================================================================
$navbar-height: 64px !default;
$navbar-line-height: $navbar-height !default;
$navbar-height-mobile: 56px !default;
$navbar-line-height-mobile: $navbar-height-mobile !default;
$navbar-font-size: 1rem !default;
$navbar-font-color: #fff !default;
$navbar-brand-font-size: 2.1rem !default;
// 14. Side Navigation
// ==========================================================================
$sidenav-font-size: 14px !default;
$sidenav-font-color: rgba(0,0,0,.87) !default;
$sidenav-bg-color: #fff !default;
$sidenav-padding: 16px !default;
$sidenav-item-height: 48px !default;
$sidenav-line-height: $sidenav-item-height !default;
// 15. Photo Slider
// ==========================================================================
$slider-bg-color: color('grey', 'base') !default;
$slider-bg-color-light: color('grey', 'lighten-2') !default;
$slider-indicator-color: color('green', 'base') !default;
// 16. Spinners | Loaders
// ==========================================================================
$spinner-default-color: $secondary-color !default;
// 17. Tabs
// ==========================================================================
$tabs-underline-color: $primary-color-light !default;
$tabs-text-color: $primary-color !default;
$tabs-bg-color: #fff !default;
// 18. Tables
// ==========================================================================
$table-border-color: #d0d0d0 !default;
$table-striped-color: #f2f2f2 !default;
// 19. Toasts
// ==========================================================================
$toast-height: 48px !default;
$toast-color: #323232 !default;
$toast-text-color: #fff !default;
// 20. Typography
// ==========================================================================
$off-black: rgba(0, 0, 0, 0.87) !default;
// Header Styles
$h1-fontsize: 4.2rem !default;
$h2-fontsize: 3.56rem !default;
$h3-fontsize: 2.92rem !default;
$h4-fontsize: 2.28rem !default;
$h5-fontsize: 1.64rem !default;
$h6-fontsize: 1rem !default;
// 21. Footer
// ==========================================================================
$footer-bg-color: $primary-color !default;
// 22. Flow Text
// ==========================================================================
$range : $large-screen - $small-screen !default;
$intervals: 20 !default;
$interval-size: $range / $intervals !default;
// 23. Collections
// ==========================================================================
$collection-border-color: #e0e0e0 !default;
$collection-bg-color: #fff !default;
$collection-active-bg-color: $secondary-color !default;
$collection-active-color: lighten($secondary-color, 55%) !default;
$collection-hover-bg-color: #ddd !default;
$collection-link-color: $secondary-color !default;
$collection-line-height: 1.5rem !default;
// 24. Progress Bar
// ==========================================================================
$progress-bar-color: $secondary-color !default;
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
.footer-copyright {
font-size: 14px;
}
@import "materialize";
@import "material_icons";
O código da aplicação está em github
A:
Como estava usando a Gem materialize-sass na versão 0.97.8 o erro ocorria hoje depois de atualizar para a Gem na versão 0.99 o erro deixou de ocorrer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding 'using' keyword : C++
Can someone please explain below output:
#include <iostream>
using namespace std;
namespace A{
int x=1;
int z=2;
}
namespace B{
int y=3;
int z=4;
}
void doSomethingWith(int i) throw()
{
cout << i ;
}
void sample() throw()
{
using namespace A;
using namespace B;
doSomethingWith(x);
doSomethingWith(y);
doSomethingWith(z);
}
int main ()
{
sample();
return 0;
}
Output:
$ g++ -Wall TestCPP.cpp -o TestCPP
TestCPP.cpp: In function `void sample()':
TestCPP.cpp:26: error: `z' undeclared (first use this function)
TestCPP.cpp:26: error: (Each undeclared identifier is reported only once for each function it appears in.)
A:
I have another error:
error: reference to 'z' is ambiguous
Which is pretty clear for me: z exists in both namespaces, and compiler don't know, which one should be used. Do you know? Resolve it by specifying namespace, for example:
doSomethingWith(A::z);
A:
using keyword is used to
shortcut the names so you do not need to type things like std::cout
to typedef with templates(c++11), i.e. template<typename T> using VT = std::vector<T>;
In your situation, namespace is used to prevent name pollution, which means two functions/variables accidently shared the same name. If you use the two using together, this will led to ambiguous z. My g++ 4.8.1 reported the error:
abc.cpp: In function ‘void sample()’:
abc.cpp:26:21: error: reference to ‘z’ is ambiguous
doSomethingWith(z);
^
abc.cpp:12:5: note: candidates are: int B::z
int z=4;
^
abc.cpp:7:5: note: int A::z
int z=2;
^
which is expected. I am unsure which gnu compiler you are using, but this is an predictable error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript counting adaptive table rows
I am trying to learn JavaScript; this is what I made for a test. My problem is that I want to count my table rows, but when I remove a table name it should adapt the table row numbers.
Is there someone who can tell me how I should or could do this? If you have a comment about my coding please give it as I want to learn as much as possible.
var count = 0;
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
var tableNr = document.getElementById("tableNr");
// input fields Variable
var firstName = document.getElementsByName("firstName")[0];
var lastName = document.getElementsByName("lastName")[0];
var Age = document.getElementsByName("Age")[0];
var Country = document.getElementsByName("Country")[0];
var AgeCheck = document.myForm.Age.valueOf;
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if( document.myForm.firstName.value == "" ) {
alert( "Please provide your first name!" );
document.myForm.firstName.focus() ;
return false;
}
// last name field check + error message
if( document.myForm.lastName.value == "" ) {
alert( "Please provide your last name!" );
document.myForm.lastName.focus() ;
return false;
}
// age field check + error message
if( isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100 ){
alert( "Please provide your age!");
return false;
}
// country select list check + error message
if( document.myForm.Country.value == "chooseCountry" ) {
alert( "Please provide your country!" );
return false;
}
// if evry thing is true return a value of true
return true;
}
function tableFunction() {
// if validate is true go
if( validate() ){
// count to see how many row's there are added
count++;
// making a new Row
var newRow = document.createElement("tr");
// adding the tow to the Table
table.appendChild(newRow);
// adding a class and a count-id to the Row
newRow.className = "tableRow";
newRow.setAttribute ("id", count);
// adding 4 td to the tr
for(i = 0; i < 5; i++ ){
var newData = document.createElement("td");
newRow.appendChild(newData);
newData.className = "tableData";
// check the td count and place data in.
if(i == 0){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = count;
} else if (i == 1) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = firstName.value;
} else if (i == 2) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = lastName.value;
} else if (i == 3) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Age.value;
} else if (i == 4){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Country.value;
}
}
}
}
function removeTableRow(){
i = tableNr.value;
// if there is no table number filled in show a error alert
if( i == "" ) {
alert( "Please provide a table number!" );
tableNr.focus() ;
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if( row == undefined ){
alert( "this row number is not in the table" );
return false;
}
row.remove(row.selectedIndex);
}
removeRowBtn.onclick = function() {removeTableRow()};
btn.onclick = function(){ tableFunction()};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<tbody id="table">
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName">
<input type="text" name="lastName" placeholder="lastName">
<input type="text" name="Age" placeholder="Age">
<select name="Country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
A:
Change
row.remove(row.selectedIndex);
to
row.remove(row.selectedIndex);
var rows = document.querySelectorAll("#table tr");
for (var i = 1; i < rows.length; i++) { rows[i].cells[0].innerText = i; }
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting the word out
Hi all,
The StackExchange team is starting in on ideas for getting math.SE some publicity. Beyond "what websites to advertise on," which was the focus of the previous publicity meta discussion, I'd like to hear any ideas you have on types of events, conferences, etc., to promote the site at (including what communities -- math, math education, general education, etc. -- we want to target and good people to get in touch with in those communities). Logo thoughts, face-to-face events we could organize, etc.--it's all game here.
The slightly-overblown-but-relevant section from the generic SE 2.0 site FAQ:
This is rapidly becoming a hot issue across the entire network: how to promote your site and how to reach out to the experts and pundits in your industry. We can come up with budgets and promotions but — more than any other issue raised here — the means and ideas about how to reach your target audience HAS TO come from you and your community. Has to. Has to, has to, has to! We simply are not experts in your field. We don’t have the the connections nor the experience you bring to the table. You are both our evangelist and our ambassador
A:
I would love to reach out to teachers. My vision of the ideal math.SE user is a bright high school student who is trying to do some math outside of school but running into difficulties due to lack of resources (for example, they want to understand something in a Wikipedia article but don't have access to any of the references). Teachers who know such students should be encouraged to redirect them here. But I don't have any particularly bright ideas for doing this. (Katie, maybe we should ask Louis about this.)
A:
I've told several friends (mostly undergraduate math majors) about math.SE, but I would imagine word-of-mouth is rather inefficient. It might be possible to write an article on the MAA website, kind of like how a few people wrote an article about MO for the AMS. (I don't know if the article actually got published though.) At least if math.SE grows significantly, then the MAA is probably the appropriate venue, since this website is intended to be at an undergraduate level. Also, I think someone posted a link on Aops, which is (or was) the usual gathering place for bright high-schoolers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can yeast in a primary fermentation of wine be used as a source of yeast for new fermentation?
So if I were to pitch bread yeast, and get to primary fermentation, which as I understand it, is the point at which regular cellular respiration can no longer continue due to a lack of oxygen , which is needed for the electron transport chain. Therefore the yeast switch to fermentation, which produces my desired product, ethanol.
But as I understand it, at this state the yeast are no longer reproducing and are in a survival mode.
Therefore if I were to cut a 2$L$ bottle of my primary ferment in half, and then add more sugar and water to the now separate 1$L$ bottles, and oxygen (if possible), up to 2$L$, would I be able to have the same amount of ethanol produced/would fermentation even occur?
I feel there would be diminishing returns even if it was possible, since yeast can only reproduce asexually so many times, which happens during stressful times, which this process might induce?
A:
Yes, it is possible to reuse yeast in both beer and wine fermentation - commercial brewers do it all the time for cost savings and batch reproducibility, and although I'm not as familiar with making wine, many sites including this one say it's perfectly fine, as long as the viability of the cells is high enough.
The yeast aren't necessarily in stress-induced survival mode during fermentation, they're just living (and metabolizing) anaerobically. They may no longer be reproducing, or doing it very infrequently, but they'll remain perfectly happy little buggers (that's a technical term) for quite a while. Give them more food (sugar), and they'll keep fermenting. What eventually stops the process with wine is the level of ethanol rising too high for their comfort. If you were to dilute the ethanol out with water, they'd keep going.
Now, I wouldn't recommend doing this indefinitely (some strains may exhibit genomic instability, etc.), but new batches can certainly be produced with existing pitches.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unicode 'OBJECT REPLACEMENT CHARACTER' added to start of first li in firefox
I'm guessing iv done something in jquery
works fine in safari but when i load in firefox it appends a weird obj string in a dotted box in front of all first li's
can someone please explain why it is there / tell me how to get rid of it
the only jquery on the page is a testimonial rotator i wrote:
<script>
var count = 1;
var quote = $("ul#quotes li");
var total = quote.size();
quote.hide()
quote.filter(':nth-child(1)').fadeIn()
window.setInterval(function(){
quote.fadeOut()
.delay(500)
count++;
if (count > total) { count = 1; }
quote.filter(':nth-child(' + count + ')').fadeIn()
}, 5000);
</script>
site is:
http://toukleywindowcleaning.com.au/
html as requested:
<div id="colTwo">
<div id="reasons">
<ul>
<li>5 REASONS WHY PEOPLE CHOOSE US</li>
<li>10 years experience</li>
<li>Fully Insured</li>
<li>All care taken for carpet & furnishings</li>
<li>We turn up on time</li>
<li>100% satisfaction guaranteed</li>
</ul>
</div>
</div>
OK as everyone is saying its not Jquery what is it? its not in my code
A:
This has nothing to do with your jquery code. if you view the source, the 'obj' is actually a special character that already exists in your HTML.
You can verify this by disabling javascript in your browser.
Check whatever is generating your HTML.. seems it is trying to render something that isnt a string.
| {
"pile_set_name": "StackExchange"
} |
Q:
issues with devicehelper.vb
does anyone know why i get the error "DirectCast(err, SetupApiError) = InWow64 {-536870347}" when running the code below? i get this error when it calls the SetupDiCallClassInstaller method on the line: Case SetupApiError.NoAssociatedClass To SetupApiError.OnlyValidateViaAuthenticode
Throw New Win32Exception("SetupAPI error: " & DirectCast(err, SetupApiError).ToString)
Dim result As Boolean = SetupDiSetClassInstallParams(handle, diData, params, Marshal.SizeOf(params))
If result = False Then Throw New Win32Exception
result = SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, diData)
If result = False Then
Dim err As Integer = Marshal.GetLastWin32Error
Select Case err
Case Is = SetupApiError.NotDisableable
Throw New ArgumentException("That device can't be disabled! Look in the device manager!")
Case SetupApiError.NoAssociatedClass To SetupApiError.OnlyValidateViaAuthenticode
Throw New Win32Exception("SetupAPI error: " & DirectCast(err, SetupApiError).ToString)
Case Else
Throw New Win32Exception
End Select
End If
A:
It is unhappy that you are calling SetupDiCallClassInstaller() from a 32-bit process running on the 64-bit version of Windows. That's easy to fix in a managed program. Right-click your EXE project, Properties, Compile tab, scroll down, Advanced Compile Options button. Change the Target CPU setting from x86 to AnyCPU.
| {
"pile_set_name": "StackExchange"
} |
Q:
Customizing WooCommerce product data label without plugin - WEIGHT
I'd like to change the product meta label from "Weight" to "Square Feet" in both the back end and front end.
I've tried this and a few [hundred] variations without success:
add_filter( 'woocommerce_register_post_type_product', 'custom_product_labels' );
function custom_product_labels( $args ) {
//
// change labels in $args['labels'] array
//
$args['labels']['_weight'] = 'Square Feet';
return $args;
I've successfully edited the UNITs with this:
add_filter( 'woocommerce_product_settings', 'add_woocommerce_dimension_units' );
function add_woocommerce_dimension_units( $settings ) {
foreach ( $settings as &$setting ) {
if ( $setting['id'] == 'woocommerce_dimension_unit' ) {
$setting['options']['feet'] = __( 'ft' ); // foot
}
if ( $setting['id'] == 'woocommerce_weight_unit' ) {
$setting['options']['sq ft'] = __( 'sq ft' ); // square feet
}
}
return $settings;
}
But I still can't figure out how to hook into the measurement labels to edit them. It's important to note that I don't want to ADD a meta unit of "Square Feet" because we already have thousands of products filled in with the sq ft data in the Weight field.
My quick workaround was to find the actual code on these pages and edit them. But it's a poor solution.
woocommerce/includes/admin/meta-boxes/views/html-product-data-shipping.php
woocommerce/includes/wc-formatting-functions.php
woocommerce/includes/wc-template-functions.php
Edit: Here is a page showing the use.
https://homedesigningservice.com/product/cape-house-plan-10034-cp/
Thank you in advance for saving my melting brain. :-)
A:
You may use this snippet
add_filter( 'gettext', 'theme_change_comment_field_names', 20, 3 );
function theme_change_comment_field_names( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
case 'Weight' :
$translated_text = __( 'Square Feet', $domain );
break;
case 'weight' :
$translated_text = __( 'Square Feet', $domain );
break;
}
return $translated_text;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
php loop through scandir to output different filename
I am attempting to generate a list of SQL commands that i will later insert. The only part at this time I seem to be stuck on is looping the file name. I need my scandir to loop through the nofilter directory and change $image each time a new line or sql query is given. I have the code and output below. Essentially no sql query should have the same $image being echo'd into it
for ($i=1351314000; $i<=1351400400; $i+= 14400) {
$images = scandir("/home/fb/public_html/post/uploads/nofilter/");
foreach($images as $image) {
}
//copy file over from no filter
$orig = "/home/fb/public_html/post/uploads/nofilter/".$image."";
$dest = "/home/fb/public_html/post/uploads/".$image."";
//copy($orig, $dest);
//output
echo "The number is " . $i . "<br />";
echo $image;
echo "<br>";
echo "<br>";
echo "<br>";
echo "
INSERT INTO `fb_fb`.`postcron_schedule` (
`id` ,
`status_message` ,
`link` ,
`photo_url` ,
`status_name` ,
`status_caption` ,
`status_description` ,
`uid` ,
`page_id` ,
`access_token` ,
`post_to` ,
`status_type` ,
`schedule_type` ,
`is_process` ,
`process_time` ,
`process_at` ,
`display_time` ,
`created_by`
)
VALUES (
NULL , '', '', '/home/fb/public_html/post/includes/../uploads/". $image ."', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '". $i ."', NULL , '". $i ."', '100000103637895'
);
";
echo "<br>";
echo "<br>";
}
The output looks like this
The number is 1351314000 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351314000', NULL , '1351314000', '100000103637895' );
The number is 1351328400 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351328400', NULL , '1351328400', '100000103637895' );
The number is 1351342800 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351342800', NULL , '1351342800', '100000103637895' );
The number is 1351357200 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351357200', NULL , '1351357200', '100000103637895' );
The number is 1351371600 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351371600', NULL , '1351371600', '100000103637895' );
The number is 1351386000 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351386000', NULL , '1351386000', '100000103637895' );
The number is 1351400400 8120925654_4041b7c50f_o.jpg
INSERT INTO `fb_fb`.`postcron_schedule` ( `id` , `status_message` , `link` , `photo_url` , `status_name` , `status_caption` , `status_description` , `uid` , `page_id` , `access_token` , `post_to` , `status_type` , `schedule_type` , `is_process` , `process_time` , `process_at` , `display_time` , `created_by` ) VALUES ( NULL , '', '', '/home/fb/public_html/post/includes/../uploads/8120925654_4041b7c50f_o.jpg', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '1351400400', NULL , '1351400400', '100000103637895' );
A:
Based on your comment, why not do it like this instead?
<php
$time = time();
$images = scandir("/home/fb/public_html/post/uploads/nofilter/");
foreach($images as $image) {
if ($image == '.' || $image == '..') {
continue;
}
$time += 14400; //add 4 hours every interval
//copy file over from no filter
$orig = "/home/fb/public_html/post/uploads/nofilter/".$image."";
$dest = "/home/fb/public_html/post/uploads/".$image."";
//copy($orig, $dest);
//output
echo "The number is " . $time . "<br />";
echo $image;
echo "<br>";
echo "<br>";
echo "<br>";
echo "
INSERT INTO `fb_fb`.`postcron_schedule` (
`id` ,
`status_message` ,
`link` ,
`photo_url` ,
`status_name` ,
`status_caption` ,
`status_description` ,
`uid` ,
`page_id` ,
`access_token` ,
`post_to` ,
`status_type` ,
`schedule_type` ,
`is_process` ,
`process_time` ,
`process_at` ,
`display_time` ,
`created_by`
)
VALUES (
NULL , '', '', '/home/fb/public_html/post/includes/../uploads/". $image ."', NULL , NULL , NULL , '0', '135031429962113', 'AAAGLZAMh7YSUBALRMCW60Rdol1kD80ZBNymqkgyQfBXDour2KsvVWKFcnZB9cU9OSLRMQjnEuKHZCTNoTZC4jf9GFtMU11BTD8JZAUFl0EVgZDZD', 'page', 'photo', 'schedule', '0', '". $time ."', NULL , '". $time ."', '100000103637895'
);
";
echo "<br>";
echo "<br>";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Consequences of a missing init?
In the process of porting a really badly coded iOS project to OS X, in which I make a point of preserving the model layer in order to (later) being able to keep the two versions in sync.
I do not currently have access to change the iOS code base - and don't particularly want to, either. Also, for all its faults, the model layer is tested and working.
If it ain't broke don't fix it, they say. So I guess my question is, is the code below broke or not? Notice there is no call to init after the alloc, and the class being instantiated is a direct subclass of NSObject.
...
SuspectClass *obj = [SuspectClass alloc];
obj.arrayProperty = [NSArray arrayWith...];
// etc.
...
I guess another way to put the question is if NSObject's init actually adds anything to an object?
A:
From the documentation of init in NSObject comes the official answer: "An object isn’t ready to be used until it has been initialized."
...and the practical answer: "The init method defined in the NSObject class does no initialization; it simply returns self."
:-)
Though functional, I don't think I'd trust a bare alloc given the number of places that warn that some form of init is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting array index of an element from it's parents children array list
My situation is that I have a table and within each table cells are a series of divs. Upon hovering over one of the divs in the table, I want the respective label to change it's background colour. The label has a separate div class than the others.
So, what I was thinking is that both the div that is going to be hovered over and the label are in the same table row (tr) element. The cell (td) that contains the label divs has a separate class from the other cells. The relationship of label divs to divs is 1:1.
Therefore, ParentCell.DivImHoveringOver[arrayIndex] = LabelCell.LabelDivIWantToChange[arrayIndex]. My point is that the array index of both elements from their parents children array list is the same, so I can use that to change the label div upon hovering over another div.
How do I do this?
I imagine it'd be something like this:
$('.table-day-detail-container').hover(
function() { //On hover entry
//Get array index of this element from it's parents children array list.
//Use that index to change background colour of another elements child node with that same array index
},
function() {//On hover exit
//Revert background colour
}
);
The elements within table cell I'll be hovering over::
<td class="table-day">
<div class="table-day-detail-container">Test1</div>
<div class="table-day-detail-container">Test2</div>
</td>
The elements within table cell which are labels to be modified upon hovering over respective element
<td class="table-day-label">
<div class="table-day-labels">Label1</div>
<div class="table-day-labels">Label2</div>
</td>
A:
You can use .index() like
$('.table-day-detail-container').hover(function () {
var $this = $(this),
index = $this.index();
$this.parent().next().children('.table-day-labels').eq(index).css('background', 'red');
}, function () {
var $this = $(this),
index = $this.index();
$this.parent().next().children('.table-day-labels').eq(index).css('background', '');
});
Demo: Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
How often I Can Update my Application on App Store?
How often I can update mobile application on App Store? Can I update every 2-3 days?
Thank you.
A:
Highly unlikely.
Apple's review time for a completely acceptable app update varies from less than 2 days to over 2 weeks, and a developer has no control over that length of time. That will limit the rate of updating any app to Apple's pace. Trying to update more often than this will put your update back at the end of the queue and slow down your approvals, and thus App store releases even more.
Somewhere, maybe a developer's talk, they may have recommended non-critical (for bugs) updates no more often than once per month.
For more frequent updates of content, see Apple's WWDC 2010 video on data driven app design, and consider having the app update certain content from your web site.
A:
Not really.
It usually takes Apple 7 days to review an app and if you upload a new update before the old one has been reviewed you go to the back of the queue. If you need to update your app more frequently than every ~7 days you should look into setting up a web-based update mechanism. Obviously, you won't be able to update any code this way, but you can update content as much as you like.
A:
No you cannot change it every 2-3 days, because there can be only one version in review of a given application. If a binary is submitted for review and you upload a new version, the old binary is thrown away and the review process starts over with the new version.
So you loose your position in the review queue each time you submit a new binary while the old one is already submitted but not accepted yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to perform a query with multiple greater/less than condition in CQL/cassandra?
I am writing a map app.
Once I got the bounds of map I have to query the DB for points.
The structure:
CREATE TABLE map.items (
id timeuuid,
type int,
lat double,
lng double,
rank int
)
and I would like to query like this:
select * from map.items
where type=1
and (lat > 30 and lat < 35)
and (lng > 100 and lng < 110)
order by rank desc
limit 10;
Newbie to cassandra, please help or provide references.
Thank you!
A:
CQL can only apply a range query on one clustering key, so you won't be able to do that directly in CQL.
A couple possible approaches:
Pair Cassandra with Apache Spark. Read the table into an RDD and apply a filter operation to keep only rows that match the ranges you are looking for. Then do a sort operation by rank. Then use collect() to gather and output the top ten results.
Or in pure Cassandra, partition your data by latitude. For example one partition might contain data points for all latitudes >= 30 and < 31, and so on. Your client would then do multiple queries of each latitude partition needed (i.e. 30, 31, 32, 33, and 34) and use a range query on longitude (using longitude as a clustering column). As results are returned, keep the highest ten ranked rows and discard the others.
| {
"pile_set_name": "StackExchange"
} |
Q:
Console log highlighted text from embedded website?
Hey guys I was wondering if there was a way to store highlighted text into a string variable from an embedded website? I haven’t found anything yet that has lead me to believe this is possible. Thanks in advance.
A:
See the answer that Tim Down gave to this similar question:
Get the Highlighted/Selected text
If by "embedded" you are referring to a frame or iframe, then you may have to alter the javascript selectors so that they select the content inside of the frame.
| {
"pile_set_name": "StackExchange"
} |
Q:
if statements with multiple conditions
I have been looking everywhere for the past week trying to figure this out. I have a small console application which asks the user a series of questions and stores the answers in variables. What I would like it to do is compare these answers against a series of conditions (welding procedures in this case) then select the procedure that matches all of the conditions. I tried doing this using if and statements but the program only uses my first If statement and does not try to compare anything... Clearly I am doing something quite wrong.. Here's my code:
Dim r As String
Dim a As String
Dim x As Double
Dim y As Double
Dim z As String
Dim v As String
Dim t As String
Dim b As String
Dim i As Double
Console.WriteLine("Is this for pipeline or facility?")
t = Console.ReadLine()
Console.WriteLine("Is this a repair procedure?")
b = Console.ReadLine()
Console.WriteLine("Is this CSA or ASME?")
r = Console.ReadLine()
Console.WriteLine("Registered with BCSA or ABSA?")
a = Console.ReadLine()
If a = "" Then
a = "bcsa"
End If
Console.WriteLine("Please Enter a Pipe Size")
x = Console.ReadLine()
Console.WriteLine("Please Enter a Wall Thickness")
y = Console.ReadLine()
Console.WriteLine("What is the Grade?")
z = Console.ReadLine()
If r = "ASME" Then
Console.WriteLine("Please Enter the Material Group e.x: Group 1, 2, 3..")
v = Console.ReadLine()
Else
v = 1000
End If
Console.WriteLine("Please enter an Impact Temperature (numerical values only please)")
i = Console.ReadLine()
If i = "" Then
i = "0"
End If
If t = "facility" And r = "asme" And a = "bcsa" & x <= 100 & x > 0 & y <= 25.4 & y >= 1.5748 & z = "p1" & v >= 1 & v <= 3 & i >= -40 Then
Console.WriteLine("I suggest the Weld Procedure MII-13-FAB11 Rev.1_BCSA")
Console.WriteLine("Would you like to open this file?")
If Console.ReadLine() = "yes" Then
Dim yes As String = "Q:\Macro Database\Use\MII-13-FAB11 Rev.1_BCSA Reg..pdf"
Process.Start(yes)
ElseIf Console.ReadLine() = "no" Then
Console.WriteLine("Okay fair enough. Thank you for using Citrus WPS Selection tool.")
End If
End If
'MII-13-FAB11 Rev.0_ABSA
If t = "facility" & r = "asme" & a = "absa" & x <= 100 & x > 0 & y <= 25.4 & y >= 1.5748 & z = "p1" & v >= 1 & v <= 3 & i >= -40 Then
Console.WriteLine("I suggest the Weld Procedure MII-13-FAB11 Rev.0_ABSA")
Console.WriteLine("Would you like to open this file?")
If Console.ReadLine() = "yes" Then
Dim yes As String = "Q:\Macro Database\Use\MII-13-FAB11 Rev.0_ABSA Reg..pdf"
Process.Start(yes)
ElseIf Console.ReadLine() = "no" Then
Console.WriteLine("Okay fair enough. Thank you for using Citrus WPS Selection tool.")
End If
End If
' MII-10-PL4 Rev.1
If t = "pipeline" & b = "no" & r = "csa" & a = "bcsa" & x <= 323.9 & x > 0 & y <= 12.84 & y >= 1.5 & z <= 386 & i >= -20 Then
Console.WriteLine("I suggest the Weld Procedure MII-10-PL4 Rev.1")
Console.WriteLine("Would you like to open this file?")
If Console.ReadLine() = "yes" Then
Dim yes As String = "Q:\Macro Database\Use\MII-10-PL4 Rev.1.pdf"
Process.Start(yes)
ElseIf Console.ReadLine() = "no" Then
Console.WriteLine("Okay fair enough. Thank you for using Citrus WPS Selection tool.")
End If
End If
I only included three procedures hopefully that gives the gist of it. so on the "If" statements I tried to use "And", "ElseOr", "&", "Or".. When I step into and run through this code in visual studio it Automatically defaults to the very weld first procedure. I looked at the Select Case blocks I am unsure how to sort this information with them? Any help is much appreciated! I'm really not too sure if what I am doing is even partially correct!
Thanks Everyone!
A:
You are using & when you should be using And (or AndAlso)
In VB.NET:-
The & Operator "Generates a string concatenation of two expressions."
The And operator "Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions"
I suspect that you actually want to use AndAlso which does the same as And but short-circuits the boolean expression to False if one of the results is false
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I deploy my application directly from appCode IDE to my iPhone and appleWatch?
I can do this in xcode easily but the debugger in xcode isn't the best. I can also deploy my app to my iPhone easily if I don't care about the appleWatch module. Is this a feature that just isn't in appCode yet?
A:
It doesn't support running watchKit apps on either the device or emulator yet. Here's the ticket from jetbrains: https://youtrack.jetbrains.com/issue/OC-11410
| {
"pile_set_name": "StackExchange"
} |
Q:
Ganache (from Truffle) hangs when started
When I run the file "ganache-1.0.1-x86_64.AppImage" that I downloaded from GitHub, Ganache just hangs showing the following screen with no more actions.
Is something missed?
I tried Ganache version 1.0.0 and and version 1.0.1.
My system contains:
Ubuntu 17.10 64bit
node v6.11.4
npm 3.5.2
Truffle v4.0.1 (core: 4.0.1)
Solidity v0.4.18 (solc-js)
Thanks,
A:
After investigation, I found that there was an application that uses the same default port of Ganache 7545.
Ganache should show error message clarifying that there is another application that uses the default running port. And better to suggest another port to start running with OR open Ganache settings page and notify to change the running port
I opened an issue at GitHub regarding this:
https://github.com/trufflesuite/ganache/issues/126
However, the solution is to close or change the port of the other application that uses the port 7545. Then you can run Ganache. After that, from Ganache settings, you can change the port that Ganache uses for any other free port you want.
Note: if Ganache crash for any reason and you hit the close button, it could be that it is still running in the background and still listening on (use) the port that it was running on. Therefore, you may need to kill (end) its process that is still running in the background.
| {
"pile_set_name": "StackExchange"
} |
Q:
CRUD commands to SQL database
I have a large application that focuses on using dependency injection. I've made a small (as I possibly could) piece of sample code to make this question more manageable. Essentially, I have a lot of boiler-plate code occurring for a number of commands that call stored procedures and return a response object back to the caller. I'd really like to find a more generic (if possible) way of doing this.
Normally, all of this code sits inside a Web Api and would have controllers executing the commands.
The complete code example is as follows (NOTE The code to refactor is at the very bottom, the rest is just supporting code):
Request/Response objects
Request
All requests inherit from BaseRequest which just contains the identifier for the api performing the request (this is verified within the proc):
public class BaseRequest
{
public string Identifier { get; set; }
}
Here is an example of a request class for a command:
public class ReadAssetRequest : BaseRequest
{
public int TypeId { get; set; }
public int OwnershipId { get; set; }
public int GroupId { get; set; }
public IEnumerable<int> StatusIds { get; set; }
}
Response
All responses inherit from BaseResponse which just contains a list of errors from the stored procedures (if any):
public class BaseResponse
{
public List<int> Errors { get; set; }
}
Here is an example of a response class for a command:
public class ReadAssetResponse : BaseResponse
{
public AssetInformation AssetInformation { get; set; }
}
This is the class for the object being returned:
public class AssetInformation
{
public int Id { get; set; }
public string Uprn { get; set; }
public string Address { get; set; }
public int? OSLocation { get; set; }
}
To talk to the database. There is a database helper:
DatabaseHelper Interface
public interface IDatabaseHelper
{
void ExecuteNonQuery(DatabaseCommandInfo data);
DataSet GetDataSet(DatabaseCommandInfo data);
DataTable GetDataTable(DatabaseCommandInfo data);
}
DatabaseHelper Class
public class DatabaseHelper : IDatabaseHelper
{
private readonly string connectionString;
public DatabaseHelper(string connectionString)
{
this.connectionString = connectionString;
}
public DataSet GetDataSet(DatabaseCommandInfo data)
{
var ds = new DataSet();
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = GetSqlCommand(data, con))
{
using (var rdr = cmd.ExecuteReader())
{
ds.Load(rdr, data.Option, data.TableNames);
}
cmd.Parameters.Clear();
}
}
return ds;
}
public DataTable GetDataTable(DatabaseCommandInfo data)
{
var dt = new DataTable();
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = GetSqlCommand(data, con))
{
using (var rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
cmd.Parameters.Clear();
}
}
return dt;
}
public void ExecuteNonQuery(DatabaseCommandInfo data)
{
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(data.StoredProcName, con))
{
cmd.CommandType = data.CommandType;
cmd.Parameters.AddRange(data.Parameters);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
private SqlCommand GetSqlCommand(DatabaseCommandInfo data, SqlConnection sqlConnection)
{
var cmd = new SqlCommand(data.StoredProcName, sqlConnection)
{
CommandType = data.CommandType
};
if(data.Parameters != null)
cmd.Parameters.AddRange(data.Parameters);
return cmd;
}
}
The database helper takes a DatabaseCommandInfo object so it knows what stored proc to call and with what SqlParameters:
DatabaseCommandInfo class
public class DatabaseCommandInfo
{
public string StoredProcName { get; private set; }
public SqlParameter[] Parameters { get; private set; }
public string[] TableNames { get; private set; }
public LoadOption Option { get; private set; }
public CommandType CommandType { get; set; }
public DatabaseCommandInfo(string storeProcName, SqlParameter[] spParams)
{
StoredProcName = storeProcName;
Parameters = spParams;
CommandType = CommandType.StoredProcedure;
}
public DatabaseCommandInfo(string storeProcName, SqlParameter[] spParams, string[] tableNames)
{
StoredProcName = storeProcName;
Parameters = spParams;
TableNames = tableNames;
Option = LoadOption.OverwriteChanges;
CommandType = CommandType.StoredProcedure;
}
}
Helper/Extension Methods
The command uses some Helper/Extension methods.
DataRowExtensions
Extension methods used to help retrieval of values from a DataRow:
public static class DataRowExtension
{
public static T GetValue<T>(this DataRow row, string columnName)
{
if (row != null && row.Table.Columns.Count > 0 && row[columnName] != DBNull.Value)
{
return (T)Convert.ChangeType(row[columnName], typeof(T));
}
return default(T);
}
public static T? GetNullableValue<T>(this DataRow row, string columnName) where T : struct
{
if (DBNull.Value.Equals(row[columnName]))
{
return null;
}
return (T)Convert.ChangeType(row[columnName], typeof(T));
}
}
Helper method to serialize object as XML
Used when a SQL parameter is not a primitive type, the value is passed as XML to the proc.
public static class ListExtensions
{
public static string IdsToXml(this IEnumerable<int> ids)
{
var idList = ids.ToList();
if (!idList.Any())
return new XElement("Ids").ToString();
var xmlElements = new XElement("Ids", idList.Select(i => new XElement("x", new XAttribute("i", i))));
return xmlElements.ToString();
}
public static string ToXml<T>(this T items)
{
return Serializer.SerializeObject(items);
}
}
Serializer class
public static class Serializer
{
public static string SerializeObject<T>(T toSerialize)
{
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
}
Actual command to refactor
With all the above supporting code. The following is an example of a simple command that contains boiler-plate code I'd like to refactor. The flow of the commands are:
Create an empty instance of the response object
Create the SqlParameters (Note the SQL parameter names are always the same as a request object property names. The data types are also identical for primitive types, anything else is serialized and passed as an XML parameter).
Create the DatabaseCommandInfo
Call a DatabaseHelper method and return a result (could be scalar object, DataSet/DataTable)
Populate the response object with the result from the database helper.
If a SqlException is thrown, store the error code and return the response with that code.
public class ReadAsset
{
private const string StoredProc = "up_Assets_ReadAsset";
private readonly IDatabaseHelper databaseHelper;
public ReadAsset()
{
databaseHelper = new DatabaseHelper("Data Source=.; Initial Catalog=Assets; integrated security=true;");
}
/// <summary>
/// Constructor used to inject dependencies
/// </summary>
/// <param name="databaseHelper"></param>
public ReadAsset(IDatabaseHelper databaseHelper)
{
this.databaseHelper = databaseHelper;
}
public ReadAssetResponse Execute(ReadAssetRequest request)
{
var response = new ReadAssetResponse();
var sqlParams = new[]
{
new SqlParameter("@TypeId", request.TypeId),
new SqlParameter("@OwnershipId", request.OwnershipId),
new SqlParameter("@GroupId", request.GroupId),
new SqlParameter("@StatusIds", request.StatusIds.ToXml()),
};
var dbCommandInfo = new DatabaseCommandInfo(StoredProc, sqlParams, new[] {"AssetInfo"});
try
{
var dataTable = databaseHelper.GetDataTable(dbCommandInfo);
response.AssetInformation = new AssetInformation();
if (DataTableIsNotPopulated(dataTable))
return response;
var row = dataTable.Rows[0];
response.AssetInformation.Id = row.GetValue<int>("Id");
response.AssetInformation.Address = row.GetValue<string>("Address");
response.AssetInformation.Uprn = row.GetValue<string>("Uprn");
response.AssetInformation.OSLocation = row.GetNullableValue<int>("OSLocation");
}
catch (SqlException sqlException)
{
response.Errors = new List<int> {sqlException.ErrorCode};
}
return response;
}
private static bool DataTableIsNotPopulated(DataTable dataTable)
{
return dataTable == null || dataTable.Rows == null || dataTable.Rows.Count != 1;
}
}
I haven't included the database information (i.e. table/procs, etc) as it is not relevant or required here.
A:
Don't do this:
public DatabaseCommandInfo(string storeProcName, SqlParameter[] spParams)
{
StoredProcName = storeProcName;
Parameters = spParams;
CommandType = CommandType.StoredProcedure;
}
public DatabaseCommandInfo(string storeProcName, SqlParameter[] spParams, string[] tableNames)
{
StoredProcName = storeProcName;
Parameters = spParams;
TableNames = tableNames;
Option = LoadOption.OverwriteChanges;
CommandType = CommandType.StoredProcedure;
}
Instead, use constructor chaining:
public DatabaseCommandInfo(string storeProcName, SqlParameter[] spParams)
: this(storeProcName, spParams, new string[])
{
}
The same is true for ReadAsset:
public ReadAsset()
: this(new DatabaseHelper("Data Source=.; Initial Catalog=Assets; integrated security=true;"))
{
}
The code isn't consistent: row[columnName] != DBNull.Value vs DBNull.Value.Equals(row[columnName]).
Why is this checked: row.Table.Columns.Count > 0 ?
In both GetValue and GetNullableValue you repeatedly call row[columnName]. Call it once and store the value in a variable and work with that variable.
In IdsToXml the element name "Ids" is used twice, so ideally it should be a const.
Your list of SqlParameter is missing the SqlDbType. I'd prefer this:
var sqlParams = new[]
{
new SqlParameter("@TypeId", SqlDbType.Int).Value = request.TypeId,
Now, looking at your "problem": it is inevitable that there has to be some place where you need to actually do something specific. In this case there's ReadAsset where you get the ReadAssetRequest, convert that to sqlParams and dbCommandInfo, use these to try to get a dataTable from the databaseHelper, convert that to a ReadAssetResponse.
I'm sure some of that can be moved to a Helper class or a base class, and if you're really hardcore you can:
build a mapper that can take any Request class and convert it to a list of SqlParameters etc. via reflection.
Perhaps the names of the SqlParameters are the same as the name of the properties, and if they aren't there's an Attribute on top of the property.
The name of the stored proc can be in a dictionary somewhere, with the type of the Request as the key.
And another mapper can convert the datatable to the Response object.
Even that DataTableIsNotPopulated check could be configured somewhere (because now you require a single result, but another response might require multiple results), etc.
Which means you perhaps wouldn't need a ReadAsset class anymore, since all of the actions inside it are actually a bunch of configurations used by helper classes. And thus instead of adding a single Asset class you now need to remember to add various configurations at various places.
Is that an improvement? I've worked with code like that, and while I did admire it, at times I did feel like Alice falling down the rabbit hole, ending up with dozens of code pages open in Visual Studio trying to figure out what needed to be altered where in order to get all of the components to play nice. And three months later I again needed to re-acquaint myself with the system before I could add another configuration.
Now, I can't say I'm a big fan of the code you show us here. The usage of arrays instead of IEnumerable<>, the apparent mixing of UI (request, response) and db (SqlParameter, DataTable),... I'd expect the db-related code to be in a separate layer and that you'd work with business entities. Why not use Entity Framework instead of mapping datatables to your custom classes? And do you really need to catch SqlExceptions?
| {
"pile_set_name": "StackExchange"
} |
Q:
Java eclipse I want to open the form like tab
Java eclipse: I want to open the form as shown below
http://i.stack.imgur.com/U0wT5.png
A:
You want to make your program look like that? With tabs? If that's the case, use a tabbed pane.
link: https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX children vs items
Why in JavaFX some controls and layout has "children" property, when other has "items" property for essentailly same purpose? Is there any philosophy behind or may be some technical difference?
A:
The getChildren() method is defined in Parent, and consequently inherited by all subclasses of Parent, including Pane, and Control. The implementation of this method in Parent returns an unmodifiable list of child nodes (so it can be used for navigation through the scene graph, but cannot be used to manipulate what is contained in the parent).
The Pane class, and its subclasses, are designed to allow you to lay out other nodes in the scene graph. So Pane overrides getChildren() to return a modifiable list of these nodes: essentially the functionality of a Pane is to allow you to add nodes to it and remove them later if you need. The Pane subclasses position these nodes in various ways.
The Control class is a subclass of Parent, as controls contain other nodes. (E.g. a ComboBox contains a label or text field (if it's editable), and a button for displaying the drop down list.) Control inherits its getChildren() method from Parent, so it returns an unmodifiable list of the child nodes, but doesn't allow you to change that list (because if you removed nodes from a control, it would no longer behave in the way that control was designed to behave).
Some controls are designed to display other content. Trivially, a Label or Button can have a graphic, which is any node. The API for these classes allows you to change that node (via setGraphic()).
More complex controls allow you to add and remove a collection of nodes, as part of their intended functionality. So for example a SplitPane allows you to add as many nodes as you like, and remove them if you need. However, these are not the only nodes contained in the SplitPane. So the getChildren() method still has its implementation from the superclass: it returns an unmodifiable list of all the child nodes of the split pane: that includes the items you add, and the dividers (and potentially other things too). On the other hand, the getItems() method returns the list of nodes that you are allowed to change: so you can remove an item by calling splitPane.getItems().remove(...) (and the split pane will remove the corresponding divider from its child list as well).
Other complex controls have getItems() methods that might return specific types: e.g. Menu.getItems() returns an ObservableList<MenuItem> (so you can't put a TableView in a menu, you can only put menu items in there). Similarly TabPane.getItems() returns an ObservableList<Tab>.
So in short, the two things have completely different functionality. getChildren() returns the list of child nodes for the parent: it allows you to inspect and navigate the scene graph. Parent subclasses that specifically choose to do so may return a modifiable list, allowing you to use them as general containers.
The getItems() methods that some Control classes define are there to define specific functionality of that particular control. They still have getChildren() methods, which will return a different list.
| {
"pile_set_name": "StackExchange"
} |
Q:
setattr accepts invalid identifiers
Here's what I mean:
>>> class Foo:
pass
>>> foo = Foo()
>>> setattr(foo, "@%#$%", 10)
>>> foo.@%#$%
SyntaxError: invalid syntax
>>> getattr(foo, "@%#$%")
10
>>> foo.__dict__
{'@%#$%': 10}
I looked it up and it has been brought up twice on the issue tracker for python 2:
https://bugs.python.org/issue14029
https://bugs.python.org/issue25205
And once for python 3:
https://bugs.python.org/issue35105
They insist it isn't a bug. Yet this behavior is quite obviously not intended; it's not documented in any version. What is the explanation for this? It seems like something that can be ignored easily, but that feels like sweeping it under the rug. So, is there any reason behind setattr's behavior or is it just a benign idiosyncrasy of python?
A:
A bug is something that happens when it's not supposed to happen, i.e., when there's some method of communication forbidding it. If there's no documentation stating this shouldn't happen then (at worst) it's an idiosyncrasy, not a bug.
There appears to be nothing in the Python documentation forbidding attribute names that are not usable with the dot notation (which is, after all, just syntactic sugar), like foo.@%#$%. The only mention is an example of where they are equivalent, specifically:
For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
The only restriction appears to be whether the class itself allows it:
The function assigns the value to the attribute, provided the object allows it.
In a more formal sense, the dot notation is specified here:
6.3.1. Attribute references
An attribute reference is a primary followed by a period and a name: attributeref ::= primary "." identifier.
The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. This production can be customized by overriding the __getattr__() method.
Note the identifier in that syntax, it has limits above and beyond those of actual attribute names, as per here, and PEP 3131 is a more detailed look at what is allowed (it was the PEP that moved identifiers into the non-ASCII world).
Since the limits of identifiers are more restrictive that what is allowed in strings, it makes sense that the getattr/setattr attribute names could be a superset of the ones allowed in dot notation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic variable for angular ng-click attribute
I am using the following way to use $scope variable ({{func}}() in this case) as function name in ng-click.
<button type="button" ng-click="{{func}}()">Call {{func}}</button></pre>
This works in angularjs-1.2.0rc3. See working plunkr here
Any future version from > 1.2.0rc3 throw this error
What's changed? How can I use the above syntax in current angular version?
A:
Ok first of all I do not recommend such a usage for ng-click because angularjs itself do not support this, but if you still want to use it such a way here is your solution...
<button type="button" ng-click="$eval(functionName)()">...</button>
where
$scope.f1 = function() {
...
};
//name of function as a string
$scope.functionName = "f1";
this is what your are looking for and here is your PLUNKER example...
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible that in a network,delay from router A to B is different from delay from router B to A
considering that metric is delay in distance vector routing algorithm,
is it possible that delay from router A to B is different from router B to A.
if yes, under which conditions??
thanks.
A:
The algorithm assumes the graph is bidirectional. Of course, it's possible for the delays to be different in each direction in practice: for example, if B is transmitting heavily to A, then traffic from A to B is likely to be faster than from B to A, since traffic from B will have to get in line at the end of a queue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use-cases for reflection
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
A:
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
A:
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
A:
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strip Characters Before Period If Filename Has Prefix in Bash
I have a directory that looks like this:
pages/
folder1/
folder1.filename1.txt
folder1.filename2.txt
folder2/
folder2.filename4.txt
folder2.filename5.txt
folder3/
filename6.txt
I want it to look like this:
pages/
folder1/
filename1.txt
filename2.txt
folder2/
filename3.txt
filename4.txt
folder3/
filename5.txt
With ls * | sed -e s/^[^.]*.// > /tmp/filenames.txt I get a file containing:
filename1.txt
filename2.txt
filename3.txt
filename4.txt
txt
How can I tell sed to ignore filenames of the form [filename].[suffix] and only look at filenames of the form [foldername].[filename].[suffix]?
The final script (as pointed out, the find command would simplify things, but this worked):
for folder in $(ls .)
do
if test -d $folder
then
pushd $folder
ls * | sed 's/.*\.\(.*\..*\)/\1/' > /tmp/filenames.txt
ls * > /tmp/current.txt
exec 3</tmp/current.txt
exec 4</tmp/filenames.txt
while read file <&3; read name <&4;
do
mv "$file" "$name"
done
rm /tmp/current.txt
rm /tmp/filenames.txt
popd
else
echo $folder "not a directory"
fi
done
exit 0
This page is now a community wiki. You can add more elegant solutions below:
for folder in $(ls .)
do
something better
A:
Give this a try:
sed 's/.*\.\(.*\..*\)/\1/'
You should really use find then you wouldn't need the check for "-d folder" or the temp file and execs or the while loop.
You can avoid the temporary file by using process substition:
while read line
do
echo $line
done < <(ls)
Another item of interest: your system may already have a Perl script called rename or prename which will rename files using a regular expression.
| {
"pile_set_name": "StackExchange"
} |
Q:
In highcharts how to format the number of percentage
Hi I want to show 7% instead of 7.0000000001% when I use point.percentage
I do not find the percentageDecimals in the documentation or any thing that could help.
A:
Try point.percentage.toFixed(0);
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving data from ajax call in controller
I have an ajax call that is sending some IDs to one of my controllers.
The jQuery that is running to do this is basically searching for elements that have an ID like notification-id- and then grabbing the IDs and storing them in a JavaScript variable.
When I alert() or console.log() this variable it prints out values like 1,2 for two notifications that I have on the page notification-id-1 and notification-id-2.
For my ajax call, I am simply doing the below:
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
I'm trying to test what my controller is receiving by doing dd($request->all()); however that is just returning:
array:1 [
"undefined" => ""
]
(The ajax call does run successfully)
How can I retrieve the ID values that are being sent in this ajax call inside my controller?
Edit: Full Script
<script type="text/javascript">
$(document).ready(function() {
var count = $('#notification-counter');
var new_notifications = $('#notification-new-counter');
$('#notification-drop-down').on('click', function() {
count.empty();
var notifications = $('[id^="notification-id-"]').map(function() {
return this.id.slice(16);
}).get();
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
});
});
</script>
A:
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: {'notifications':notifications},
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dynamically use a Vuetify component in vue-cli project
I'm experiencing a problem in my vue-cli created application. The following does not work:
<component :is="'v-text-field'"></component>
However a simple <v-text-field /> works great
The error is:
Unknown custom element: <v-text-field> - did you register the component correctly?
Does someone knows why? I can't reproduce it on codepen
A:
Are you using vuetify-loader with tree-shaking? If so, you may just want to import {VTextField} from 'vuetify/lib' and add components: { VTextField }
| {
"pile_set_name": "StackExchange"
} |
Q:
Random -2 "unaccept" on a question I didn't ask?
Somehow, I managed to get a -2 to my reputation on Stackoverflow.
The link it points to: https://stackoverflow.com/questions/145983/pitfalls-of-object-oriented-programming/3137250#3137250 (link to answer that isn't mine)
The reason: "Unaccept"
I don't think I was ever involved in this question at all, so where did this come from?
A:
You asked a question that was subsequently merged into the question you linked: when it was merged, the answer you accepted on your version of the question was unaccepted, and thus you lost the 2 reputation for accepting it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Build security acl replication scripts in AIX (need help to complete it)
The current scripts i have written so far:
#!/bin/ksh
rm -fR /tmp/aclget
cd /
find ./ -type d \
| grep -v "^./tmp/" \
| xargs -I {} mkdir -p "/tmp/aclget/{}"
find ./ \
| grep -v "^./tmp/" \
| xargs -I {} aclget -o "/tmp/aclget/{}.acl" "{}"
cd /tmp
tar -cvf acl.tar aclget
gzip acl.tar
To replicate the permission on another machine
#!/bin/ksh
cd /tmp
gunzip acl.tar
tar -xvf acl.tar
cd /tmp/aclget
find ./ -exec aclput -i {} `echo "{}" | sed "s/^\.//g"`
The problems i am having is that the tmp always goes out of space when building the list.
is it possible to make pipe so that it can work on the fly ?
update code after reading feedback and trying with some idea of uuencode, change after some testing. (probably kernel tuning is need for the 255 bytes limit in xargs)
Checking:
odmget -q "attribute=ncargs" PdAt
lsattr -El sys0 | grep ncargs
Tunning:
chdev -l sys0 -a ncargs=1024
Scripts:
#!/bin/ksh
cd /
find ./ -name "^./tmp/" -o \
-exec sh "aclget '{}' | uuencode - '/tmp/acl/{}.acl'" \; \
| gzip acl.uu.gz
anyone got idea on the the reverse part ? i have come up so far, need to cut the file down since uudecode can only decode the first file
#!/bin/ksh
gunzip acl.uu.gz | uudecode
cd /tmp
find ./ -exec aclput -i {} `echo "{}" | sed "s/^\.//g"`
A:
I never used aclget but here are some generic approaches you can use.
First you could do the work on chunks directory by directory and hope no single chunk is too big. Also you can optimize tar like:
tar -vc aclget | gzip -9 > myfile1.tar.gz
btw bzip and xz have much better compression ratio if needed.
Another approach could be instead of:
xargs -I {} aclget -o "/tmp/aclget/{}.acl" "{}"
to have a while loop like:
(
batch_idx=0
iterations=1
threshold=$(( 100 * 1024 * 1024 ))
while read -r FILE; do
aclget -o "/tmp/aclget/$FILE.acl" "$FILE"
tar uv -C /tmp/aclget -f acl.tar $FILE.acl
rm "/tmp/aclget/$FILE.acl"
if (( iterations%threshold == 0 )); then
mv acl.tar acl_$batch_idx.tar
gzip acl_$batch_idx.tar
(( batch_idx+=1 ))
iterations=0
fi
(( iterations+=1 ))
done
mv acl.tar acl_$batch_idx.tar
gzip acl_$batch_idx.tar
)
It is also very good to use find's -print0 option but then you would need to change the IFS variable within the while sub-shell. You need to test that though, hopefully it wont affect any of the other commands besides read.
You see, I'm not giving you a tested solution but I see you are more than capable to turn the above into working code. Regards!
update: forgot to tell you about the used pseudo-funciton filesize. It's very platform dependent what you have on your machines. If can use stat, wc, du and others.. see here for suggestions:
http://www.linuxquestions.org/questions/programming-9/file-size-using-bash-script-410766/
How to check size of a file?
update 2: I updated the while loop to be ksh (from aix7) compatible as well I avoid using filesize as a criterion. You would need to adjust threshold variable so it is large enough to to avoid big number of output files and sill fit into your free space.
| {
"pile_set_name": "StackExchange"
} |
Q:
Maintaining a Nat within a fixed range
I'd like to have a Nat that remains within a fixed range. I would like functions incr and decr that fail if they are going to push the number outside the range. This seems like it might be a good use case for Fin, but I'm not really sure how to make it work. The type signatures might look something like this:
- Returns the next value in the ordered finite set.
- Returns Nothing if the input element is the last element in the set.
incr : Fin n -> Maybe (Fin n)
- Returns the previous value in the ordered finite set.
- Returns Nothing if the input element is the first element in the set.
decr : Fin n -> Maybe (Fin n)
The Nat will be used to index into a Vect n. How can I implement incr and decr? Is Fin even the right choice for this?
A:
I guess the easiest way is to use some standard Fin↔Nat conversion functions from Data.Fin:
incr, decr : {n : Nat} -> Fin n -> Maybe (Fin n)
incr {n=n} f = natToFin (succ $ finToNat f) n
decr {n=n} f = case finToNat f of
Z => Nothing
S k => natToFin k n
| {
"pile_set_name": "StackExchange"
} |
Q:
Akka Send Delayed Message to self cannot Find implicit ExecutionContext
I am using Akka 2.1.4. I need one of my actors to send a delayed message to itself.
I have tried, from within the Actor's receive:
context.system.scheduler.scheduleOnce(1 second, self, msg)
However, it does not compile, since it cannot find the implicit ExecutionContext. Where can I get it from?.
NOTE: I am aware that the actual sender will not be my actor, but that is OK, since I don't need to know who the sender is.
A:
You could also do it like this:
class MyActor extends Actor{
import context._
...
}
This way you are assured that you are getting the dispatcher assigned to that actor in case it differs from the main dispatcher for the system (which is what you are getting with your solution).
A:
I think I have found it:
import myActorSystem.dispatcher
context.system.scheduler.scheduleOnce(1 second, self, msg)
Now it compiles.
| {
"pile_set_name": "StackExchange"
} |
Q:
How would someone most likely abbreviate "Michael" as a German speaker?
How would someone most likely abbreviate Michael as a German speaker? I am trying to translate something and am curious what Germans use as the short version of Michael. I'm guessing it is the same as in English and the answer is Mike but I could also see it going the other way.
A:
I'm from the decade where Michael was one of the most frequent names for boys, so I met my fair share of them. Personally, I found that this is one of the names that often remain unaltered, but with an abundance of "Michaels" in a class or group, abbreviations/nicknames were a simple way of distinguishing between them.
As it stands, abbreviations and nicknames follow no "standard", and many are regional or dialect versions of the name, but my first thoughts were:
Michi
That's what most of my peers are called.
Micha
Which avoids the diminuitive-like '-i' at the end.
Michl
Which is a variant mostly from the southern parts of Germany. Not necessarily an abbreviation, simply the dialect version. Often people are officially named in standard German but addressed in the dialect variant. Note that there is also the symbolic figure Deutscher Michel, representing "the German".
Some may choose the English versions
Mike
Mick
But when meeting someone with this name I would (instinctively) assume this to be the given name, not an abbreviation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Load a page and apply javascript in a single bookmark
I have a bookmark that opens my a google calendar page (http://www.google.com/calendar/renderOnline) and a bookmarklet that applies some javascript on it:
javascript:document.getElementById('gadgetcell').setAttribute('style','width:300px');document.getElementsByClassName('sn-frame')[0].setAttribute('style','width:300px');
Is there a way to combine these into a single bookmarklet so that i don't have to click twice all the time?
Thank you!
A:
You could use an extension to get the same behavior.
For example in Safari you would create a button that launches the URL and an injected script that runs your bookmarklet. GreaseMonkey and many other extensions frameworks can do similar things.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is mono's log file?
I'm having an issue with a program crashing on mono, I have an idea why but I can not confirm it as I can not find the log location for mono on ubuntu. I'm developing on windows however I'm deploying to a ubuntu server. So my question is, where is the standard log location for mono on ubuntu?
A:
I could not find a log file so I ended up opening a terminal in the file location and running mono via the terminal so the mono terminal wouldn't close straight away
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to run a Vaadin application on remote server
I am building a Vaadin application with Java. Here is the folder structure.
- com
-- my
--- WebTool
---- ToolUI.java
---- View_1.java
---- View_2.java
The entry point to the application is ToolUI.java and has the method init() that takes VaadinRequest as a parameter. It is this file where I add the views Views_1 and View_2 as views of the application and add navigations among them. Everything runs great when I run the application via the Eclipse IDE.
Now I have a requirement that I have to deploy this application on a remote server. So I created a war of the project and deployed on the server by the name
MyWebTool.war.
Now when I try running the war with the command
java -jar MyWebTool.war
it gives me the error: Can't execute war no main manifest attribute, in MyWebTool.war
I am not sure what to add the main class as since the init method gets invoked and sets the app running. So I put a blank main function inside the MyWebToolUI.java and added this dependency in the pom.xml file.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.my.WebTool.ToolUI</mainClass>
</manifest>
</archive>
<failOnMissingWebXml>false</failOnMissingWebXml>
<!-- Exclude an unnecessary file generated by the GWT compiler. -->
<packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
</configuration>
</plugin>
But now when trying to run the application it says Could not find or load main class com.my.WebTool.ToolUI
Can please somebody shed light on this? I don't know if I am missing something simple here but at this point, I am stuck. Thanks a lot.
A:
For running war packaged applications, you will need a servlet container.
The servlet container provides all the basic infrastructure needed to run java based web applications.
One of the most common ways to do this, is to deploy the war file to a tomcat installation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which finger should I use for the fourth valve of a piccolo trumpet?
I am kind of a beginner (and a self-learner) on the piccolo trumpet. I have seen people playing the instrument's fourth valve with their right hand little finger, and others with their left hand index. Is there a reason to choose one over the other, is there a configuration which definitely provides more endurance or agility in the long term?
A:
Depends on the way the instrument is constructed. Most piccolo trumpets, especially ones with piston valves, are designed for the valve to be played with the fourth finger of the right hand:
You can see that the 4th valve is even offset a hair to make it easier to reach.
Some rotary valve piccolos have extra spatulas that are operated with the left hand:
Picture from http://www.trevorjonesltd.co.uk
I'm having trouble finding a picture of a 4-valve picc with the 4th valve played with the left hand, but I know I've seen it. It's the same principle as a euphonium's fourth valve:
The thing about piccolo trumpets is that they're so small and the tubing is so tightly wrapped that there's often no comfortable way to hold them. So while I'm normally a stickler for holding an instrument properly, I think there's nothing wrong with operating a picc's 4th piston valve with the left hand. I say let it be a personal choice.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to submit form by GET method using js
I'm trying to pass values in the url through js but getting the error below
Uncaught RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
Javascript
$(document).on('submit','#adminProductFilter',function () {
var category_id = $('#category').val();
var prdouct_name = $('#productName').val();
var link = '{{url('/admin/products?:id')}}';
var url = link.replace(':id',"categories_id="+category_id+"&product="+prdouct_name);
$(this).attr('action',url);
$('#adminProductFilter').submit();
});
Form.php
<form class="form-inline form-validate" enctype="multipart/form-data" id="adminProductFilter">
{{csrf_field()}}
<div class="form-group">
<h5 style="font-weight: bold; padding:0px 5px; ">{{ trans('labels.FilterByCategory/Products') }}:</h5>
</div>
<div class="form-group" style="min-width: 220px">
<select class="form-control" name="categories_id" style="width: 100%" id="category">
<option value="">{{ trans('labels.SelectCategory') }}</option>
@foreach ($results['subCategories'] as $key=>$subCategories)
<option value="{{ $subCategories->id }}"
@if(isset($_REQUEST['categories_id']) and !empty($_REQUEST['categories_id']))
@if( $subCategories->id == $_REQUEST['categories_id'])
selected
@endif
@endif
>{{ $subCategories->name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<input type="text" name="product" class="form-control" id="productName"
@if(isset($_REQUEST['product']) and !empty($_REQUEST['product']))
value="{{ $_REQUEST['product'] }}"
@endif
placeholder="Products">
</div>
<button type="submit" class="btn btn-success">{{ trans('labels.Search') }}</button>
<a href="{{ URL::to('admin/products')}}" class="btn btn-danger">{{ trans('labels.ClearSearch') }}</a>
</form>
Route.php
Route::get('/products', 'AdminMasterProductsController@products');
When i click submit button it is showing url in the form action but the form is not getting submitted.
I just wanted to submit the form and get the result.
Please Help.
A:
You can change the attribute of submit button to 'button', give it an id.
<form class="form-inline form-validate" enctype="multipart/form-data" id="adminProductFilter">
{{csrf_field()}}
<div class="form-group">
<h5 style="font-weight: bold; padding:0px 5px; ">{{ trans('labels.FilterByCategory/Products') }}:</h5>
</div>
<div class="form-group" style="min-width: 220px">
<select class="form-control" name="categories_id" style="width: 100%" id="category">
<option value="">{{ trans('labels.SelectCategory') }}</option>
@foreach ($results['subCategories'] as $key=>$subCategories)
<option value="{{ $subCategories->id }}"
@if(isset($_REQUEST['categories_id']) and !empty($_REQUEST['categories_id']))
@if( $subCategories->id == $_REQUEST['categories_id'])
selected
@endif
@endif
>{{ $subCategories->name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<input type="text" name="product" class="form-control" id="productName"
@if(isset($_REQUEST['product']) and !empty($_REQUEST['product']))
value="{{ $_REQUEST['product'] }}"
@endif
placeholder="Products">
</div>
<button type="button" id='btn-submit' class="btn btn-success">{{ trans('labels.Search') }}</button>
<a href="{{ URL::to('admin/products')}}" class="btn btn-danger">{{ trans('labels.ClearSearch') }}</a>
</form>
And submit through event click.
$("#btn-submit").click(function(){
var category_id = $('#category').val();
var prdouct_name = $('#productName').val();
var link = '{{url('/admin/products?:id')}}';
var url = link.replace(':id',"categories_id="+category_id+"&product="+prdouct_name);
$("#adminProductFilter").attr('action',url);
$('#adminProductFilter').submit();
})
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server and generatd xml with xml auto, elements
I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into a sub-table node named the same as the table node it's already in (so say it's a table xyz, it'd be print("<xyz><node1></node1><xyz><generated-node-from-function></generated-node-from-function></xyz>");
No matter what I try (even directly manipulating a copy of the sql as generated by the app) it always seems to create this extra node layer, which causes problems later when we try to process this xml to extract the data later. Is there any particular property causing the xml generator in sql server to work this way, and is there any way to prevent it so I can keep the generated data node on the same level as the rest of the data for the table it's associated with?
Edit: renamed columns/tables in some cases but otherwise should be the same sql.
SELECT * FROM (SELECT column1,column2,column3,iduser,jstart,jstop,jbatchperiod,jinactive,processed,column4,lock,column5,batchticketmicr,machineid,sjobopex,szopexrefid,jreceived,jstartopex,jstopopex,idspecialmicr,idp2batchoriginal,stateflags,bcrossrefid,bidentifier1,bidentifier2,bidentifier3,bidentifier4,bidentifier5,idexport,idimport,rsahash FROM table1) table1
LEFT JOIN (SELECT column21,ienvelope,isort,column1,idtemplate,processed,column4,lock,envelopetypecode,szqueuesvisitedunique,exportdate,jcompleted,status,ipriority,idbankaccount,iprioritybeforerzbump,fstoredrecondata,cscountyid,column10,column11,checkbox1,checkbox2,column12,column13,column14,xxxempfein,column15,column16,originalenvelopeid,column17,column18,xxxoag,trackingnumber,csldc,ecrossrefid,postmark,routingflags,eidentifier1,eidentifier2,eidentifier3,eidentifier4,eidentifier5,idexport FROM envelope) envelope ON table1.column1=Envelope.column1
LEFT JOIN (SELECT column21,column22,isort,column23,processed,side,pagetypecode,rawmicrline,rawscanline,rawbarcode,exportid,szlocandconf,szlocandconfpagefields,idformtemplate,szparms,rawmarksense,audittrail,audittrailelectronic,pixheight,pixwidth,ocrattemptcounter,idspecialmicr,idpageexception,pagemodifierflags,column10,csldc,rejectdate,rejectuser,rejectqueue,fsupervisorreject,xxxempno,xxxtraceno,xxxemplcnt,checkbox1,keyword,templatealtered,templateflags,pidentifier1,pidentifier2,pidentifier3,pidentifier4,pidentifier5,isscanlinevalid,idexport,clickcount FROM Table2) Table2 ON Envelope.column21=Page.column21
LEFT JOIN (select column22, column21, dbo.Fileimagepath(column21, column22) as path from Table2) Fileimg ON Table2.column21=FileImg.column21 AND Table2.column22=FileImg.column22
WHERE Envelope.column21 = 8
FOR XML AUTO, ELEMENTS
Another edit: basically FileImg's results are getting wrapped in an extra set of Table2 tags inside existing table2 tab with the rest of the data.
Yet another Edit: Testing against another database with the same sql it worked correctly, it appears there is a bad setting in my database or the stored proc is different goes to investigate farther.
If that doesn't work I'll try some of the other suggestions above, thanks for the help so far :)
A:
Doing some further reserach, as of now it appears running a db in 2000 compat mode while on a 2005 sql server this problem is created, will not pin this until confirmed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Byte count for named, recursive lambda expressions in C# answers
I have been questioned about the byte count in my C# answer for the The Snail in the Well challenge. Usually C# answers only need to count the following bytes:
(a,b)=><do_something>
with the rest of the code being in the header or footer. So at first my answer was like this:
(a,b,c)=>a>b?1+f(a-b+c,b,c):1
Then Martin Ender noted that if I call a f method in my code, I should include that assignment in the code, so I changed it to
f=(a,b,c)=>a>b?1+f(a-b+c,b,c):1
Then Martin said that I should also declare the f variable and add the trailing ;, rendering my answer into something like this:
System.Func<int,int,int,int>f=null;f=(a,b,c)=>a>b?1+f(a-b+c,b,c):1;
At this point the answer is useless as there are shorter ways to solve the problem using standard, non-recursive functions.
Usually the declaration of the lambda expression goes in the header, that's why I left it there. But I understand this is a recursive function, so what should I include in the answer (and therefore in the byte count)?
A:
That structure is not self-contained
All the answers we expect must be self-contained.
The formulation f=<args>=><execution> is not self-contained.
Indeed, you can write
<type> f=<args>=><execution>
But C# doesn't allow the following construct:
foo.bar(f=<args>=><execution>);
This latter construct requires that f is typed before, like this:
<type> f;
foo.bar(f=<args>=><execution>);
So, while a lambda alone is self-contained, the structure f=<lambda> is not self-contained without the type of f, and is therefore not following the global rules of PPCG.
A:
If I'm not mistaken, (my search has failed me), a unnamed function literal answer is defined along the lines of
a block of code that evaluates to a callable value
So, if your submission is
<code>
You should be able to do one of the following (structures) to run your answer:
<type> <result> = (<code>).call(<params>);
<type> <name> = <code>;
<type> <result> = <name>.call(<params>);
Or, as a function answer, adding your code should (in a language-defined way) provide a callable binding which solves the problem.
In Python, f=lambda ... works because after its execution, a binding f exists which is a reusable callable binding which solves the question.
In C-like languages, <type> f() { ... } works because after its inclusion in a source file, a callable binding f exists which is a reusable solution to the question.
In Java/C# though, we've run into the issue of typing with our unnamed function. As in the related issue about typing lambdas, we allow just the literal because the question itself gives the context to infer the required type of the binding, and it's more consistent with other languages' scoring.
However, I don't think this should extend to when the function needs to be named. At that point, you are no longer submitting an answer as an unnamed function, but as a block of code that after inclusion defines a function binding.
f=<lambda> means nothing in C#. You need to provide a type to create a name binding in C#.
I think C# has an opinion on this as well:
Cannot assign lambda expression to an implicitly-typed variable
I was going to suggest the use of var, but C# disallows that, likely because of the discussed issues about typing a lambda.
My position is that if you need to name the function submission, you need to provide a proper function submission, that is: code that, when included, defines a callable name binding which can be used to solve the question.
An unnamed function expression needs to be that: an unnamed function expression that I assign to a variable (and thus take the typing responsibility).
TL;DR this shouldn't be an allowed submission format, use a proper function declaration if you need to call it.
I agree with the summary in this answer, with the extension of allowing combining any number of defined functions with one anonymous function which is the submission.
TL;DR TL;DR: Oliver's answer expresses the same sentiment and I agree with it fully.
A:
If a lambda is to be called it should show what it is assigned to, so the following:
f=<args>=><someRecursiveWork>
If we view the code needing to compile this it looks like the following, note the trailing semi-colon:
System.Func<input...N, output> f = null;
f=<args>=><someRecursiveWork>;
However, we usually don't require trailing semi-colons for C# lambdas so I believe we should follow that rule here too.
On a side note the top comment should also be applied to if an answer uses multiple lambdas to delegate some work off:
g=<args>=><someWork>
<args>=><someWorkWithG>
Note how what would be f is not showing what it is assigned too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Symbol Table References are Null - REST Call
I am trying to get the references for methods defined in Apex Class via Tooling API ( by REST Call ). Please find the information of the REST Call below ( using Workbench )
When i make the above REST call, i am able to get lot of information including "Symbol Table" but for all the classes references is coming as Null. But almost all the classes are being referred by some other class, so ideally it should be populated.
EDIT
Screenshot of the Symbol Table having Null References
Can anyone provide pointers why its not fetching the references?
A:
RE: Mystery "type" field
The Tooling API documentation is a little shallow in this area, it does not go into the specific meaning of all the fields returned. I don't see any description for the "type" field, which i can see is null indeed give your test Apex class use case. I sometimes find reviewing the WSDL for the SOAP version of the Tooling API helpful, sometimes we find the fields has some enum values, though not so in this case.
<xsd:complexType name="Symbol">
<xsd:sequence>
<xsd:element name="location" type="tns:Position"/>
<xsd:element name="modifiers" minOccurs="0" maxOccurs="unbounded" type="xsd:string"/>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="references" minOccurs="0" maxOccurs="unbounded" type="tns:Position"/>
<xsd:element name="type" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
To understand what this field might represent take a look at how the above XML Schema type is used throughout the XML Schema in the WSDL, eventually if you follow the type inheritance, you will see that "VisibilitySymbol" extends it, and that this type is in fact used in to also represent Apex properties in the SymbolTable, which i assume your test Apex class does not have? As the "properties" field is not present above. In this case as you can see below the "type" field is present and describes the Apex data type of the property.
public with sharing class SymbolTableTest {
public SymbolTableTest() {
}
public String PropertyA { get; set; }
public String methodA(String parameterA)
{
return PropertyA;
}
public String methodB(String parameterA)
{
return methodA(parameterA);
}
}
RE: Presence of External references
As per the documentation on the ApexClass object in the Tooling API documentation, this information is not present.
If there is not a cached version of SymbolTable, it will be compiled in the background and the query might take longer than expected. The SymbolTable returned from ApexClass does not contain references; to retrieve a SymbolTable with references, use ApexClassMember.
It is only populated when you query the ApexClassMember object. The downside here is you can only access the ApexClassMember Symbol Table after you have performed a compile, which requires learning about MetadataContainer's and another object called ContainerAysncRequest. If you review the MetadataContainer documentation there is a summary of the process at the bottom of the topic. Note that is an async process and thus requires some polling approach in your code as well. If you want to see the process in code you can review the code for the Apex UML open source tool here, although the code is Apex, the process and steps to call the REST API are the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proguard can't find referenced method 'void allowCoreThreadTimeOut(boolean)'
I'm trying to build a new release build of my Android App for the Google Play store. I receive the following build error.
MyApp] Proguard returned with error code 1. See console
MyApp] Warning: bolts.Executors: can't find referenced method 'void allowCoreThreadTimeOut(boolean)' in class java.util.concurrent.ThreadPoolExecutor
MyApp] Warning: bolts.WebViewAppLinkResolver$2$2: can't find referenced class android.webkit.JavascriptInterface
MyApp] You should check if you need to specify additional program jars.
MyApp] Warning: there were 1 unresolved references to classes or interfaces.
MyApp] You may need to specify additional library jars (using '-libraryjars').
MyApp] Warning: there were 1 unresolved references to program class members.
MyApp] Your input classes appear to be inconsistent.
MyApp] You may need to recompile them and try again.
MyApp] Alternatively, you may have to specify the option
MyApp] '-dontskipnonpubliclibraryclassmembers'.
MyApp] java.io.IOException: Please correct the above warnings first.
MyApp] at proguard.Initializer.execute(Initializer.java:321)
MyApp] at proguard.ProGuard.initialize(ProGuard.java:211)
MyApp] at proguard.ProGuard.execute(ProGuard.java:86)
MyApp] at proguard.ProGuard.main(ProGuard.java:492)
I'm not really sure how to go about fixing the issue.
I did just swap out the old Facebook sdk for the newest version. Could that have something to do with this?
A:
The bolts library seems to refer to a method and a class that are not present in the older Android runtime that you are using for building the application. That could cause problems when you run the application on a device with this runtime. You should consider building against and targeting a more recent runtime.
If your sure that it's not a problem, you can tell ProGuard to continue anyway:
-dontwarn bolts.**
| {
"pile_set_name": "StackExchange"
} |
Q:
Python--Function not returning value
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a_points (Think of it like Team A) and vice versa (add one point to b_points if val2 is larger.)
If the two values are even I won't add any points to a_points or b_points.
My problem is test_val will not return the values of a_points or b_points.
a_points=0
b_points=0
def test_val(a_points,b_points,val1,val2):
if val1 > val2:
a_points+=1
return a_points
elif val2 > val1:
b_points+=1
return b_points
elif val1==val2:
pass
Here's a link to a visualization showing the problem.
A:
Consider this:
a0=5
a1=6
a2=7
b0=3
b1=6
b2=10
a_points=0
b_points=0
def test_val(a_points, b_points, val1, val2):
if val1 > val2:
a_points += 1
return (a_points, b_points)
elif val2 > val1:
b_points += 1
return (a_points, b_points)
elif val1==val2:
return (a_points, b_points)
a_points, b_points = test_val(a_points,b_points, a0, b0)
a_points, b_points = test_val(a_points,b_points, a1, b1)
a_points, b_points = test_val(a_points,b_points, a2, b2)
print(a_points, b_points)
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
StreamReader and Writer from a list box
Question 1: whatever the user enters in the text box displays in the listbox but other text is showing up first then what the user enters shows up at the end.
Question 2: my StreamReader / StreamWriter I keep getting 1601 error code to new to C# so I don't know all the terms.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace foodOrderApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//textDialog = new SaveFileDialog();
//textDialog.Filter = ""
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(foodText.Text, "^[a-zA-Z]"))
{
MessageBox.Show("This textbox only accepts alphebetical characters");
}
else
{
displayFoodOrder.Items.Add(foodText.ToString());
}
}
private void loadButton_Click(object sender, EventArgs e)
{
if (loadButton.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(
new FileStream(loadButton.FileName,
FileMode.Create,
FileAccess.ReadWrite)
);
sw.WriteLine(displayFoodOrder.Text);
sw.Close();
}
}
private void saveOrder_Click(object sender, EventArgs e)
{
if (saveOrder.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(
new FileStream(saveOrder.FileName,
FileMode.Open,
FileAccess.Read)
);
}//end if
}
}
}
Error:
CS1061 'Button' does not contain a definition for 'FileName' and no extension method 'FileName' accepting a first argument of type 'Button' could be found (are you missing a using directive or an assembly reference?)
line 42
A:
I don't really understand your first question, what other text shows up first?
For your second question, there are actually other problems I think you have. Firstly you are using:
if (loadButton.ShowDialog() == DialogResult.OK)
and
if (saveOrder.ShowDialog() == DialogResult.OK)
From what I can tell, these are buttons you are clicking, which won't have a ShowDialog method.
The error you are actually looking at is due to you trying to get a FileName property from what I still suspect are buttons (and backed up by the error message - 'Button' does not contain a definition for 'FileName'):
loadButton.FileName
and
saveOrder.FileName
I'm suspicious what you are actually supposed to be using are OpenFileDialog and SaveFileDialog controls, but you've actually referenced the buttons you're clicking on instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript: overriding (not just defining) a function in if statement
I have the following javascript.
var f = function() { ... };
if (x === 1) {
// redefine f.
f = function() {
...
};
}
Is that code valid ?
In other words can I redefine a javascript function inside an if statement where I actually write the code.
I am worried because of this:
Function declarations inside if/else statements?
A:
Yes you can do that.
f = function() {
...
};
is not a function declaration, it is a function expression (assigned to f), so the problems mentioned in the other question don't apply here.
Only variable and function declarations are hoisted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to center the registration point for dynamically imported MovieClip
I'm trying to see if there's a way to change the registration point of a MovieClip that's importing an image dynamically?
Here is my code where I add an image to an "overlayHolder":
overlayBitmap = _loader.getBitmap( _data.id + "-overlay_image" );
overlayHolder.addChild(overlayBitmap);
overlayHolder.x = _data.overlay_left;
overlayHolder.y = _data.overlay_top;
What I need to do is rotate this image later on, upon interaction from someone, but need it to rotate with a center-registration.
I've seen a bunch of tutorials/forums talk about centering a registration point when you're drawing a Sprite on the stage, but not when you're importing an image.
Any help would be appreciated.
Thanks in advance!
A:
So, i figured it out, and thought I'd share:
You can create a Sprite, that's inside of your MovieClip and move that to where it should be.
Something like this:
overlayBitmap = _loader.getBitmap( _data.id + "-overlay_image" );
overlayHolder.x = _data.overlay_left;
overlayHolder.y = _data.overlay_top;
overlayHolderInner = new Sprite();
overlayHolder.addChild(overlayHolderInner);
overlayHolderInner.addChild(overlayBitmap);
overlayHolderInner.x = 0-(overlayHolderInner.width/2);
overlayHolderInner.y = 0-(overlayHolderInner.height/2);
Thought I'd share in case anyone runs into this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Im having an issue, verifying if fields were filled
I have a form, and Im trying to verify if the user fill all fields:
if(in_array('',$f) || empty($_FILES['thumb']['tmp_name']))
{
echo '<span>Please fill all fields!</span>';
}
And everything is working fine, When I didn´t fill a field, I got the alert message.
But now I introduce a new "input file" on my form, to insert PDFs, and I also entered this field in my validation:
if(in_array('',$f) || empty($_FILES['thumb']['tmp_name']) || empty($_FILES['pdf']['tmp_name']))
And now, the thumb and other form fields are working fine, when I dont fill, I got the alert message, but with my pdf field, When I dont fill this field, I never get the alert message.
Here I have my form:
<form name="form" action="" method="post" enctype="multipart/form-data">
<label class="line">
<span>Image:</span>
<input type="file" class="fileinput" name="thumb"/>
</label>
<label class="line">
<span>Title:</span>
<input type="text" name="title" value="" />
</label>
<label class="line">
<span>Pdfs<input type="file" name="pdf[]" size="60" multiple="multiple" accept="application/pdf"/></span>
</label>
<input type="submit" value="Submit" name="sendForm" />
</form>
A:
You are passing an array "pdf[]" compared to "thumb". You could check the first element of this array [0]:
if(in_array('',$f) || empty($_FILES['thumb']['tmp_name']) || empty($_FILES['pdf'][0]['tmp_name']))
It is the array elements ($_FILES['pdf'][0], $_FILES['pdf'][1], etc.) that would contain the 'tmp_name'.
My mistake, the array is the other way round $_FILES['pdf']['tmp_name'][0].
| {
"pile_set_name": "StackExchange"
} |
Q:
DELETE request with parameters using Guzzle
I have to do a DELETE request, with parameters, in the CodeIgnitor platform. First, I tried using cURL, but I switched to Guzzle.
An example of the request in the console is:
curl -X DELETE -d '{"username":"test"}' http://example.net/resource/id
But in the documentation of Guzzle they use parameters just like GET, like DELETE http://example.net/resource/id?username=test, and I don't want to do that.
I tried with:
$client = new GuzzleHttp\Client();
$client->request('DELETE', $url, $data);
but the request just calls DELETE http://example.com/resource/id without any parameters.
A:
If I interpret your curl request properly, you are attempting to send json data as the body of your delete request.
// turn on debugging mode. This will force guzzle to dump the request and response.
$client = new GuzzleHttp\Client(['debug' => true,]);
// this option will also set the 'Content-Type' header.
$response = $client->delete($uri, [
'json' => $data,
]);
| {
"pile_set_name": "StackExchange"
} |
Q:
UUID1 from UTC Timestamp in Python?
The problem goes like this:
My application is deployed on a remote server with different timezone and I want to generate a uuid1 against UTC timestamp. I can't find a way to generate uuid1 from any given timestamp. The reason I want to do this is that I don't want to get into the hassle of calculating my local time where my local time does not observe Daylight saving time and the remote server does and a result the presentation logic becomes cumbersome.
The limitation is that the Timestamp needs to be stored as uuid1. Any idea or workaround for this will be higly appreciated.
A:
the UUID class will do the bit-juggling if you give it the right fragments - http://docs.python.org/library/uuid.html
to get the right components you can copy the the uuid1 code from python2.7:
def uuid1(node=None, clock_seq=None):
"""Generate a UUID from a host ID, sequence number, and the current time.
If 'node' is not given, getnode() is used to obtain the hardware
address. If 'clock_seq' is given, it is used as the sequence number;
otherwise a random 14-bit sequence number is chosen."""
# When the system provides a version-1 UUID generator, use it (but don't
# use UuidCreate here because its UUIDs don't conform to RFC 4122).
if _uuid_generate_time and node is clock_seq is None:
_buffer = ctypes.create_string_buffer(16)
_uuid_generate_time(_buffer)
return UUID(bytes=_buffer.raw)
global _last_timestamp
import time
nanoseconds = int(time.time() * 1e9)
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
_last_timestamp = timestamp
if clock_seq is None:
import random
clock_seq = random.randrange(1<<14L) # instead of stable storage
time_low = timestamp & 0xffffffffL
time_mid = (timestamp >> 32L) & 0xffffL
time_hi_version = (timestamp >> 48L) & 0x0fffL
clock_seq_low = clock_seq & 0xffL
clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
if node is None:
node = getnode()
return UUID(fields=(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node), version=1)
all you need to do is copy+paste that and modify the timestamp part to use a fixed value (you can ignore the last_timestamp part if you know that your times are distinct - that is just to avoid duplicates when the clock resolution is insufficient).
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying the specific error returned in a Behat test step
I'm working on integrating Behat with HipChat and I've got the following code so far.
/**
* Send an alert to HipChat when a test fails
*
* @AfterStep
*/
public function notifyHipchat(Behat\Behat\Event\StepEvent $event)
{
if ($event->getResult() === Behat\Behat\Event\StepEvent::FAILED) {
$step = $event->getStep();
$feature = $step->getParent()->getFeature()->getTitle();
$scenario = $step->getParent()->getTitle();
$step = $step->getType() . ' ' . $step->getText();
$error = '!!!!NEED CODE FOR THIS!!!!';
$current_page = $this->getSession()->getCurrentUrl();
$message =
'<img src="http://dl.dropboxusercontent.com/u/9451698/fail.gif" width="32" height="32" /> <strong>Whoopsie! There was a test failure!</strong>' . "<br>" .
'<strong>Domain:</strong> <a href="'.$this->getMinkParameter('base_url').'">' . $this->getMinkParameter('base_url') . "</a><br>" .
'<strong>Test Instance:</strong> ' . $this->getMinkParameter('files_path') . "<br>" .
'<strong>Feature/Test:</strong> ' . $feature . "<br>" .
'<strong>Scenario:</strong> ' . $scenario . "<br>" .
'<strong>Step:</strong> ' . $step . "<br>" .
'<strong>Current Page:</strong> <a href="'.$current_page.'">' . $current_page . '</a>';
$hipchat_url = 'https://api.hipchat.com/v1/rooms/message?auth_token='.getenv('HIPCHAT_AUTH_TOKEN').'&room_id='.getenv('HIPCHAT_ROOM_ID').'&from=Behat&color=red¬ify=1&message=' . urlencode($message);
$hipchat_message = file_get_contents($hipchat_url);
}
}
Which is working great but it only returns the test step that failed, it doesn't tell me what the actual error was. How do I access the exception that was thrown by the failed step? Thanks!
A:
It's
$event->getException()
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to observe class changes on the DOM of a website through a chrome extension?
I'm trying to triger an action when a especific class changes in a external web site. Is that possible?
A:
Attach a MutationObserver to the element and watch for attribute changes. When a mutation occurs, check if the attributeName of the mutation is class:
const div = document.querySelector('div');
new MutationObserver((mutations) => {
if (mutations[0].attributeName === 'class') {
console.log('class change seen');
}
})
.observe(div, { attributes: true });
setTimeout(() => {
div.classList.add('foo');
}, 2000);
<div></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why 1 value from API doesn't not save?
API this one https://covid19.mathdro.id/api
Sorry for interrupt, but I freaking out with this issue, almost 2 hours im thinking what the problem.
So, for recored and for confirmed it works fine, but for deaths I have this issue:
Issue photo
import React from 'react';
import {Card, CardContent, Typography, Grid} from '@material-ui/core';
import CountUp from 'react-countup';
import cx from 'classnames';
import styles from './Cards.module.css'
const Cards = ({data: {deaths, confirmed, recovered, lastUpdate } } ) => {
if(!confirmed) {
return 'Loading...'
};
return (
<div className={styles.container}>
<Grid container spacing={3} justify="center">
<Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.infected)}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Infected</Typography>
<Typography variant="h5">
<CountUp
start={0}
end={confirmed.value}
duration={2.5}
separator=","
/>
</Typography>
<Typography color="textSecondary">{new Date(lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of active cases</Typography>
</CardContent>
</Grid>
<Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.recovered)}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Recovered</Typography>
<Typography variant="h5">
<CountUp
start={0}
end={recovered.value}
duration={2.5}
separator=","
/>
</Typography>
<Typography color="textSecondary">{new Date(lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of recoveries from COVID-19</Typography>
</CardContent>
</Grid>
<Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.deaths)}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Deaths</Typography>
<Typography variant="h5">
<CountUp
start={0}
end={deaths.value}
duration={2.5}
separator=","
/>
</Typography>
<Typography color="textSecondary">{new Date(lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of deaths caused by COVID-19</Typography>
</CardContent>
</Grid>
</Grid>
</div>
)
}
export default Cards;
this is my app.js
import React from 'react';
import { Cards, Chart, CountryPicker } from './components';
import styles from './App.module.css';
import { fetchData } from './api';
class App extends React.Component {
state = {
data: {},
}
async componentDidMount() {
const fetchedData = await fetchData();
this.setState({ data: fetchedData });
}
render() {
const {data} = this.state;
return (
<div className={styles.container}>
<Cards data={data}/>
<Chart />
<CountryPicker />
</div>
)
}
}
export default App;
So, I'm try without deaths and it works, but with not.
index.js
import axios from 'axios';
const url = 'https://covid19.mathdro.id/api';
export const fetchData = async () => {
try {
const { data: { confirmed, recovered, death, lastUpdate } } = await axios.get(url);
return {confirmed, recovered, death, lastUpdate};
} catch (error) {
}
}
Thanks for helping me out!
A:
You have missed a "s" (it is deaths not death, according to the API) in your fetch data function.
Update your this part
data: { confirmed, recovered, death, lastUpdate } } = await axios.get(url);
to
data: { confirmed, recovered, deaths, lastUpdate } } = await axios.get(url);
:D
| {
"pile_set_name": "StackExchange"
} |
Q:
sending ui data in swift
I'm a bit beginner in SWIFT and right now I'm facing a problem whit UI. In this PHOTO I'm showing my UI to clarify what I'm saying . in part 1 I check if the user is logged in to his account or not, if yes it goes to part 3, if not it goes to part 2. when user login in part 2, I transfer the user to part 3.
part 1 and 2 should not have any navigation color, though the part 3 should have the navigation color.
Part 1:
if let token = UserDefaults.standard.string(forKey: ConstantsKey.token){
if !token.isEmpty{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
self.present(rootController, animated: true, completion: nil)
}else{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginVc")
let rootController = UINavigationController(rootViewController: vc)
self.present(rootController, animated: true, completion: nil)
}
}else{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginVc")
let rootController = UINavigationController(rootViewController: vc)
self.present(rootController, animated: true, completion: nil)
}
Part 2:
let storyboard : UIStoryboard = UIStoryboard(name: "MainTabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
self.present(rootController, animated: true, completion: nil)
I want to have that red color in part 3 ! but whenever I run the application in shows the defualt color of the navigation controller
does anybody knows how should I manage/handle this problem?
A:
Then in Part 1:
if !token.isEmpty{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
rootController?.navigationBar.barTintColor = UIColor.red
self.present(rootController, animated: true, completion: nil)
Part 2:
let storyboard : UIStoryboard = UIStoryboard(name: "MainTabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
rootController?.navigationBar.barTintColor = UIColor.red
self.present(rootController, animated: true, completion: nil)
| {
"pile_set_name": "StackExchange"
} |
Q:
Fine grained suspension
tl;dr version: Rather than locking people out of the house for increasing periods of time, wouldn't it be better if they were only locked out of the rooms they consistently made messes in? This would allow otherwise good users to contribute in the ways they are best able to participate without allowing them to cause the problems they consistently cause.
Problem
A significant problem that suspended users and their supporters complain of frequently is that the user is awesome in some way, and benefits the community greatly. The hope is that we will consider weighing their infractions against their contributions so we can continue to extract usefulness from them, rather than throwing them out wholesale.
Evidence
While I hate to open old wounds, and there is an unwritten social agreement to avoid mentioning specific people who have been banned (Primarily for privacy reasons), I feel it's important that we consider some concrete examples that did happen, rather than postulate based on what could or might happen.
Threatening emails from Jeff Atwood <-- User asked privately to change their comment posting behavior to avoid suspension.
https://stackoverflow.com/users/5640/geoffrey-chetwood <-- User suspended due to numerous complaints and flags against user's comments and other interactions on the site.
Numerous other users have been banned at various times for various reasons, including extraordinary users (one of the top superusers, for instance, and that is a site that could still use a little more help). Would these cases have been better if we could remove one or another ability, rather than removing them from the site completely?
Solution
Implement fine grained suspension that removes specific abilities related to the type of infractions they commit
In both examples above the users in question are/were defended by other users who clearly believe their value to the community is worth the extra work and pain they cause to moderators and other users. It generally appears that their infractions do not conflict with their best contributions. In the first case, the user provides excellent answers, but had poor commenting skills. While the comments were valuable, the way they were used irritated fellow users, caused many flags, and soaked up more moderator time than allowable. In the second case the user's primary contribution was in editing and low level moderation activity, but they would frequently spar in comments in an ineffective and sometimes offensive way, requiring a lot of moderator intervention. Removing commenting ability from these two users in question would permit them to participate in the ways that they were most effective in rather than suspending them, while removing (for a time) the ability to participate in ways that were ineffective and sometimes damaging to the community.
There are other abilities that should be discussed along these lines, such as voting for those that regularly exhibit strange voting patterns, editing posts for frivolous reasons, etc, but commenting is an obvious first test case for implementing this sort of system.
There is already some precedence for this in the moderator flagging system - those who regularly flag items which the moderators choose not to act on are pushed to the bottom of the flag list and eventually ignored. For all intents and purposes they have lost their ability to flag for moderator attention.
Discussion Points
Is this worse than a full suspension (ie, being able to participate, but not fully, might hurt worse than simply being kicked out?)
Is there validity in the idea that kicking them down the ladder would be better than just removing certain abilities? (for instance, if you can't comment properly, perhaps you shouldn't be allowed to do anything else above commenting that your reputation would otherwise allow)
Is it fair making a user's ability contingent on something other than reputation, such as how well they use that ability?
Is it wise to remove their ability to defend themselves in comments? (Are comments a primary feature of the site?)
Are there abilities that should or should not be considered for this treatment? (Posting questions and answers is the primary purpose of the site - if we remove either of those, isn't that essentially the same as suspending them completely, even if it's only for a few days?)
Specifically regarding commenting, should comment-suspended users be allowed to comment on their own questions and answers, or if someone explicitly calls them out using the @username feature? (for instance in the case of someone commenting on how the suspended user edited a question)
A:
It's too complicated. Timed suspension is simple.
It would be a lot of development work.
For the users in question, even if we had this fine granular "remove abilities", they would have reacted no differently in my opinion. In fact, I believe they would have acted out in other negative ways based on the partial removal of abilities. Ways that would not be available to them in a standard "can't do anything" timed suspension.
In general, I find that for the types of users where timed suspension is necessary, if it's not this {random event} that sets them off, it will inevitably be the next {random event} a few weeks later. There is something about these rare users that puts them on edge, and any attempt to moderate their behavior often (not always, but often) results in them spiraling further and further out of control.
Reducing or limiting the effect of timed suspension would have, at best, no benefit -- and I strongly suspect it would make matters worse.
A:
A person (or bot or whatever) has to work awfully hard to manage to get themselves suspended by the team. I don't think, for example, that Col. Shrapnel has managed it yet. These are not marginal cases. In fact, as far as I can tell, what really distinguishes the suspendees is their reliably and far-reaching insistence on picking fights and giving offense.
Thus, I very much doubt that a more complex penalty box structure would receive much use.
I personally don't care how many muppets or sock-puppets or meat-puppets have soft spots for these disruptive characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
To find relatively prime ordered pairs of positive integers $(a,b)$ such that $ \dfrac ab +\dfrac {14b}{9a}$ is an integer
How many ordered pairs $(a,b)$ of positive integers are there such that g.c.d.$(a,b)=1$ , and
$ \dfrac ab +\dfrac {14b}{9a}$ is an integer ?
A:
We are looking for $9ab\ |\ 9a^2+14b^2$.
Now, as everything else is divisible by $9$, we immediately get that
$9\ |\ b^2$, i.e., $3\ |\,b$.
Similarly, looking at divisibility by $a$, we get $a\,|\,14$. This gives only four possibility on $a$: it can be $\ 1,\ 2,\ 7,\ 14$.
If we write $b=3k$, we get $27ak\ |\ 9a^2+14\cdot 9k^2$, that simplifies to
$$3ak\ |\ a^2+14k^2\,.$$
Now, by divisibility by $k$, we have $k\,|\,a^2$, which is only possible if $k=1$ by condition $\gcd(a,b)=1$.
From this there are only $4$ possibilities, check them manually.
A:
A slight generalization shows more clearly the structure behind the number of solutions:
Theorem $\ $ Suppose that $\,c\,$ is a positive integer and $\,p\,$ is prime such that $\,p^2\nmid c.\ $ Then
$\ \ $ there are coprime integers $\, a,b > 0\,$ with $\,\dfrac{a}{b} +\dfrac{b\,c\ }{a\,p^2}\in\Bbb Z\iff b=p,\,\ c = aa',\,\ p\mid a\!+\!a' $
Therefore the #solutions = #factorizations $\,c\,$ into two factors $\,>0\,$ with sum divisible by $\,p.$
Proof $\ $ By Euclid $\,(a,b)=1\,\Rightarrow\, (a,b^2)=1=(b,a^2),\ $ thus $\ abp^2\mid p^2a^2 + cb^2\,\Rightarrow\,a\mid c,\,\ b\mid p^2.\,$ Let $\ a' = c/a.\,$ By unique factorization $\,b\mid p^2\Rightarrow\,b = 1\,$ or $\,b=p\,$ or $\,b = p^2,\, $ yielding $3$ cases:
$\qquad\qquad\qquad b\, =\, 1\,\Rightarrow\,\ a + \dfrac{a'}{p^2}\in\Bbb Z\,\Rightarrow\, p^2\mid a'\mid c,\,$ contra hypothesis.
$\qquad\qquad\qquad b = p^2\,\Rightarrow\, \dfrac{a}{p^2}+ a'\in\Bbb Z\,\Rightarrow\, p^2\mid a\mid c,\,$ contra hypothesis.
$\qquad\qquad\qquad b\, =\, p\, \Rightarrow\, \dfrac{a}p + \dfrac{a'}{p}\in\Bbb Z\iff p\mid a+a'\quad $ QED
Yours is special case $\,p = 3,\,\ c = 14\,$ with factors $\,a,a' = 1,14;\,\ 2,7;\,\ 7,2;\,\ 14,1.$
A:
If $(a,b)$ is an ordered pair of positive integers such that $\gcd(a,b)=1$ and
$$\frac{a}{b}+\frac{14b}{9a}=\frac{9a^2+14b^2}{9ab},$$
is an integer, then $9ab$ divides $9a^2+14b^2$. In particular $a$ and $b$ both divide $9a^2+14b^2$, and so $a$ divides $14b^2$ and $b$ divides $9a^2$. Because $\gcd(a,b)=1$ it follows that $a$ divides $14$ and $b$ divides $9$. If $b=9$ then $81a$ divides $9a^2+14\cdot 81$, so $81$ divides $9a^2$ and hence $3$ divides $a$, contradicting the fact that $\gcd(a,b)=1$. Of course $b\neq1$ because $9$ does not divide 14. Hence $b=3$, and we conclude that there are precisely four such pairs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cucumber reports not generating
I'm having an issue with cucumber reports not generating. I'm running the tests with IntelliJ.
Here's my pom:
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>4.8.0</version>
<scope>test</scope>
</dependency>
I've created a RunCucumberTest.java class, with the following:
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty", "html:target/reports", "json:target/reports/cucumber.json"},
glue = {"com.PACKAGE.featureTests"})
public class RunCucumberTest {
}
I've run it successfully with the IntelliJ plugin, with failures and without (I know some issues have been that the report doesn't generate when there are failures). But in neither case will any report be created in my target folder.
Thoughts?
A:
I finally solved my problem by upgrading to 5.1.3 and they generate fine there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need local SDK tool for parsing native pdf file with large tables
User needs to parse native-pdf(selectable data, not scanned, no OCR required) in local. The pdf files may be over 400 pages with large tables. Some tables may not have clear borders. Is there any API I could use?
Thanks!
A:
Now that I know you don't want an API, I might recommend that you check out ItextSharp, from nuget. I have used this several times in the past, and there are many stack overflow forums on how to use it. https://www.nuget.org/packages/iTextSharp/5.5.13.1
EDIT: I apologize, it looks like iTextSharp has been replaced with iText 7 https://itextpdf.com/en/products/itext-7
| {
"pile_set_name": "StackExchange"
} |
Q:
What was the connection between Harold and the tech guy at the end of season 4
Near the end of Season 4 Root & Harold break into the software firm to get something but get caught. The guy who caught them just saw Root and there was a relationship established a few episodes before.
Harold walks out and the guy knew him as a professor. It's been a while since I've seen previous seasons, was this relationship between this guy and Harold already filled in? I felt like I was really missing something important when he was just like "whatever you need, it's yours."
A:
The person you are talking about is Caleb Phipps, he appeared as an Irrelevant Number in the 11th episode of the 2nd season (2πR).
When we first meet Caleb, he is a teenager, who performs poorly at school. He also anoonymously deals drugs to support his mother who become an alcoholic after Ryan's (Caleb's brother) death. Ryan was hit by a train while the brothers were drunk and crossing tracks on a dare.
Finch poses as a substitute math teacher and quickly realizes that Caleb is in fact a computer genius, working on a revolutionary compression algorithm named 17-6-21. This turns out to be the exact age Ryan was when he died and Caleb's current age. Finch figures out what Caleb's about to do - he is blaming himself for Ryan's death and wants to commit a suicide in the same way his brother died.
Finch finds Caleb at the train station and sits down next to him and manages to convince Caleb not to kill himself.
The next day They meet outside the school. Finch warns Caleb to be more careful with his code and tells him a story of a young hacker who changed everything with a home-made PC in the early days of the internet.
As I see it: Finch saved Caleb from himself and gave him reason to live.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is there a grid behind a transparent background PNG?
When I open a transparent background PNG, I see a grey-white grid.
Is the grid embedded into the file? How can I change it?
A:
That's there to show that it's a transparent background; it's not actually embedded since it's just the way it's displayed in Photoshop. When you drop that onto your web page / document you won't see the grid.
You can change the parameters for the grid in Photoshop → Preferences → Transparency & Gamut.
| {
"pile_set_name": "StackExchange"
} |
Q:
Explicit bijection between the successor of $\alpha$ and $\alpha$ (infinite ordinal).
I would like to construct an explicit bijection from $\alpha^*$ to $\alpha$, where $\alpha$ is an infinite ordinal. I have been told a possible bijection would be:
\begin{equation}
f(\beta) = \begin{cases} 0 & \text{if } \beta = \alpha \\
\beta^* & \text{if } \beta \text{ is finite} \\
\beta & \text{otherwise}
\end{cases}
\end{equation}
I don't understand how this is constructed, or why it is a bijection.
A:
This is essentially a Hilbert's hotel argument.
The ordinal $\alpha^*$ is obtained by adding a new element to $\alpha$ (namely $\alpha$ itself, i.e. $\alpha^* = \alpha \cup \{ \alpha \}$). The idea is to define a function $f : \alpha^* \to \alpha$ that is as close to the identity function as possible.
We can't just define $f(\beta)=\beta$ for all $\beta \in \alpha^*$ since then $f(\alpha)$ would be undefined. So we define $f(\alpha)=0$. But then $f(0)$ can't be $0$, since then $f$ would not be injective, so we take $f(0)=1$. But then $f(1)$ can't be $1$ since $f$ would not be injective, so we take $f(1)=2$... and so on. But this 'and so on' stops at $\omega$, since the map $n \mapsto n+1$ gives a bijection $\omega \to \omega \setminus \{ 0 \}$.
So if we take $f(\alpha)=0$, $f(n)=n+1$ for all $n \in \omega$, and $f(\beta) = \beta$ for all other $\beta$, then we obtain a bijection $\alpha^* \to \alpha$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you describe "x > y > 5 ", inequality or inequalities?
x > y > 5 ... (1)
This is a combination of two inequalities; x > y and y > 5 , so should this be described as "inequalities" not "inequality"? For example, which of the following is suitable?
Solve the inequality (1)
Solve the inequalities (1)
A:
Each one
x > y
y > 5
is an inequality, stated as
x > y and y > 5
you could use the inequalities, however stated as
x > y > 5
you could use the inequality, it depends how you want to combine them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why defined integral of x works
I know this is duplicate, but I still struggling to understand why this particular example works:
If we check integral of x dx, we see it is parabola.
https://www.wolframalpha.com/input/?i=integral+of+x+dx
Then if we do it as integral from 0 to 1 of x dx
https://www.wolframalpha.com/input/?i=integral+from+0+to+1+of+x+dx
Then it "magically" works and calculate precise area of 0.5 .
I know all about delta x and so on.
But how the parabola is related to straight line?
And how just subtracting two anti-derivatives, we got the area in question?
A:
Consider a triangle of width and height $x$ (instead of $1$). Isn't its area
$$A(x)=\frac{x\cdot x}2 ?$$
Now consider the trapezium formed by the verticals at $x=\dfrac12$ and $x=1$, the $x$ axis and the line $y=x$. Isn't is area given by the difference of two triangles of width/height $\frac12$ and $1$ ?
$$\left.A\right|_{\frac12}^1=\frac{1^2}2-\frac{\left(\frac12\right)^2}2.$$
The area of a shape can be recast as "the width times the average height", and in a discrete setting the average is "the sum over the number of values", which is what an integral computes in the continuous domain.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python math, Pythagora, degrees and coordinates
Is me again. Did I mention how much I love you guys? My prof talked me into trying python, so far I hate it, but I decided to give it a try. I have made a simple program, using pygame, that moves few circles around the screen. I have issues with some math problems in it. I gave each circle (x, y) coordinates (the center of circle) and I calculated their shifts(Dx, Dy) on the screen, based on the speed (distance per move) I want them to move.
This is what I have done for the move method:
def Move(self, speed):
Dx = self.qx * (speed * math.sin(math.degrees(90 - Alp)))
Dy = self.qy * (speed * math.sin(math.degrees(Alp)))
self.x += Dx
self.y += Dy
print "D = ", math.sqrt(Dx * Dx + Dy * Dy)
the problem:
I calculate Dx and Dy based on speed using Pythagorahs theorem, and then, calculating D (actaully speed) in print statement using the same theorem, I should Have a result equal to speed that is inputed. But, the result I get is:
D = 9.15180313227 (speed = 10)
The result varies and is not always the same (I have test method with random values), but it's always close and wrong. What am I missing?
NOTE: Ignore self.qy and self.qx, they are used to properly determine the direction, their value is either 1 or -1
A:
Looking to your code, and precisely where you call math.degrees(90-Alp), it seems to me that you understood math.degrees in the wrong way:
>>> math.degrees(2)
114.59 (...)
This function converts radians to degrees, not the opposite. How does it perform if you use math.radians instead?
| {
"pile_set_name": "StackExchange"
} |
Q:
Quiz interativo com usuários em LiveStream Youtube
Tenho algumas ideias sobre criar um aplicativo em php ou até mesmo em uma outra linguagem, onde o aplicativo responda interações do chat de uma livestream no youtube, por exemplo.
Uma pergunta exibe na live, se a pessoa que estiver assistindo acertar a pergunta com uma palavra já pré programada, esse nome da pessoa é exibido na live, junto da resposta, isso acontecendo simultaneamente em tempo real.
Andei vasculhando as api do youtube, mas não consegui clarear a mente, alguém tem uma sugestão?
Obrigado!
A:
Bom, vendo um pouco da API que o youtube disponibiliza para ser utilizada, não existe uma forma de "socket". Portanto, você terá que ficar dando GET de tempos em tempos em um sala de chat específica para retornar uma lista das mensagens enviadas. Depois disso, coloque cada mensagem em uma pilha (para manter a integridade do momento em que a mensagem foi enviada), ou alguma estrutura do gênero e comece a varrer essa pilha procurando pelo o que você está interessado. Essa seria a forma que eu construiria uma aplicação deste tipo. Se existe alguma outra solução melhor, por favor me deixam saber! :D
Para que a mensagem correta seja exibida na tela, você precisará conectar essa aplicação com algum software de livestreaming (tipo: xplit, obs) por meio de algum plugin que você terá que implementar para eles. Para isso você terá que estudar um pouco mais sobre a API desses softwares também! Não entendo muito como que eles funcionam, mas sei que é por ai. Se eu não me engano, já deve existir algum plugin que realize as operações que você está querendo implementar. Tente estudá-los! :)
Aqui está a documentação que peguei como base para esse tipo de implementação que você está querendo fazer: https://developers.google.com/youtube/v3/live/docs
Vá até a sessão de "LiveChatMessages" e ali ele te dará as operações disponíveis para manipulação do chat.
Caso tenha falado algo errado, por favor me corrijam. Abraços!
| {
"pile_set_name": "StackExchange"
} |
Q:
WSDLException ... An error occurred trying to resolve schema ... Connection timed out: connect
First of all, my error is almost identical to what is reported in this question: WSDLException : An error occurred trying to resolve schema referenced at
Here is a snippet of my stack dump:
javax.wsdl.WSDLException: WSDLException (at /definitions/types/xs:schema/xs:schema): faultCode=OTHER_ERROR: An error occurred trying to resolve schema referenced at 'http://www.w3.org/2005/05/xmlmime', relative to 'http://server.subdom.domain.com:13080/SM/7/Common.xsd'.: java.net.ConnectException: Connection timed out: connect] MDC{}
2015-05-24 14:36:33,751 ERROR (c.d.g.w.c.ContexteApplicatif.contextInitialized) [main] catching MDC{}
javax.xml.rpc.ServiceException: Error processing WSDL document:
javax.wsdl.WSDLException: WSDLException (at /definitions/types/xs:schema/xs:schema): faultCode=OTHER_ERROR: An error occurred trying to resolve schema referenced at 'http://www.w3.org/2005/05/xmlmime', relative to 'http://server.subdom.domain.com:13080/SM/7/Common.xsd'.: java.net.ConnectException: Connection timed out: connect
at org.apache.axis.client.Service.initService(Service.java:250) ~[axis-1.4.jar:?]
This occurs in my embedded Tomcat server running from within Eclipse. It is running on a Windows machine and there is an httpProxy at the system level. However, the URL is an internal address for which no proxy is needed. Anyhow, I implemented programmatically a proxy with the following code just before the reference to the WSDL file:
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "proxyhost.subdom.domain.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxyhost.subdom.domain.com");
System.setProperty("https.proxyPort", "8080");
And now I am getting an HTTP 502 error which indicate a bad gateway. So, I suppose this solution is the wrong one since I shouldn't need a proxy in first place. I can access the page from within a browser, indistinctly if I enable or disable the proxy settings. In addition, there is a script to configure the proxy and if I use the proxy host shown above and hardcode it in my browser instead of "system proxy" or "automatic setting" I cannot access the page.
To summarize, it behaves like there is like it needs a proxy setup, however it doesn't. The problem is elsewhere and I have no idea how I can make significant progress to debug this problem.
Any hints? Something with Tomcat? Something with Eclipse?
I haven't tried yet on a standalone Tomcat server since my code is not yet ready for deployement.
NOTE: BTW, I tried the command from the quoted post and I am getting the same error as well. Connect timed out without system properties defined for the proxy and 502 code otherwise. At the same time, if I am launching the Web Service Explorer from Eclipse I am perfectly able to access the webservice and invoke operations.
Further investigation: I decided to use WireShark to see what is going on with the request and it appears both HTTP requests (the wsdl and the common types definitions) were fulfilled without a glitch and no connection timed out at all, not a single error. I can see the XML in WireShark and the HTTP status is 200 OK and everything is perfectly fine at this level.
So, what is going on here? I have the same problem on a Linux server while the message is a bit different. What wsdl2java is doing to believe there was a problem and abort?
A:
After further investigation and testing with Axis2 and CXF, I finally found the problem, thanks to the CXF's version of the wsdl2java script which is giving a bit more details.
First of all, the original solution proposed was almost correct. I actually need to add all the proxy information, however I also needed to specify the non-proxy hosts otherwise I am getting the 502 error. The messages from the Axis script were not very detailed about the offending request, while CXF's version was very clear and enabled me to finally solve my problem.
So, in addition, if you modify the wsdl2java script, add -Dhttp.nonProxyHosts=... in addition to other options. The same thing if you need to specify a proxy programmatically.
| {
"pile_set_name": "StackExchange"
} |
Q:
Buttons changing background images on iPhone
I have it working with a small error. I have two code pieces for each button. One being this:
-(IBAction)clickoneButton:(id)sender
{
[sender setBackgroundImage:[UIImage imageNamed:@"cnumber_1.jpg"] forState:UIControlStateNormal];
}
And the other being this:
-(IBAction)oneButton:(id)sender
{
self.enteredPhoneNumberString = [self.enteredPhoneNumberString stringByAppendingString:[NSString stringWithFormat:@"%d", 1]];
[self updateFormattedPhoneNumberLabel];
[sender setBackgroundImage:[UIImage imageNamed:@"Number_1.jpg"] forState:UIControlStateNormal];
}
The first is set up to be Touch Down. The other is for Touch Up Inside. The app looks like the phones regular dialer. So the first image is a light blue button and the second is a dark blue button just the same way as the iPhones dialer is. The issue is when I press down on the button it almost seems like the dark image is still behind the Touch Down light blue image. It is changing to a lighter colored image but is shaded almost like the dark image is transparent through it or something. Not sure how else to explain it. If you have any ideas as to why the light blue is darkened some when the Touch Down is happening I would appreciate any help. Thanks
Button before touch and after release (Correct)
Button on Touch Down (not working properly)
What the touch down button should look like
A:
Based upon the two snippets of code you provided, you are not setting an image for when the button is pressed. Try updating your code to use the following when you load the view:
// sets the background image for when the button is not pressed
[sender setBackgroundImage:[UIImage imageNamed:@"cnumber_1.jpg"] forState:UIControlStateNormal];
// sets the background image for when the button is pressed
[sender setBackgroundImage:[UIImage imageNamed:@"Number_1.jpg"] forState:UIControlStateHighlighted];
| {
"pile_set_name": "StackExchange"
} |
Q:
NoClassDefFoundError when trying to load class
I am getting a java.lang.NoClassDefFoundError when trying to instantiate some class
I will try to simplify the structure of my projects: I have 2 jar files A (with a.class inside) and B (with b.class) I am trying to instantiate a 'b' class inside 'a' code. JAR A is dependant on JAR B. JAR A is a regular JAR file which is located in application/lib and JAR B is packaged as an EJB_JAR.
I am using glassfish and J2EE with maven I am new to J2EE and I have tried to look up a little for it. I have figured out it might be a class loaders issue, as the Classloader that loads classes from lib ( A) is the Ancestor of the Classloader that loads EARs WARs and EJB_JARs hence because of visibility issues I cannot load class 'b' from 'a'
Also, when I'm trying invoke (using the "expression evaluator") Class.forName("com.package.SomeClass") in the debugger from classes located in Jar-A to load class in JAR-A I get a class, but when I try to load classes located in Jar-B I get the java.lang.NoClassDefFoundError exception.
The thing is, that the passed EJB in the constructor has all the EJB fields properly, so I thought it should work, and, everything was compiled successfully.
How do I solve this problem?
The weirdest thing:
I am using drools which resides in JAR_A and JAR_A has some regular class which tries to call b.class (in JAR_B)
calling b.class from a.class doesnt work,
but calling b.class directly from a rule (which got b.class from CommandFactory.newSetGlobal("Bclass",b))works just fine.
How Could it be?
when I pass it as an Object from JAR_B it works and invokates fine.
A:
Recap
You say:
I am trying to instantiate a 'b' class inside 'a' code. JAR A is dependant on JAR B. JAR A is a regular JAR file which is located in application/lib and JAR B is packaged as an EJB_JAR.
From what I understand, you have a pom.xml to build jar A, which states that jar B is its <dependency/>.
Then I see two possible cases for your deployment scenarios: you are either deploying the jars to the application server as an EAR, where jar A is contained inside this EAR as a library and jar B is a deployment inside it, or you are trying to use B from another, unrelated application.
In either deployment case, this is an error, but it might be due to expressing your dependencies incorrectly, or accessing the EJB incorrectly.
Nested Deployment case
If this is a nested deployment, where jar A is contained in the EAR as a library, you have a dependency expression problem. An EAR library can not have a dependency on the EAR itself, it can only be the other way around. After all, this is the definition of a library, right? :)
You have to refactor your application to match the use case you are trying to implement here. For more info, see the excellent Patterns of Modular Architecture RefCard from DZone.
Application client case
If what you are writing is an isolated (might even be a standalone) client that is going to invoke some operations on the EJB, what you should do is create an interface (local or remote, depending on how you are deploying the client) and package it with the client application and your EJB.
Then use a JNDI lookup in your client application to obtain a reference to the remote EJB and use it via the interface:
Context foo = new InitialContext(remoteJndiServiceProperties);
MyBeanInterface bar = (MyBeanInterface)foo.lookup("com.mycompany.MyBeanInterface");
bar.doStuff();
The remote JNDI registry properties and your bean's business interface name have to be expressed properly, of course. See the EJB FAQ for Glassfish for more info.
It is even simpler if your client is running in the same deployment unit - you can just use the @EJB annotation in that case and inject a no-interface EJB reference.
For more information on standalone clients with GlassFish, see the Developing Application Clients with ACC guide which covers all possible deployment scenarios.
Some theory behind this
Run the application in a debugger (or look at the heap dump taken while your client is invoking methods on the EJB, passing it objects as parameters).
What you will see is that the EJB container (that is, your EJB) is not working with the actual class you think it is, but rather with something called a static proxy class, which is generated on the fly by the container.
Because of this, when you invoke the instanceof operator inside the EJB, checking if the class you're working with is of the correct type, it will evaluate to true, but when you try to typecast it, you will get a ClassCastException.
This is required by the EJB specification and there is not much you can do about it, except pass the objects not as references, but rather as serialized data (which is going to cost you).
It works the other way around, too, because the container must be able to intercept anything done to the EJB from outside of it, and react (such as unauthorized use of restricted methods, transaction handling, etc.).
BTW, a lot of what you are describing above is illegal. ;)
Manually loading classes using Class.forName() inside an EJB container, for example - the EJB container should manage the lifecycle of your objects and anything you can not obtain using a factory method, or even better, using "compatible" mechanisms such as CDI producers and dependency injection, should be passed to your EJBs as a parameter.
What is also questionable is the way you try to pass an instance of the EJB to an application running outside of the container. If you need to access your EJBs to invoke methods on them, you should do it by means of an EJB client, in your case most probably through a remote interface.
Also, look up the definition of classloader hell if you still want to pursue your approach - you might want to start with this article, but I guess it's just as good as any other.
| {
"pile_set_name": "StackExchange"
} |
Q:
cancel package documentation, shaded blocks to cancel
I would like to use some kind of colored cancel lines to mark simplifications. The cancel package documentation reads:
If you use the color package, then you can declare
\renewcommand{\CancelColor}{<color_command>}
and the cancellation marks will be printed in that color (e.g. \blue). However if you are using color, I recommend lightly shaded blocks rather then diagonal arrows fro cancelling.
I guess the lightly shaded blocks are a good idea, how would I implement this? (What package should I use?)
MWE
\documentclass[10pt,a4paper]{article}
\usepackage{cancel}
\usepackage{xcolor}
\begin{document}
\[ \frac{\cancel{a}b}{4\cancel{a}} \]
\renewcommand{\CancelColor}{\color{blue}}
\[ \frac{\cancel{(a+4)}\cdot 3}{\cancel{a+4}} \]
\end{document}
A:
I assume the author is suggesting to use something like \colorbox. You can either add a background shade, or shade the font using a different colour. Some options to consider:
\documentclass{article}
\usepackage{cancel,xcolor}
\newcommand{\shadedbox}{\colorbox{black!5}}
\newcommand{\cancelbox}[1]{{\color{black!50}#1}}
\begin{document}
\[
\frac{\cancel{a}b}{4\cancel{a}}
\]
\renewcommand{\CancelColor}{\color{blue}}
\[
\frac{\cancel{(a + 4)}\cdot 3}{\cancel{a + 4}}
\]
\renewcommand{\CancelColor}{}
\[
\frac{\shadedbox{$(a + 4)$}\cdot 3}{\shadedbox{$a + 4$}}
\]
\[
\frac{\shadedbox{\smash{$(a + 4)$}\vphantom{+}}\cdot 3}{\shadedbox{$a + 4$}}
\]
\[
\frac{\cancelbox{(a + 4)}\cdot 3}{\cancelbox{a + 4}}
\]
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Clickable links from ArrayList in JOptionPane
I'm trying to implement a history-button in my Browser class (created in eclipse), and I want the links in the button to be clickable. Here is my code that gets initiated when the user presses the button History:
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
In the code above, history is a list with all the webpages that has been previously visited.
I have tried using the method presented here:
clickable links in JOptionPane, and I got it to work. The problem is, this solution only lets me predefine URL:s, but I want my list history to be displayed, and the URLs in it to be clickable.
For example, if I have visited https://www.google.com and https://www.engadget.com, the list will look like this: history = [www.google.com, www.engadget.com], and both links should be separately clickable.
A:
This is the function that should be called when someone presses the history-button. It uses a JEditorPane with a HyperlinkListener. The string html in the code below adds the needed html-coding so that the HyperlinkListener can read and visit the webpages.
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "<a href=\"" + link + "\">" + link + "</a>\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to combine the outputs of multiple naive bayes classifier?
I am new to this.
I have a set of weak classifiers constructed using Naive Bayes Classifier (NBC) in Sklearn toolkit.
My problem is how do I combine the output of each of the NBC to make final decision. I want my decision to be in probabilities and not labels.
I made a the following program in python. I assume 2 class problem from iris-dataset in sklean. For demo/learning say I make a 4 NBC as follows.
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
import numpy as np
import cPickle
import math
iris = datasets.load_iris()
gnb1 = GaussianNB()
gnb2 = GaussianNB()
gnb3 = GaussianNB()
gnb4 = GaussianNB()
#Actual dataset is of 3 class I just made it into 2 class for this demo
target = np.where(iris.target, 2, 1)
gnb1.fit(iris.data[:, 0].reshape(150,1), target)
gnb2.fit(iris.data[:, 1].reshape(150,1), target)
gnb3.fit(iris.data[:, 2].reshape(150,1), target)
gnb4.fit(iris.data[:, 3].reshape(150,1), target)
#y_pred = gnb.predict(iris.data)
index = 0
y_prob1 = gnb1.predict_proba(iris.data[index,0].reshape(1,1))
y_prob2 = gnb2.predict_proba(iris.data[index,1].reshape(1,1))
y_prob3 = gnb3.predict_proba(iris.data[index,2].reshape(1,1))
y_prob4 = gnb4.predict_proba(iris.data[index,3].reshape(1,1))
#print y_prob1, "\n", y_prob2, "\n", y_prob3, "\n", y_prob4
# I just added it over all for each class
pos = y_prob1[:,1] + y_prob2[:,1] + y_prob3[:,1] + y_prob4[:,1]
neg = y_prob1[:,0] + y_prob2[:,0] + y_prob3[:,0] + y_prob4[:,0]
print pos
print neg
As you will notice I just simply added the probabilites of each of NBC as final score. I wonder if this correct?
If I have dont it wrong can you please suggest some ideas so I can correct myself.
A:
First of all - why you do this? You should have one Naive Bayes here, not one per feature. It looks like you do not understand the idea of the classifier. What you did is actually what Naive Bayes is doing internally - it treats each feature independently, but as these are probabilities you should multiply them, or add logarithms, so:
You should just have one NB, gnb.fit(iris.data, target)
If you insist on having many NBs, you should merge them through multiplication or addition of logarithms (which is the same from mathematical perspective, but multiplication is less stable in the numerical sense)
pos = y_prob1[:,1] * y_prob2[:,1] * y_prob3[:,1] * y_prob4[:,1]
or
pos = np.exp(np.log(y_prob1[:,1]) + np.log(y_prob2[:,1]) + np.log(y_prob3[:,1]) + np.log(y_prob4[:,1]))
you can also directly predit logarithm through gnb.predict_log_proba instead of gbn.predict_proba.
However, this approach have one error - Naive Bayes will also include prior in each of your prob's, so you will have very skewed distributions. So you have to manually normalize
pos_prior = gnb1.class_prior_[1] # all models have the same prior so we can use the one from gnb1
pos = pos_prior_ * (y_prob1[:,1]/pos_prior_) * (y_prob2[:,1]/pos_prior_) * (y_prob3[:,1]/pos_prior_) * (y_prob4[:,1]/pos_prior_)
which simplifies to
pos = y_prob1[:,1] * y_prob2[:,1] * y_prob3[:,1] * y_prob4[:,1] / pos_prior_**3
and for log to
pos = ... - 3 * np.log(pos_prior_)
So once again - you should use the "1" option.
| {
"pile_set_name": "StackExchange"
} |
Q:
"cumulative" vs "additive"
I was reading a brief theory of measurement from ftp://ftp.sas.com/pub/neural/measurement.html when a passage got me stuck. It says that
Consider a rat in a Skinner box who pushes a lever to get food pellets. The number of pellets dispensed in the course of an experiment is obviously an absolute-level measurement of the number of pellets dispensed. If number of pellets is considered as a measure of some other attribute, the measurement level may differ. As a measure of amount of food dispensed, the number of pellets is at the ratio level under the assumption that the pellets are of equal size; if the pellets are not of equal size, a more elaborate measurement model is required, perhaps one involving random measurement error if the pellets are dispensed in random order. As a measure of duration during the experiment, the number of pellets is at an ordinal level. [...] In the example above with number of pellets as a measure of duration, the errors would be cumulative, not additive, and the error variance would increase over time.
From reading about the classical model of error, I gather that an additive error is one that can be factored out by averaging many measurements. How does the cumulative error work? I nearly thought they are the same, but this passage makes it clear they are not.
A:
The cumulative error (also referred to as system error) - It's a single direction error. e.g, - If you are to measure 10 km run & your stopwatch is running 2 sec faster every minute. So at the end of the experiment to calculate error you will add 2 secs for each minute.
Additive errors (also referred as multiplicative) - Error term which can go either way based on the scenario. Good example is residuals in a linear regression model. The residuals can be both negative or positive based on your observation (unlike 1st scenario)
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
API to gather statistics from running JVM
For a class project, I would like to implement a Java application that connects to a local JVM and gathers statistics such as heap usage, number of threads, loaded classes etc. I've searched online for an API, third party of built-in, that would allow me to do this but I have so far been unsuccessful.
Does anyone know of an API that will allow me to connect to a running JVM and gather statistics?
A:
The following class demonstrates how to connect to a running JVM and establish a JMX connection, loading the JMX agent if necessary. It will print System Properties (this works through the JVM connection without the need for JMX) and the memory usage using the MemoryMXBean. It’s easy to extend to print other statistics using other MXBean types.
Note, that before Java 9, you have to add the tools.jar of your JDK to the classpath manually. In modular software, you have to add a dependency to the jdk.attach module.
import static java.lang.management.ManagementFactory.MEMORY_MXBEAN_NAME;
import static java.lang.management.ManagementFactory.newPlatformMXBeanProxy;
import java.io.*;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.*;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sun.tools.attach.*;
public class CmdLineTool
{
static final String CONNECTOR_ADDRESS =
"com.sun.management.jmxremote.localConnectorAddress";
public static void main(String[] args)
{
if(args.length!=1)
System.err.println("Usage: java CmdLineTool <pid>");
else if(printStats(args[0])) return;
System.out.println("Currently running");
for(VirtualMachineDescriptor vmd:VirtualMachine.list())
System.out.println(vmd.id()+"\t"+vmd.displayName());
}
private static boolean printStats(String id)
{
try
{
VirtualMachine vm=VirtualMachine.attach(id);
System.out.println("Connected to "+vm.id());
System.out.println("System Properties:");
for(Map.Entry<?,?> en:vm.getSystemProperties().entrySet())
System.out.println("\t"+en.getKey()+" = "+en.getValue());
System.out.println();
try
{
MBeanServerConnection sc=connect(vm);
MemoryMXBean memoryMXBean =
newPlatformMXBeanProxy(sc, MEMORY_MXBEAN_NAME, MemoryMXBean.class);
getRamInfoHtml(memoryMXBean);
} catch(IOException ex)
{
System.out.println("JMX: "+ex);
}
vm.detach();
return true;
} catch(AttachNotSupportedException | IOException ex)
{
ex.printStackTrace();
}
return false;
}
// requires Java 8, alternative below the code
static MBeanServerConnection connect(VirtualMachine vm) throws IOException
{
String connectorAddress = vm.startLocalManagementAgent();
JMXConnector c=JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress));
return c.getMBeanServerConnection();
}
static void getRamInfoHtml(MemoryMXBean memoryMXBean)
{
System.out.print("Heap:\t");
MemoryUsage mu=memoryMXBean.getHeapMemoryUsage();
System.out.println(
"allocated "+mu.getCommitted()+", used "+mu.getUsed()+", max "+mu.getMax());
System.out.print("Non-Heap:\t");
mu=memoryMXBean.getNonHeapMemoryUsage();
System.out.println(
"allocated "+mu.getCommitted()+", used "+mu.getUsed()+", max "+mu.getMax());
System.out.println(
"Pending Finalizations: "+memoryMXBean.getObjectPendingFinalizationCount());
}
}
The connect method of above solution requires Java 8. The alternative for older Java versions looks like
static MBeanServerConnection connect(VirtualMachine vm) throws IOException
{
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if(connectorAddress == null)
{
System.out.println("loading agent");
Properties props = vm.getSystemProperties();
String home = props.getProperty("java.home");
String agent = home+File.separator+"lib"+File.separator+"management-agent.jar";
try {
vm.loadAgent(agent);
} catch (AgentLoadException|AgentInitializationException ex) {
throw new IOException(ex);
}
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
while(connectorAddress==null) try {
Thread.sleep(1000);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
} catch(InterruptedException ex){}
}
JMXConnector c=JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress));
return c.getMBeanServerConnection();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Beamer overlay with columns - changing image and highlighting text
I am making a presentation to explain an algorithm which produces a picture. I want to use two columns to have the picture on one side and the algorithm on the other. I want to click through the algorithm highlighting successive steps in bold or a different colour and have the image change to show the relevant step as I go.
So far I have tried this:
\begin{frame}
\begin{columns}
\begin{column}{.5\linewidth}
\includegraphics<1>[width=\linewidth]{step1.pdf}
\includegraphics<2>[width=\linewidth]{step2+3.pdf}
\includegraphics<3>[width=\linewidth]{step4.pdf}
\includegraphics<4>[width=\linewidth]{step5.pdf}
\includegraphics<5>[width=\linewidth]{step6.pdf}
\includegraphics<6>[width=\linewidth]{step7.pdf}
\includegraphics<7>[width=\linewidth]{result.pdf}
\end{column}
\begin{column}{.5\linewidth}
\begin{itemize}
\item \only<1>{\color{blue}} Start with cube (generation 0)
\item \only<2>{\color{blue}} Split into 8 sub-cubes (generation 1)
\item \only<2>{\color{blue}} Select fertile sub-cubes
\item \only<3>{\color{blue}} Split fertile sub-cubes (generation 2)
\item \only<4-6>{\color{blue}} Repeat until maximum generation reached
\item \only<7>{\color{blue}} Place stars
\end{itemize}
\end{column}
\end{columns}
\end{frame}
But that seems to make all the \items blue until I reach that step, then turn them black. I want them all to be black except the one I am highlighting.
A:
One option using the alert@ specification for overlays to highlight text on desired slides; for example,
\item<3-|alert@3>
shows the item text from the third slide on and highlights it on the third slide only. The color used to highlight the text can be changed using
\setbeamercolor{alerted text}{fg=<color>}
The code:
\documentclass{beamer}
\begin{document}
\begin{frame}
\begin{columns}
\begin{column}{.5\linewidth}
\includegraphics<1>[width=\linewidth]{example-image}
\includegraphics<2>[width=\linewidth]{example-image-a}
\includegraphics<3>[width=\linewidth]{example-image-b}
\includegraphics<4>[width=\linewidth]{example-image-c}
\includegraphics<5>[width=\linewidth]{example-image-16x9}
\includegraphics<6>[width=\linewidth]{example-image-16x10}
\includegraphics<7>[width=\linewidth]{example-image-golden}
\end{column}
\begin{column}{.5\linewidth}
\setbeamercolor{alerted text}{fg=blue}
\begin{itemize}
\item<1-|alert@1> Start with cube (generation 0)
\item<2-|alert@2> Split into 8 sub-cubes (generation 1)
\item<2-|alert@2> Select fertile sub-cubes
\item<3-|alert@3> Split fertile sub-cubes (generation 2)
\item<4-|alert@4-6> Repeat until maximum generation reached
\item<7-|alert@7> Place stars
\end{itemize}
\end{column}
\end{columns}
\end{frame}
\end{document}
An animation of the result:
| {
"pile_set_name": "StackExchange"
} |
Q:
text и textvariable для одного виджета одновременно
Мне нужно чтобы на этом Label отображался постоянно определенный текст, а в конце его было число, которое менялось бы. Я не знаю как это сделать.
Единственное что приходит в голову это IntVar, но если я укажу в опциях виджета опцию text и одновременно опцию textvariable, то отображаться на этом виджете будет только последняя. Надо что-то вроде такого, или вообще другое решение
number = IntVar()
number.set(1)
Label(root, text="Number = ", textvariable=number)
Потом командой менять эту переменную
def change():
number.set(number.get + 1)
Команда вызывается кнопкой
A:
FIX_PART = "Number = "
var_part = "1"
str_num = StringVar()
str_num.set(FIX_PART + var_part)
Label(root, textvariable=str_num)
def change():
old_val = str_num.get()
var_part = old_val[len(FIX_PART):]
num = int(var_part)
vart_part = str(num + 1)
str_num.set(FIX_PART + var_part)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is having a unique key to encrypt data not sufficient
Is it necessary to use a unique Initialization Vector (IV) with various cipher modes of operation (e.g. CBC) even though I use a unique key to encrypt plain text every time?
It is said that an IV needs to be unique but not secret, every time a new piece of information is encrypted.
Can't we just make IV as unique and secret? Will it
mean that the IV can now be treated as a secret Key?
A:
Can't we just make IV as unique and secret? Will it mean that the IV
can now be treated as a secret Key?
Key distribution is hard, and there's no reason to make the IV a secret.
If Alice wants to send a message to Bob using symmetric encryption both must somehow already know the encryption key and the IV. To share the encryption key Alice and Bob could meet up in person once, then use the shared key to send many messages without having to physically meet again.
Now if the IV is a secret, and the IV must also change every message then Alice and Bob now have to meet to share the secret IV for every message. If they have to meet every time, then why not just share the message when they meet?
Seeing as the encryption is not weakened by an attacker knowing the IV, they might as well save themselves the hassle of meeting in person by just sending the IV with the encrypted message, rather than trying to securely exchange it. It saves them both a lot of hassle, and they're no less secure.
| {
"pile_set_name": "StackExchange"
} |
Q:
bounty for meta
My question Full site not responding to iPad has not been paid much attention by the moderators of stack exchange. I wish there were bounty for meta questions.
A:
As a workaround, try posting on Meta Stack Overflow, where it should receive more attention. Also, since MSO has a full-fledged reputation system of it's own, you can post bounties on that site if your issue doesn't receive a response.
Bounties are supposed to be used to draw attention to issues on meta, not just for rep, but I think the community team has a hard time keeping up with 80+ child meta forums.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server: Granting db_datawriter on all databases
I want to manage permissions and access to a SQL Server database server on a development machine. I've created a local windows group (called DBReaderGroup) and assigned various people to it. The group was created as a SQL Server login successfully:
create login [MYMACHINE\DBReaderGroup] from windows
My goal is to grant this group read/write access to all databases (which are constantly being added and dropped). Is it possible to configure the right settings so that SQL Server manages this?
My biggest challenge is that each time a db is created, I have to update the "User Mapping" settings for this group on the new database.
Am I missing something simple?
A:
Add the login to the Model database in the db_datawriter role, and any new database will give that login full write access by default. This won't work, however, if the databases being added are from other sources (ie restored versions).
| {
"pile_set_name": "StackExchange"
} |
Q:
build.gradle.kts syntax sugar - explanation
I was searching in the Internet but I have not found answer for my question regarding to build.gradle.kts syntax.
I haven't found any syntax regarding to below application plugin adding:
plugins {
// Apply the Kotlin JVM plugin to add support for Kotlin on the JVM.
id("org.jetbrains.kotlin.jvm") version("1.3.21")
// Apply the application plugin to add support for building a CLI application.
application
//id("kotlin-android")
I mean, what kind of syntax stay behind application?
It only looks like a class member name. Maybe is it a function call? but it has no brackets.
I don't catch this kotlin syntax sugar.
Additional, I have not found plugins (and others blocks) implementation in gradle repository. Someone know where it is located? I am just curious how it works.
A:
If you go to the implementation of application it should bring you to the source:
/**
* The builtin Gradle plugin implemented by [org.gradle.api.plugins.ApplicationPlugin].
*
* Visit the [plugin user guide](https://docs.gradle.org/current/userguide/application_plugin.html) for additional information.
*
* @see org.gradle.api.plugins.ApplicationPlugin
*/
inline val org.gradle.plugin.use.PluginDependenciesSpec.`application`: org.gradle.plugin.use.PluginDependencySpec
get() = id("org.gradle.application")
So application is just an extension function on PluginDependenciesSpec or plugins { }
| {
"pile_set_name": "StackExchange"
} |
Q:
how to manage/design API access on GCP?
Let's say I have 3 datasets on Big Query -- Dataset A, Dataset B and Dataset C.
Also, I have 3 clients -- Client A, Client B and Client C.
And, I have a simple web app deployed in App Engine with an API, say, '/weather'.
The API simply writes a query from the client's input and reads and writes on the datasets, using Big Query APIs, and returns the result.
Clients A, B and C have their own API key so that they can use the weather API.
But I want to restrict API access such that Client A can only access Dataset A, Client B can only access Dataset B and Client C can only access Dataset C.
But, if Client A wants to access Dataset B too, I would also want to be able to easily grant Client A access to Dataset B without having to re-deploy my app.
I've done a lot of reading on Cloud Endpoints, App Engine and Big Query, but I couldn't really find any solutions.
What is the best way to achieve this hopefully maybe at Cloud Endpoints level or App Engine level or Big Query level? If not, at back-end Python level (I am using Flask)
The last resort I can think of would be, I would have to create a simple dictionary in a DB where the key is the API key and the value is a list of datasets that it can access. So, when a client hits the endpoint with their own API key, I have to check and see whether the client has access to the dataset or not.
But that would be quite an expensive operation and I would like to take care of this at GCP level or back-end python level.
Please let me know if there is any features on GCP that can help me achieve this.
A:
When you perform access control, you have 2 parts: Authentication and Authorization.
Cloud Endpoint is a good solution if you want to secure your API with a weak authentication secret (API Key). I wrote an article on this.
Here, with your 3 clients, you will authenticate only 3 projects (no USERS, only PROJECTS). You also have the APIkey value in the query param. But it's only authentication.
If you want an authorization layer, to say WHO have access to WHAT, here, the client A has only access to the Dataset A, you have to code it by yourselves.
In my company, we keep these data into Firestore: serverless, quick, free (up to 50k read per day)
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof about the Sylow $2$-subgroups of permutation group such that each element has at most two fixed points
Let $G$ be a finite, transitive, nonregular permutation group on $\Omega$ such that every element of $g \in G^{\#} := G \setminus \{ 1_G \}$ has at most two fixed points. Suppose further that $|\Omega| \ge 4$. (*)
Lemma: Suppose that $S \in Syl_2(G)$ is such that $S_{\omega}\ne 1$. Then $S$ is dihedral or semidihedral and $|S_{\omega}| = 2$ or $G_{\omega}$ contains a subgroup of index at most $2$ of $S$. In the second case, if $S \nleq G_{\omega}$, then there exists $\delta \in \Omega$ such that $\omega \ne \delta, S_{\omega} = S_{\delta}$ and some element in $S$ interchanges $\omega$ and $\delta$.
Proof: Let $\Delta := \omega^S$ and let $n,m \in \mathbb N_0$ be such that $|S_{\omega}| = 2^n$ and $|S : S_{\omega}| = 2^m$. First suppose that $m \ge 2$. Let $d$ denote the number of fixed points of $S_{\omega}$ on $\Delta$. Note that $d$ is even, but $d\ne 0$ and thus the above hypothesis (*) about $G$ implies that $S_{\omega}$ acts semiregularly on $\Delta \setminus \mbox{fix}_{\Delta}(S_{\omega})$. So now choose $a \in \mathbb N_0$ such that $|\Delta| = d + a\cdot 2^n$. As $n \ge 1$ and $|\Delta| = 2^m \ge 4$, we see that $d = 2$ and hence $2^m = 2\cdot (1 + a\cdot 2^{n-1})$. This implies that $a\cdot 2^{n-1}$ is odd, in particular $n = 1$. [...]
This is the beginning of the proof. Why does (*) implies that $S_{\omega}$ acts semiregular on $\Delta \setminus \mbox{fix}_{\Delta}(S_{\omega})$, and where is this facts used in the further argumentation? Also choosing $a$ assumes that $m > n$, or not? So why that, and also I do not see why $2^m = d + a\cdot 2^n$ with $n \ge 1, m \ge 2$ implies $d = 2$, this equation has many other solutions for $a$ and $d$, for example $m = 4, n = 1, a = 1$, then $d = 12$.
A:
Since $d$ is even and $d \neq 0$, we have $d\geq 2$; in other words $d=|\text{fix}_\Delta(S_\omega)| \geq 2$. Now, by assumption, no nonidentity element $g$ of $S_\omega$ fixes more than two points of $\Delta$, and yet it fixes the (at least two) points of $\text{fix}_\Delta(S_\omega)$, so it cannot fix any other points of $\Delta$; i.e. $S_\omega$ acts semiregularly on $\Delta\setminus\text{fix}_\Delta(S_\omega)$. This means that every orbit of $S_\omega$ on $\Delta\setminus\text{fix}_\Delta(S_\omega)$ has size $|S_\omega|=2^n$; thus summing the sizes of the orbits gives the relation $|\Delta|=d+a\cdot 2^n$, where $a$ is the number of orbits of $S_\omega$ on $\Delta\setminus\text{fix}_\Delta(S_\omega)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open Android Device Monitor in latest Android Studio 3.1
Recently I updated my android studio, after the update, I am unable to find android device monitor option in the tools section. In the previous update it was there in tools->android->android device monitor. But now in the updated version, it is not present. You can check screenshot of my android studio.
A:
If you want to push or pull your files from devices monitor now android studio offers something better then android monitor. Just take a look at right side of your studio there is an option device file explorer. Open it and you are good to go. Select your device from top dropdown and rest of everything is pretty much the same as it was in android monitor. Below is the screen Shot attached to give you the exact location and idea.
A:
Now you can use device file explorer instead of device monitor. Go to
view > tool windows > device file explorer
screenshot: opening device file explorer in android studio 3.1.3
More details
Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
Select a device from the drop down list.
Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.
Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.
screenshot: The Device File Explorer tool window
When exploring a device's files, the following directories are particularly useful:
data/data/app_name/
Contains data files for your app stored on internal storage
sdcard/
Contains user files stored on external user storage (pictures, etc.)
Note: Not all files on a hardware device are visible in the Device
File Explorer. For example, in the data/data/ directory, entries
corresponding to apps on the device that are not debuggable cannot be
expanded in the Device File Explorer.
A:
To start the standalone Device Monitor application, enter the following on the command line in the android-sdk/tools/ directory:
monitor
You can then link the tool to a connected device by selecting the device from the Devices pane. If you have trouble viewing panes or windows, select Window > Reset Perspective from the menu bar.
Note: Each device can be attached to only one debugger process at a time. So, for example, if you are using Android Studio to debug your app on a device, you need to disconnect the Android Studio debugger from the device before you attach a debugger process from the Android Device Monitor.
reference : https://developer.android.com/studio/profile/monitor.html
=> You Can change minSdkVersion 16 And open Device File Explorer
Device File Explorer work same as a Android Device Monitor
See Below Image:
| {
"pile_set_name": "StackExchange"
} |
Q:
Efficient AES - Use of T-tables
I'm really in trouble! I'm trying to understand how the T-tables in AES encryption work. But I don't know if I get the point.
What I understood is that they are used to reduce the whole computation of the iteration of AES just looking at the T-boxes and the XOR operation.
Now, what I got is that:
State M Matrix
┏ ┓ ┏ ┓
┃ d4 e0 b8 1e ┃ ┃ 02 03 01 01 ┃
┃ bf b4 41 27 ┃ ┃ 01 02 03 01 ┃
┃ 5d 52 11 98 ┃ ┃ 01 01 02 03 ┃
┃ 30 ae f1 e5 ┃ ┃ 03 01 01 02 ┃
┗ ┛ ┗ ┛
I have my State matrix and M matrix composed by 4X4 bytes. Each t-table should receive in input one byte and give in output 4 bytes.
Now, in order to create the t-tables i will have in the first table:
T0=(d4*02)+(d4*01)+(d4*01)+(d4*03)
(e0*02)+(e0*01)+(e0*01)+(e0*03)
(b8*02)+(b8*01)+(b8*01)+(b8*03)
(1e*02)+(1e*01)+(1e*01)+(1e*03)
Then the second table should be:
T0=(bf*03)+(bf*02)+(bf*01)+(bf*01)
(b4*03)+(b4*02)+(b4*01)+(b4*01)
(41*03)+(41*02)+(41*01)+(41*01)
(27*03)+(27*02)+(27*01)+(27*01)
And so on...until I'll have 4 tables. Am I right? Now...How can I use these tables?
A:
(You should take a look at page 18 of FIPS 197 where it describes the MixColumns transform).
You're close. Swap the order of your matrices so that you have:
|02 03 01 01| |d4 e0 b8 1e|
|01 02 03 01| |bf b4 41 27|
|01 01 02 03| |5d 52 11 98|
|03 01 01 02| |30 ae f1 e5|
And then you compute the new columns. i.e. the new first column is:
|02 03 01 01| |d4|
|01 02 03 01| |bf|
|01 01 02 03| |5d|
|03 01 01 02| |30|
Which equals:
|02*d4 + 03*bf + 01*5d + 01*30|
|01*d4 + 02*bf + 03*5d + 01*30|
|01*d4 + 01*bf + 02*5d + 03*30|
|03*d4 + 01*bf + 01*5d + 02*30|
And so on.
Do you See the pattern in the sum? Each column in the matrix is multiplied by an element in the column and then they are summed. We can precompute these columns, and compute the above sum using 4 table lookups and 32-bit XOR operations.
The tables will be arrays of 32-bit values which look like this ("|" denotes byte concatenation):
T0[00] = 02*00 | 01*00 | 01*00 | 03*00
T0[01] = 02*01 | 01*01 | 01*01 | 03*00
...
T0[FF] = 02*FF | 01*FF | 01*FF | 03*FF
T1[00] = 03*00 | 02*00 | 01*00 | 01*00
T1[01] = 03*01 | 02*01 | 01*01 | 01*01
...
T1[FF] = 03*FF | 02*FF | 01*FF | 01*FF
T2[00] = 01*00 | 03*00 | 02*00 | 01*00
T2[01] = 01*01 | 03*00 | 02*00 | 01*00
...
T2[FF] = 01*FF | 03*FF | 02*FF | 01*FF
T3[00] = 01*00 | 01*00 | 03*00 | 02*00
T3[01] = 01*01 | 01*01 | 03*01 | 02*01
...
T3[FF] = 01*FF | 01*FF | 03*FF | 02*FF
Using four tables, you can compute the new state matrix with 16 table look-ups and 12 32-bit XOR operations.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.