text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How can I use data annotation validations in wcf rest service data contracts
I am using WCF rest service in my application. Just need to confirm whether I can use data annotations validations in data contracts like I use in MVC models. If yes how can I?
A:
Data annotations was not designed for WCF use:
The System.ComponentModel.DataAnnotations namespace provides attribute
classes that are used to define metadata for ASP.NET MVC and ASP.NET
data controls.
From MSDN: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx
There is some alternatives to do the same in WCF, like this:
https://wcfdataannotations.codeplex.com/
And this: https://msdn.microsoft.com/en-us/library/ff647875.aspx
Hope it helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mysql select from subquery is not working
I want to create report of total number of orders and total earning that are belong to each users.
SELECT w.id, CONCAT_WS(' ', w.fname, w.sname) AS full_name,
te.total_earnings, te.assigned_jobs
FROM users AS w
LEFT JOIN (
SELECT wr.user_id,
COUNT(o.order_id) AS assigned_jobs,
SUM(o.fee) AS total_earnings
FROM (
SELECT DISTINCT user_id, order_id, withdrawn
FROM work_records
) AS wr
LEFT JOIN orders o ON o.order_id = wr.order_id
WHERE wr.withdrawn IS NULL
AND o.verified != 'rejected'
) AS te ON te.user_id = w.id
WHERE w.status = 1
orders work_records
___________________ _________________________________
| order ID | fee | | id | order_id | fee | user_id |
------------------- ---------------------------------
| 334 | 425 | | 1 | 334 | 50 | 6 |
| 2 | 334 | 50 | 6 |
This query works on single user id. But it doesn't work if I want to get report of all users.
Any advise thanks?
A:
Here is the answer for others. How ever the query is slower. But if you have faster query would greate to share.
SELECT w.id, CONCAT_WS(' ', w.fname, w.sname) AS full_name,
te.total_earnings, te.assigned_jobs
FROM users AS w
LEFT JOIN (
SELECT w.id,
SUM(work.earnings) AS total_earnings,
COUNT(work.order_id) AS assigned_jobs
FROM users AS w
LEFT JOIN (
SELECT wr.order_id, wr.writer_id, o.fee AS earnings
FROM work_records wr
LEFT JOIN orders o ON o.order_id = wr.order_id
WHERE wr.withdrawn IS NULL
AND o.verified = 'verified'
GROUP BY wr.order_id
) work ON work.writer_id = w.id
GROUP BY work.writer_id
) te ON te.id = w.id
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django Test Runner Not Finding Test Methods
I recently upgraded from Django 1.4 to 1.9 and realized something weird was going on with my tests. Here is the project structure:
project
manage.py
app/
__init__.py
tests/
__init__.py
test_MyTests.py
The test_MyTests.py file looks like this:
from django.test import TestCase
class MyTests(TestCase):
def test_math(self):
self.assertEqual(2, 2)
def test_math_again(self):
self.assertEqual(3, 3)
The test runner can find all of the tests when I run
./manage.py test app or ./manage.py test app.tests. However when I try running ./manage.py test app.tests.MyTests I get:
File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'MyTests'
If I change the test class name to test_MyTests I can then run ./manage.py test app.tests.test_Mytests and it will find all tests. I was reading the Django docs though and it seems the file name and class name don't have to be the same. In either case that I showed above I still can't run individual tests like this, ./manage.py test app.tests.MyTests.test_math
I would like to be able to run individual tests and test classes, can someone help me here? Thanks.
A:
In app.tests.test_MyTests part test_MyTests is module name, not class. To run test_math you should specify full path to this method:
python manage.py test app.tests.test_MyTests.MyTests.test_math
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Executing function on objects of name 'i' within for-loop in R
I am still pretty new to R and very new to for-loops and functions, but I searched quite a bit on stackoverflow and couldn't find an answer to this question. So here we go.
I'm trying to create a script that will (1) read in multiple .csv files and (2) apply a function to strip twitter handles from urls in and do some other things to these files. I have developed script for these two tasks separately, so I know that most of my code works, but something goes wrong when I try to combine them. I prepare for doing so using the following code:
# specify directory for your files and replace 'file' with the first, unique part of the
# files you would like to import
mypath <- "~/Users/you/data/"
mypattern <- "file+.*csv"
# Get a list of the files
file_list <- list.files(path = mypath,
pattern = mypattern)
# List of names to be given to data frames
data_names <- str_match(file_list, "(.*?)\\.")[,2]
# Define function for preparing datasets
handlestripper <- function(data){
data$handle <- str_match(data$URL, "com/(.*?)/status")[,2]
data$rank <- c(1:500)
names(data) <- c("dateGMT", "url", "tweet", "twitterid", "rank")
data <- data[,c(4, 1:3, 5)]
}
That all works fine. The problem comes when I try to execute the function handlestripper() within the for-loop.
# Read in data
for(i in data_names){
filepath <- file.path(mypath, paste(i, ".csv", sep = ""))
assign(i, read.delim(filepath, colClasses = "character", sep = ","))
i <- handlestripper(i)
}
When I execute this code, I get the following error: Error in data$URL : $ operator is invalid for atomic vectors. I know that this means that my function is being applied to the string I called from within the vector data_names, but I don't know how to tell R that, in this last line of my for-loop, I want the function applied to the objects of name i that I just created using the assign command, rather than to i itself.
A:
Inside your loop, you can change this:
assign(i, read.delim(filepath, colClasses = "character", sep = ","))
i <- handlestripper(i)
to
tmp <- read.delim(filepath, colClasses = "character", sep = ",")
assign(i, handlestripper(tmp))
I think you should make as few get and assign calls as you can, but there's nothing wrong with indexing your loop with names as you are doing. I do it all the time, anyway.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Asymptotic expansion of $\operatorname{arsinh}(c/t)$ as $t\rightarrow 0$
let $c>0$ be a constant and let $f:(0,\infty)\rightarrow\mathbb{R}$ be defined as $f(t):=\operatorname{arsinh}(\frac{c}{t})$, where $\operatorname{arsinh}$ denotes the inverse of sinus hyperbolicus. That function has a singularity at $t=0$, and I am interested in an asymptotic expansion in powers of $t$ as $t\rightarrow 0$.
By just guessing and using the rule of l'Hospital, I proved that $f(t)\sim \frac{c}{t}$ as $t\rightarrow 0$. Is it possible to obtain a full asymptotic expansion by a systematic approach?
Best wishes
A:
You have the following expansion of $\operatorname{argsinh}x$, based on the Taylor expansion of its derivative $\frac1{\sqrt{1+x^2}}$:
\begin{align}
&\operatorname{argsinh}x=\\
&\phantom{{}={}}x-\frac12\frac{x^3}3+\frac{1\cdot 3}{2\cdot 4}\frac{x^5}5-\frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\frac{x^7}7 +\dots+(-1)^{2n+1}\frac{(2n-1)!!}{(2n)!!}x^{2n+1}+\dotsm
\end{align}
A:
Reference Gradshtyn & Ryshik
Gradshteyn, I. S.; Ryzhik, I. M.; Zwillinger, Daniel (ed.); Moll, Victor (ed.), Table of integrals, series, and products. Translated from the Russian. Translation edited and with a preface by Victor Moll and Daniel Zwillinger, Amsterdam: Elsevier/Academic Press (ISBN 978-0-12-384933-5/hbk; 978-0-12-384934-2/ebook). xlv, 1133 p. (2015). ZBL1300.65001.
Formula 1.641.2
As $z \to 0$, which corresponds to $t \to \infty$:
\begin{align}
\operatorname{asinh} z &= z - \frac{1}{2\cdot3}\;z^3
+ \frac{1\cdot3}{2\cdot4\cdot5}\;z^5
-\frac{1\cdot3\cdot5}{2\cdot4\cdot6\cdot7}\;z^7+\dots
\\ &=\sum_{k=0}^\infty
\frac{(-1)^k(2k)!z^{2k+1}}{2^{2k}(k!)^2(2k+1)}
= z\;{}_2F_1\left(\frac{1}{2},\frac{1}{2};\frac{3}{2};-z^2\right)
\end{align}
Formula 1.642.1
As $z \to \infty$, which corresponds to $t \to 0$:
\begin{align}
\operatorname{asinh} z &= \log(2z) + \frac{1}{2}\;\frac{1}{2z^2}
-\frac{1\cdot3}{2\cdot4}\;\frac{1}{4z^4} +\dots
\\ &= \log(2z) + \sum_{k=0}^\infty
\frac{(-1)^{k+1}(2k)!z^{-2k}}{2^{2k}(k!)^2 2k}
\end{align}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to organize steps from several test functions when using pytest?
I have three test cases with some dependency of two of them on the third one. Namely, tests test_inner_1 and test_inner_2 are independent from each other but their execution makes no sense if test_outher fails. They both should be run if test test_outher passes and both should be skipped if test_outher fails.
The pytest manual https://pytest.org/latest/example/simple.html
presents some simple example how to implement incremental testing with
test steps. I am trying to apply this approach to my situation and
to implement something like that:
content of conftest.py:
import pytest
def pytest_runtest_makereport(item, call):
if "incremental" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_runtest_setup(item):
if "incremental" in item.keywords:
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" % previousfailed.name)
content of test_example.py:
import pytest
@pytest.mark.incremental
class TestUserHandling:
def test_outher(self):
assert 0
class TestInner:
def test_inner_1(self):
assert 0
def test_inner_2(self):
pass
Unfortunately, I have got the output
==================== 2 failed, 1 passed in 0.03 seconds ====================
while expected to get the output
=================== 1 failed, 2 xfailed in 0.03 seconds ====================
How to correct the conftest.py to get the desired behaviour?
A:
There is a plugin for pytest called pytest-dependency that does what you want to do in this case.
Your code can look like this:
import pytest
import pytest_dependency
@pytest.mark.dependency()
def test_outher():
assert 0
@pytest.mark.dependency(depends=["test_outher"])
def test_inner_1():
assert 0
@pytest.mark.dependency(depends=["test_outher"])
def test_inner_2():
pass
Output is:
=================================== FAILURES ===================================
_________________________________ test_outher __________________________________
@pytest.mark.dependency()
def test_outher():
> assert 0
E assert 0
test_example.py:6: AssertionError
===================== 1 failed, 2 skipped in 0.02 seconds ======================
You can use classes of course, but for this example it is not necessary. If you need example with classes, let me know.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What kind of training is required to be a civilian employee / resident on a starship?
The Enterprise D in TNG has civilian employees on board, such as Mot the barber, Ms. Kyle the school teacher, and Guinan's wait staff in Ten Forward. There are also families on board.
What training are they required to complete in order to be permitted to live on a starship (apart from training required for their own careers)?
Are they required to have training in basic ship functions and emergency procedures (in case of a ship disaster), or in basic combat training (in case the ship is boarded by hostiles)? If so, is this training normally completed prior to becoming a resident on the ship, or is it typically completed on board?
A:
Based on what we see in the shows, the answer is probably very little. The Enterprise-D, unlike other ships is less of a military vessel and more of a mobile Starbase. Arriving non-military personnel are likely given a brief (verbal) tour of the ship's facilities, shown where the emergency shelters are and told what to do in the event of various catastrophes, as you would for someone who was going to work as a barmaid on a cruise liner (albeit with probably more emphasis on what to do if you lose air pressure or the gravity fails than on how to avoid drowning).
In the event of catastrophic failure of life support, as for instance happens in TNG : Night Terrors and TNG : Disaster, we see the Enterprise itself (via lighting, visual and audio cues) and enlisted crew directing civilians to designated shelter areas such as Ten Forward, automated lifeboats and automated transporters. The need for a non-officer to do anything proactive in an emergency, aside from following orders, appears to be essentially nil.
With regard to when these emergency procedures are laid out, probably the closest we get is in the TNG episode "A Matter of Honor". New personnel are immediately shown to an 'indoctrination session'. I would assume that this includes a presentation about what to do in the event of a red-alert, what to do if your dreams manifest themselves, what to do if you find yourself pregnant by a ball of glowing light, etc.
RIKER: Welcome aboard the Enterprise. I'm Commander William Riker, your First Officer. Those of you who are here as replacements
will step outside follow Lieutenant Lewis. He will assign you to your
crew quarters. (to the Benzite) Ensign, you're here on the exchange
programme. If you'll just follow Mister Crusher.
...
RIKER: It's nice to have you here, Ensign. There will be a briefing and indoctrination session in fifteen minutes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to creat a Human Design Chart in Android
How Can I draw Human Design Chart as shown in Image. I have all the coordinates of it now I do not know how to draw it in android. As there are too many coordinates of each total 64 lines and triangles how can I draw it
I have all the coordinates in csv files.
Please Help. I am searching for it for too long I do not know how to do.
A:
Simply Import all your Coordinates in Database or .csv file and use this method
Paint paint = new Paint();
paint.setColor(Color.GRAY);
paint.setAntiAlias(true);
paint.setStrokeWidth(1);
Path path = new Path();
path.moveTo(x,y);
path.lineTo(x,y);
path.close();
canvas.drawPath(path, paint);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Htaccess mod_rewrite conditions and parameters
i need some help regarding rewrite rules of .htaccess, and some of the regular expressions there.
i alredy have some rewrite rules definitions in htaccess, so if i call html file, it is executed as php.
all i need now is if i open in browser like:
http://mydomain.com/some-string/12345.html
to call file article.php?id=12345
(id value can only be integer)
if you can help he how to achieve this...
thank you in advance!
A:
Based on @Michiel answer:
RewriteEngine On
RewriteRule ^([a-z\-]+)\/([0-9]*)\.html$ article.php?id=$2 [NC,L]
This will catch (lower-case letters and hyphens)/(numbers).html and redirect to article.php?id=numbers. i.e. this will now catch cars/13.html, mens-shorts/27.html, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can i find the largest gameobject size from array?
void Awake()
{
Clone();
objects = GameObject.FindGameObjectsWithTag("ClonedObject");
float size = objects[0].transform.localScale.x;
}
The float size is just for a test.
Inside Clone() function i set the size for each gameobject
for (var i = 0; i < ObjectCount; i++)
{
var o = Instantiate(ObjectToCreate);
o.tag = "ClonedObject";
o.transform.SetParent(base.gameObject.transform);
o.transform.localScale = new Vector3(ObjectSize, ObjectSize, ObjectSize);
The variable ObjectSize is global
I want in the Awake function to find the biggest size of a gameobject form all the gameobjects in the array. So float size will get the biggest gameobject size.
Then to find the gameobject radius so size/2 i think.
Then later i want to use the variable size in other script so i will make it global public and static. But first how do i find the biggest gameobject by size from the array ?
A:
But first how do i find the biggest gameobject by size from the array
?
inside your Awake() method you can simply use a for each loop to find the largest value.
float LargestSize = 0;
foreach(var element in objects){
float Size = element.transform.localScale.x;
if(Size > LargestSize) LargestSize = Size;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove space around clickable image
I'm trying to place a clickable image in the center using padding.
The problem is that there is a lot of unwanted clickable space around the image now. I can even click the image from the edges of my screen although the image is in the middle of the screen.
If I remove padding it works but then the image isn't were I want.
Is there a way to fix this?
My HTML:
<body>
<div class="page">
<div class="body">
<div id="clicktoenter">
<h1><a href="home.html" class="home" title="Home Link"></a></h1>
</div>
</div>
</div>
</body>
My CSS:
.body{
width:940px;
margin:0 auto;
padding:0 10px;
overflow:hidden;
}
.home{
margin-bottom: 10px;
width: 460px;
height:460px;
display:block;
background:url(../images/image.png) center center no-repeat;
padding:200px 200px;
}
.home:hover{
background:url(../images/imageclick.png) center center no-repeat;
padding:200px 200px;
}
A:
Change your margin to this and it will center, not using padding.
.home{
margin:200px auto 200px auto;
width: 460px;
height:460px;
display:block;
background:url(../images/image.png) center center no-repeat;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Speeding up page transitions in jQuery Mobile 1.1 for iPhone apps built with PhoneGap?
Page transitions in JQM 1.1 still incur a 1-2 second delay on iPhones, which compromises the user experience.
Has anyone figured out how to make the page transitions in JQM 1.1 feel more native? We know there are alternative frameworks like Zepto, but we prefer using JQM if possible.
We're using PhoneGap to distribute the app on iOS devices.
A:
I use a couple of methods which together produce a quite satisfactory result.
1) Energize.js - https://github.com/davidcalhoun/energize.js removes tap delay on all clicks/taps
2) In your jQM initiation add:
$.mobile.buttonMarkup.hoverDelay = 0;
3, 4 & 5) Use
$( "#YourPage" ).delegate("#YourButton", 'tap', function(event) {
$.mobile.showPageLoadingMsg();
$.mobile.changePage( "YourPage", { transition: "slide"} );
e.stopImmediatePropagation();
return false;
} );
3) Instead of using a normal anchor link which jQM then converts to a mobile.changePage - Do that part yourself and (potentially) shave off a few ms
4) Delegate it to tap instead of click (although with energize.js present I can't tell any difference)
5) Show a loading message before you start transferring. If the the site you are navigating to is complicated it might take a while to generate, if you display a loading message, at least the user knows something is happening
6) Preload content using
$.mobile.loadPage( "YourPage" );
This might be a bit overkill due to overlap but hopefully using these techniques you'll be able to make your app a bit more responsive!
EDIT - Bonus: Here's a blog post which covers three other techniques for speeding up PhoneGap jQuery Mobile apps: http://therockncoder.blogspot.no/2012/06/three-quick-performance-tips-for.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
uber/jaeger-client-node: backend wont receive data
I'm currently looking into different openTracing Tracer-Implementations.
I want to use uber/jaeger-client-node but the backend won't receive my traces.
Here is what I did:
I started the all-in-one docker image:
docker run -d -p5775:5775/udp -p16686:16686 jaegertracing/all-in-one:latest
Next, i wrote a simple example application:
Gist
But when I go to Jaeger UI, nothing is shown about the example service.
What did I do wrong?
Thanks
A:
There are two issues here. One is that your code sets the port for Jaeger client to 5775. This port expects a different data model than what Node.js client sends, you can remove the agentHost and agentPort parameters and rely on defaults.
The second issue is that you're running the Docker image without exposing the required UDP port. The correct command is shown in the documentation, as of today it should be this (one long line):
docker run -d -p5775:5775/udp -p6831:6831/udp -p6832:6832/udp \
-p5778:5778 -p16686:16686 -p14268:14268 jaegertracing/all-in-one:latest
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Anchoring an item in place for vertical scrolling but not horizontal
I have a menu that is contained in a div with the class float. float is given below:
.float {
display:block;
position:fixed;
top: 20px;
left: 0px;
z-index: 1999999999;
}
* html .float {position:absolute;}
The above css class makes it so that the menu stays in place regardless of how the user scrolls (the *html is for internet explorer). However, I need to make it so that it only stays in place when the user scrolls vertically. It should move left to right if the user scrolls left or right. I can't seem to find any css to allow for this, and any javascript I run into is choppy in adjusting the item. The javascript below works but I'd like something a bit smoother if possible. I have the body tag set to onload="scrolladj()" with scrolladj() being written out below:
function scrolladj()
{
if(brow == 'Microsoft Internet Explorer')
{
o = document.documentElement.scrollLeft;
}
else
{
o = window.pageXOffset;
}
$('main_menu').style.left = (20-o)+'px';
}
Any ideas?
A:
The following code works for FF and Chrome
<HTML>
<HEAD>
<style>
.float {
display:block;
position:fixed;
top: 20px;
left: 0px;
z-index: 1999999999;
}
</style>
<script>
function x()
{
if(document.body.offsetLeft != document.body.scrollLeft)
document.getElementById('fd').style.position='absolute';
else
document.getElementById('fd').style.position='fixed';
}
</script>
</HEAD>
<BODY onscroll="x();">
<div class="float" id="fd">
sdkjfkljfs
</div>
<div style="overflow: auto; width: 2000px; height: 1000px" >
</div>
</BODY>
</HTML>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Security and login on a Symfony 2 based project
I'm developing a web application based on the Symfony 2 PHP framework.
It has a login page for the users registered. I want to execute some custom logic for every user logging into the system.
Basicaly, I want to log whenever any user logs into the system, but I don't want to do it on the main page's controller, because it would log every time the user reloads the main page.
I also want to implement a function that gets called when the user logs into the system so I can decide wether the access is granted or not for any user (based on a full set of information stored on the user's database).
How can I achieve this?
A:
For the first part of your question, I had something similar (eg store the last date & time of a user's login). I went down the route of a service which was fired upon an event. In your services config (XML example here):
<services>
<service id="my.login.listener" class="My\OwnBundle\Event\LoginEventListener">
<tag name="kernel.event_listener" event="security.interactive_login" />
</service>
</services>
and then create the above mentioned class in the appropriate place in your bundle:
namespace My\OwnBundle\Event;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use My\OwnBundle\User\User as MyUser;
class LoginEventListener
{
/**
* Catches the login of a user and does something with it
*
* @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event
* @return void
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$token = $event->getAuthenticationToken();
if ($token && $token->getUser() instanceof MyUser)
{
// You can do something here eg
// record the date & time of the user's login
}
}
}
I would imagine that you could extend this to the second part of your question, however I've not done this :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Netsuite nlapiSearchRecord Expression filters not working
Running into an issue with the nlapiSearchRecord() I can apply the nlobjSearchFilter() object to the searchRecord but I need an OR option and it seems that the only thing the searchFilter passes is AND. I saw this post "NetSuite And/Or Filter" which gave me the the correct information but I keep getting the following error.
Title SSS_INVALID_SRCH_FILTER_EXPR_OBJ_TYPE
Type System
Details filters
and I am not sure why, I tried to do a search for the Error title "SSS_INVAILD_SRCH_FILTER_EXPR_OBJ_TYPE" but google did not produce any helpful information.
Here is the Expression Code I am running
filterExpr = [
['internalid',null,'is',itemId],
'AND',
[
['inventorylocation',null,'is',locationId],
'OR',
['inventorylocation',null,'is',3]
]
];
var results = nlapiSearchRecord('item',null,filterExpr,columns);
--- SOLVED ---
Figured it out the issue was with the null I had in the filter it should have been written as such.
filterExpr = [
['internalid','is',itemId],
'AND',
[
['inventorylocation','is',locationId],
'OR',
['inventorylocation','is',3]
]
];
var results = nlapiSearchRecord('item',null,filterExpr,columns);
Thanks in advance for the help.
A:
The filter did not need the null option that I was putting in my bad for not fully reviewing the format.
--- SOLVED ---
Figured it out the issue was with the null I had in the filter it should have been written as such.
filterExpr = [
['internalid', 'is', itemId],
'AND', [
['inventorylocation', 'is', locationId],
'OR', ['inventorylocation', 'is', 3]
]
];
var results = nlapiSearchRecord('item', null, filterExpr, columns);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the meaning of $\alpha$ in this derivation?
I'm doing a derivation related to quantum mechanics. I need to know what's the meaning of $\alpha$ in this. Here is the pdf version of the document.
A:
I think it is just the name the generic quantum state you're considering to construct the Path Integral representation. Then, in the subsequent lines it is thrown away by inserting a sum over the system eigenstates, and you ends just with the sum over the projections of them over it in order to define the wave-function in the position space.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
setting enablesReturnKeyAutomatically on UISearchBar
I'm writing for iphone OS 3.1.3. I want the search button in the keyboard from my UISearchBar to have the search button enabled all the time. If this was any old UITextField (not a search bar) the property would be enablesReturnKeyAutomatically.
I have tried setting this using the example given at http://discussions.apple.com/thread.jspa?messageID=8457910
which suggests:
UITextField *searchTextField ;
searchTextField = [[searchBar subviews]objectAtIndex:0];
searchTextField.enablesReturnKeyAutomatically = NO ;
Should work.
unfortunately it crashes:
2010-05-20 08:36:18.284 ARemote[5929:207] *** -[UISearchBarBackground setEnablesReturnKeyAutomatically:]: unrecognized selector sent to instance 0x3b31980
2010-05-20 08:36:18.284 ARemote[5929:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UISearchBarBackground setEnablesReturnKeyAutomatically:]: unrecognized selector sent to instance 0x3b31980'
I have also tried
((UITextField *)[(NSArray *)[searchBar subviews] objectAtIndex:0]).enablesReturnKeyAutomatically = NO;</code>
Which gives similar results.
Any ideas?
Cheers
Erik
A:
You're accessing an the documented view hierarchy of UISearchBar. This may be lead to rejection, but your app's behavior will be unspecified on firmware upgrade.
This is an example. When that reply was posted, the UITextField was still the 1st subview of the search bar. Now the 1st subview becomes UISearchBarBackground.
The minimal change is to iterate through the whole view hierarchy and find the actual UITextField.
for (id subview in searchBar.subviews) {
if ([subview respondsToSelector:@selector(setEnablesReturnKeyAutomatically:)]) {
[subview setEnablesReturnKeyAutomatically:NO];
break;
}
}
But for forward compatibility, it's better to use a UITextField instead of a UISearchBar, or not to demand the search button be enabled all the time (e.g. use the Cancel button).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Features seen on the Space Shuttle's solid booster; what does "LOADED" mean exactly?
The question Please explain the time reference shown in Shuttle launch engineering video links to the very cool video Ascent - Commemorating Shuttle. After about 22:25 in the video there is footage from "Camera 33" showing the external fuel tank and one solid booster.
As the booster passes by on the right side of the image, I noticed the following sequence of things pass by, superimposed on the otherwise smooth white matte surface of the booster.
Question: What are these, and what exactly does "LOADED" mean?
BLACK band
“LOADED”
BLACK band
WHITE band
(small writing)
BLACK band
“LOADED”
WHITE band
“LOADED”
BLACK band
(small writing)
(Bottom, nozzle)
A:
Image source
The booster has two kinds of joints between its segments, field joints and factory joints. The booster parts shipped to KSC were made up of two segments joined by factory joints. At KSC, these parts were put together using the field joints. There are three field joints and seven factory joints in a Shuttle SRB.
Image Source
Both kinds of joints are pinned joints. As shown in this picture, there are a large number of holes around the joint. Once the segments are aligned, pins are inserted into the holes. Then a retainer band goes around the outside of the joint to hold the pins in.
Here is a cutaway drawing of the factory joint.
Image Source
That's it for the factory joints. These are the black bands you see.
The field joints are assembled basically the same way, but after the retainer band goes around them, electrical joint heaters are attached, to keep the joint O-rings nice and warm and help prevent another Challenger-like failure. (Mechanical features of the field joints are different now from what they were in Challenger days as well.) The white bands are field joints and are bigger because they incorporate insulation and the joint heaters.
Here's a cutaway drawing of the field joints showing the heaters, insulation, retaining band and pins.
Image source
LOADED just means the casing has propellant in it. I haven't found a reference for that one either.
Bonus SRB labeling fact: the SRB segment railcars are labeled with DO NOT HUMP.
Image source
That means they should not be subjected to "humping", a process where "rail cars are pushed up a hill (hump), uncoupled, and then rolled downhill into remotely controlled sorting tracks." (source: Union Pacific glossary)
General reference for field and factory joints: SPACE TRANSPORTATION SYSTEM HAER No. TX-116
A:
'Loaded' means it's loaded with propellant (as opposed to something like 'inert' or no marking at all, for casings that have not been loaded). It's used to make it easy to distinguish which casing segments have been loaded with propellant and which ones haven't. Loaded segments require different handling procedures than non-loaded segments.
In the military, color codes are used for the same purpose: to make it easy to distinguish between live missiles (with propellant and explosives on board) and training rounds (without explosives, used to train people in missile handling).
The black bands are a rubber coating over the joints between sections. The white bands are another joint cover, I think. The black ones are applied in the factory, which means the white ones are applied on the launch site when the 4 booster segments are joined. Each segments consists of smaller barrel sections that are joined at the factory before the propellant is cast into the section.
The much wider black band at the top was painted on the left-side booster only to make it easier to distinguish between them during descent and splashdown.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hibernate IdentifierGenerationException: unrecognized id type : uuid-binary
Hi all and thanks for your time. I've run into a little trouble with auto-generating java.util.UUIDs.
Consider the following entity:
@javax.persistence.Entity
@javax.persistence.Table(name="clients")
public class Client {
@javax.persistence.GeneratedValue
@javax.persistence.Id
private UUID id;
public UUID getId() {
return id;
}
}
When attempting to persist a new instance, I get the following stacktrace:
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: unrecognized id type : uuid-binary -> java.util.UUID
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:257)
at com.sun.proxy.$Proxy49.persist(Unknown Source)
at com.shorecg.artemis.model.repository.impl.jpa.JpaRepository.save(JpaRepository.java:116)
at com.shorecg.artemis.model.repository.impl.jpa.JpaRepository$$FastClassByCGLIB$$1a43e5e0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:713)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646)
at com.shorecg.artemis.model.repository.impl.jpa.authn.JpaClientRepository$$EnhancerByCGLIB$$e44cf7a.save(<generated>)
at com.shorecg.artemis.server.controllers.Client.postJson(Client.java:71)
at com.shorecg.artemis.server.controllers.Client$$FastClassByCGLIB$$8f5a18aa.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:713)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646)
at com.shorecg.artemis.server.controllers.Client$$EnhancerByCGLIB$$b3bf8521.postJson(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:833)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:696)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1568)
at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:164)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1539)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1548)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:524)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:568)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1110)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:453)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1044)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:199)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:459)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:280)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536)
at java.lang.Thread.run(Thread.java:724)
I've seen many solutions that involve the use of @GenericGenerator. If the model is supplied by a vendor and cannot be modified, how then may I rectify the situation. I have come across snippets which suggest I might be able to register a default generator through the SessionFactory, but I've yet to determine how.
Any help is much appreciated.
Edit:
I did some digging through the sources indicated by the trace, and I came to this section in org.hibernate.id.IdentifierGeneratorHelper:
Class clazz = type.getReturnedClass();
if (rs.getMetaData().getColumnCount() == 1) {
if ( clazz == Long.class ) {
return rs.getLong( 1 );
}
else if ( clazz == Integer.class ) {
return rs.getInt( 1 );
}
else if ( clazz == Short.class ) {
return rs.getShort( 1 );
}
else if ( clazz == String.class ) {
return rs.getString( 1 );
}
else if ( clazz == BigInteger.class ) {
return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
}
else if ( clazz == BigDecimal.class ) {
return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
}
else {
throw new IdentifierGenerationException(
"unrecognized id type : " + type.getName() + " -> " + clazz.getName()
);
}
}
At a glance, unless I'm missing something higher up in the chain, there seems to be no way of returning anything other than a primitive as a generated id.
Further Edit:
The column type in the database was incorrect. Fixing it did not rectify the problem. I did however notice that if I generate the UUID myself using java.util.UUID.randomUUID that Hibernate persists the ID correctly. At this point I'm marching forward with application-generated UUIDs, but I'd like to find out why I've been having this problem. Alternatively, I'm willing to entertain reasons why I shouldn't bother with letting Hibernate generate the uuids.
A:
You might also declare a generator in a package-info.java file and then use it via the @GeneratedValue annotation on the id field.
package-info.java:
@org.hibernate.annotations.GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
package org.leanhis.patientmanagement;
PatientEntity.java:
public class PatientEntity implements Patient {
@Id
@GeneratedValue(generator = "UUID")
@Column
private UUID id;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
php does not import variables from another file
I'm working on a cloud system with login/register system and mysql, but the problem is that php does not imports the variables i'm including.
Here is my config file:
<?php
// Connection details
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
?>
And my code to include the config file:
require("/classes/config.class.php");
When i'm trying do echo the variables that are defined in the config it gives this error:
Notice: Undefined variable: servername in C:\xampp\htdocs\index.php on line 2
I'm using xampp on my local computer it has php Version 5.5.30.
EDIT: First lines of php, from comment
<?php
// Include classes require("/classes/user.class.php");
require("/classes/password.class.php");
// Include configuration require("/classes/config.class.php");
echo $servername; echo $username; echo $password; echo $dbname;
A:
I write an answer because I can't type carriage returns in comments.
Your code in index.php (as your comment above):
<?php // Include classes require("/classes/user.class.php"); require("/classes/password.class.php"); // Include configuration require("/classes/config.class.php");
echo $servername;
(...)
Double slashes // are a comment sign, meaning that all following text it in the same line will be ignored.
I suggest you (also for better code clarity) to edit in this way:
<?php
// Include classes
require("/classes/user.class.php");
require("/classes/password.class.php");
// Include configuration
require("/classes/config.class.php");
echo $servername;
(...)
Read more about Comments in PHP
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using condition to replace value of data frame using another data frame in R
I am stuck in one problem and try to find the similar solution but was unable to find that here in stackoverflow. My data look like this:
x1 <- data.frame(x = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0))
y1 <- data.frame(x = c(sin(x1 - 3.4)), y = c(cos(x1-3.2), z = tan(x1-3.5)))
What I want to do is to replace the value of y1 by NA if x1 = 0 but would like to keep the value as it is if x1 = 1 for whole data frame y1 at the same time. I
I tried ifelse function as
y1 <- ifelse(x1 == 0, NA, y1)
But I was unable to process that. If anyone can suggest me the answer without loop that would be great.
Thanks in advance
A:
y1[x1$x == 0,] <- NA
Note that this sets relevant rows in all columns in y1 as NA. You could do this for one column only by, for example:
y1$x[x1$x == 0] <- NA
|
{
"pile_set_name": "StackExchange"
}
|
Q:
keypress on iframe document gets whole html as target (not exact node)
I have an iframe with designMode="on" (Yeah - I know this is bad thing)
I should catch clicking on it and keypressing and echo the node name of target element.
$(function() {
var editor = $("#editor")[0].contentWindow;
var doc = editor.document;
editor.document.designMode = "on";
doc.open();
doc.write('<div id="dummy">test</div>');
doc.close();
// find iframe body
var $body = $("#editor").contents().find('#dummy').parent();
// clean after finding
$body.html('<div>Hello</div>');
var report = function(e) {
$("#result").html(
$("#result").html() + " " + e.target.nodeName.toLowerCase());
};
$body.click(report);
// $body.keypress(report) -> doesn't work
// only $(doc).keypress works:
$(doc).keypress(report);
});
When I click on word "Hello" - I get "div" - it's correct, but when I keypress on it - i get "html" instead "div". How to fix this?
http://jsfiddle.net/fJLTG/
A:
I created a function, it can work keypress.
var reportDomPath = function (e) {
// 1. get caret cursor position node
var selection, range, node, i_node;
var tag = null;
var iframe = document.getElementById('editor');
var iframe_win = iframe.contentWindow || iframe.contentDocument;
e = e || fwin.event;
if (iframe_win.getSelection) {
try { // FF
selection = iframe_win.getSelection();
range = selection.getRangeAt(0);
node = range.commonAncestorContainer;
} catch (e) {
return false;
}
} else {
try { // IE
selection = iframe_win.document.selection;
range = selection.createRange();
node = range.parentElement();
} catch (e) {
return false;
}
}
//2. parse DOM Path until HTML. The top of the "HTML" is "Document"
i_node = node;
do {
if (i_node.nodeType != 1)
continue;
// get all of DOM Note
if (tag == null) {
tag = i_node.nodeName.toLowerCase();
} else {
tag = tag + ">>" + i_node.nodeName.toLowerCase();
}
// do_some_thing for each Node : obj.addClass('active'); or obj.removeClass('active'); and so on.
} while (i_node = i_node.parentNode)
//do_some_thing for all of note fwin.parent.do_some_thing(ret);
var keyCode = e.charCode || e.keyCode;
$("#result").html(
$("#result").html() + "node dom path: " + tag + ' key' + e.type + ': keyCode: ' + keyCode + '<br>'
);
};
$body.click(reportDomPath);
$(doc).keypress(reportDomPath); // only FF
But $(doc).keypress(reportDomPath) only works on FF.
A:
I did a bit of google .. this might help you:
var f = document.getElementById('iframe_id');
var fwin = f.contentWindow || f.contentDocument;
fwin.document.designMode = 'on';
var evt_key = function (e) {
e = e || fwin.event;
var range = null, ret = null;
if (fwin.document.selection) {
range = fwin.document.selection.createRange();
ret = range.parentElement();
}
else if (fwin.window.getSelection) {
var range = fwin.window.getSelection().getRangeAt(0);
ret = range.commonAncestorContainer.parentNode || fwin.document;
}
fwin.parent.do_some_thing(ret);
};
if (fwin.document.attachEvent) {
fwin.document.attachEvent('onkeypress', evt_key);
}
else if (fwin.document.addEventListener) {
fwin.document.addEventListener('keypress', evt_key, false);
}
all credis to jetcook (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25589672.html)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't connect IBOutlets for custom UITableViewCell
I've got a problem trying to create a custom tableview cell for my iPhone app in Xcode 4. I've created the .h and .m files, created IBOutlets for all of the subviews that should be present inside the cell, and dragged the actual controls onto the cell's XIB file in Interface Builder. However, I can't figure out how to connect the outlets to the IB controls. Every tutorial I read says to control-drag from the TableViewCell object in the objects list to the subviews, but when I do that my IBOutlets are not listed in the popup window. The only outlets that are available are 'acccessoryView', 'backgroundView', 'editingAccessoryView' and 'backgroundSelectedView'. Shouldn't I also be seeing my own IBOutlets in that list as well? Or am I not following the correct procedure? (I'm pretty new to iPhone development).
Here is the code I'm using for the custom cell class:
.h :
//
// RecommendationCell.h
// Tuneplug
//
// Created by Bill Labus on 6/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RecommendationCell : UITableViewCell {
UIImageView *artwork;
}
@property (nonatomic, retain) UIImageView *artwork;
@end
.m :
//
// RecommendationCell.m
// Tuneplug
//
// Created by Bill Labus on 6/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "RecommendationCell.h"
@implementation RecommendationCell
@synthesize artwork;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc
{
[super dealloc];
}
@end
(Note that I reduced the subviews to just the 'artwork' image view for now, to simplify figuring it out). Thanks for any help!
A:
Unless I'm misunderstanding:
Try adding the IBOutlet tag.
IBOutlet UIImageView *artwork;
and
@property (nonatomic, retain) IBOutlet UIImageView *artwork;
This tag is a #define within Xcode that tells Interface Builder to recognize your code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Computing $T^5(2x+1)$?
Let T be a transformation from $P2$ to $P2$ where $P2$ is the space of all polynomials with degree no more than $2$. $T$ is defined by
\begin{align}T(1) &= -3x-1\\
T(x) &= 4x\\
T(x^2) &= 2x^2+x+1\end{align}
a) Choose a basis in $P2$ to make the matrix of $T$ diagonal.
For this problem I got the eigenvalues to be $-1, 4, 2$. So the basis would be
$$
v_1 =
\begin{bmatrix}
5 \\
3 \\
0 \\
\end{bmatrix},
v_2 =
\begin{bmatrix}
0 \\
1 \\
0 \\
\end{bmatrix},
v_3 = \begin{bmatrix}
1 \\
0 \\
3 \\
\end{bmatrix}
$$
and the diagonal matrix would be
$$
\begin{bmatrix}
-1 & 0 & 0 \\
0 & 4 & 0 \\
0 & 0 & 2 \\
\end{bmatrix}
$$
b) Compute $$T^5(2x+1)$$
How do I do this part?
A:
Note that you have found that if $A$ is the matrix of $T$ with respect to the initial basis $\{1, x, x^2\}$, then you have that
$$A = P\Lambda P^{-1}$$
where $P$ is the matrix with columns the eigenvectors you have found (with the order of the columns corresponding to the ordening of the eigenvalues in $\Lambda$).
Now we have that $$T^k = \underbrace{T \circ T \circ \ldots \circ T}_{k \text{ times}}$$ and composition corresponds to matrix multiplication. So if you want to compute $T^k$, then you have to compute $A^k$. This seems to turn out into a very long computations! However, you are lucky: $A$ is diagonizable and you can show that for a diagonal matrix $D$ you have that $D^k$ is the diagonal matrix with the diagonal elements raised to the power $k$. Hence we have that
$$A^k = \underbrace{(P \Lambda P^{-1})(P \Lambda P^{-1})\ldots (P \Lambda P^{-1})}_{k \text{ times}} = P \Lambda^k P^{-1}$$
since we can cancel out $PP^{-1}$ in the large product. Does this help you in computing $T^5$ and applying it to $2x+1$?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQl Query to Hibernate Query
I have a MySQL query that I use to retrieve random rows from a table. The query is:
SELECT * FROM QUESTION WHERE TESTID=1 ORDER BY RAND() LIMIT 10;
Now I need to change this query to Hibernate. Did a bit of googling but couldn't find the answer. Can someone provide help on this?
A:
According to this post, you can do that :
String query = "from QUESTION order by newid()";
Query q = session.createQuery(query);
q.setMaxResults(10);
Not sure if it will work (especially for the random part), but you can try it :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android Studio: Gradle Sync fail with v4 support library
I have been following the Android fragments tutorial which requests that I set up my project to work with the v4 library by following the Support Library Setup document here.
Here are the steps I followed.
1) Make sure you have downloaded the Android Support Repository using
the SDK Manager.
2) Open the build.gradle file for your application.
3) Add the support library to the dependencies section. For example,
to add the v4 support library, add the following lines:
dependencies {
...
compile "com.android.support:support-v4:24.1.1"
}
After following the three steps I receive these two errors:
Gradle project sync failed...
Error:Could not find method compile() for arguments [com.android.support:support-v4:24.1.1] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Please install the Android Support Repository from the Android SDK Manager.
According to the Android SDK Manager, I do have the Android Support Repository installed.
I am going to continue investigating this issue as fragments appear to be a valuable tool to develop powerful Android mobile apps. Help approaching this issue would be appreciated.
As Sufian requested in the comments below, here are the contents of my build.gradle file.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
compile "com.android.support:support-v4:24.1.1"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is a screenshot of my Android Standalone SDK Manager showing that the Android Support Repository is installed.
A:
There are two build.gradle files in your project, one rootlevel, and one for your application. You will also see a dependencies section in the other build.gradle. You need to place the compile "com.android.support:support-v4:24.1.1" in there.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind a model property with DefaultModelBinder - ASP.NET MVC2
I have the following scenario.
I have the Edit/Employee view populated with a model from an Entity Framework entity (Employee)
I post from Edit/Employee to the Save/Employee controller action. The Save/Employee action expect another type (EmployeeSave) which has Employee as property
This is the Edit/Employee method
public ActionResult Edit(EmployeesEdit command)
{
var employee = command.Execute();
if (employee != null)
{
return View(employee);
}
return View("Index");
}
This is the Save/Employee method
public ActionResult Save(EmployeesSave command)
{
var result = command.Execute();
if (result)
{
return View(command.Employee);
}
return View("Error");
}
This is the EmployeeSave class
public class EmployeesSave
{
public bool Execute()
{
// ... save the employee
return true;
}
//I want this prop populated by my model binder
public Employee Employee { get; set; }
}
The MVC DefaultModelBinder is able to resolve both Employee and EmployeeSave classes.
A:
You might need to use BindAttribute here. If your view contains the properties of the EmployeeSaveViewModel and Employee named like this (I made up property names)
<input type="text" name="EmployeeSaveViewModel.Property1" />
<input type="text" name="EmployeeSaveViewModel.Employee.Name" />
<input type="text" name="EmployeeSaveViewModel.Employee.SomeProperty" />
Then, your action could look like this:
[HttpPost]
public ActionResult Save([Bind(Prefix="EmployeeSaveViewModel")]
EmployeeSaveViewModel vm)
{
if(ModelState.IsValid)
{
// do something fancy
}
// go back to Edit to correct errors
return View("Edit", vm);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create a clickable circle 10 times using javascipt and if I click on it, it shows number in center how many time I clicked
I am practicing javascript.I want to have like 10 circles with different colors. I can create 10 circles using html and css, but need help with javascript. For each circle, show the number of times it is clicked on. If I click on blue 3 time, it should show 3 in the center of circle
<style>
.circle{
border-radius: 50%;
width: 40px;
height: 40px;
padding: 3px;
background: blue;
border: 2px solid black;
text-align: center;
}
</style>
</head>
<body>
<div class="circle">
3
</div>
</body>
A:
Try the following way
var circleSelector = document.getElementsByClassName("circle");
var myClickFunction = function() {
var previousNumber = +this.innerHTML || 0;
this.innerHTML = previousNumber + 1;
};
for (var i = 0; i < circleSelector.length; i++) {
circleSelector[i].addEventListener('click', myClickFunction, false);
}
.circle {
border-radius: 50%;
width: 40px;
height: 40px;
padding: 3px;
background: blue;
border: 2px solid black;
text-align: center;
float: left;
margin-left: 5px;
}
.red {
background: red;
}
.gray {
background: gray;
}
<div class="circle">
0
</div>
<div class="circle red">
0
</div>
<div class="circle gray">
0
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Database structure for product variants
I am upgrading a website to enable product variants - currently the website only provides standalone products but there is now a requirement to provide variants of a particular product, e.g. size or colour. The aim is to enable the site admin to easily insert/edit product variants.
The current structure is as follows:
table product
=============
id
name
description
category_id
price
stock_level
The fields 'price' and 'stock_level' will now need to be relevant to each product variant.
A product can have multiple combinations of variants, e.g:
Product ID 5 - Size: Small, Colour: Black
Product ID 5 - Size: Small, Colour: Brown
On the front end there are two dropdowns to select the variants (Size and Colour). Upon selecting the required variants, the values are posted to a PHP script which runs an SQL query to check if that particular variant combination is available.
I am struggling to come up with a solution for this. I have currently created the following functionality, which I think is the starting point:
Ability to create/edit variant TYPES e.g. Size or Colour:
table variant_type
==================
id
name
Ability to assign values to variant types, e.g. Small, Large, Black, Brown:
table variant_type_value
========================
id
name
variant_type_id
I am struggling to come up with the design for the table(s) that will store the product variant combinations (including their price and stock level).
Bear in mind, on the backend, there will be a form to "Add a new Variant" - on this form the admin will need to select 'Size', 'Colour', 'Price' and 'Stock Level' when adding/editing a variant.
A:
I think the easiest way would be to have a Product table; that would have all the details of the variants in it, by including the foreign keys for the Product table, as well as the Size and Colour tables:
table variant
=============
variantID
productID
sizeID
colourID
stock
price
table product
=============
id
name
description
category_id
table size
==========
sizeID
sizeName
table colour
============
colourID
colourName
So you can get the details for the variants by joining all four tables together. Information that relates to the product in general goes in the product table, and you can add extra types of variant by creating new tables and linking them in the variant table.
Editted to add:
This way, you'll need to add extra tables if you want to add a new type of variant. You could also get around it by merging all the variant possibilities into one variant table:
+--+------+------+
|ID|Type |Option|
+--+------+------+
|1 |Colour|Brown |
|2 |Size |Small |
+--+------+------+
You'd then have multiple foreign keys from variantInfo in the main product table.
I don't tend to like that - I don't like have multiple types of information stored in the same table. I just think it's confusing, and you need to make the programming logic more complicated. If you want to have extra variant types, I'd recommend just setting them all up now - it's a little extra work, and some of them won't be used, but I think it's a lot easier to maintain.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
React.lazy: this.props is empty
I have simple test project with App.js
import React, { Component, Suspense } from 'react';
import { BrowserRouter, Route, NavLink } from 'react-router-dom';
const Posts = React.lazy(() => import('./containers/Posts'));
class App extends Component {
render() {
return (
<BrowserRouter>
<React.Fragment>
<nav>
<NavLink to="/posts/222">Posts Page</NavLink>
</nav>
<Route path="/posts/:id" render={() => (
<Suspense fallback={<div>Loading...</div>}>
<Posts {...this.props} />
</Suspense>
)}
/>
</React.Fragment>
</BrowserRouter>
);
}
}
export default App;
and containers/Posts.js
import React, {Component} from 'react';
class Posts extends Component {
componentDidMount() {
console.log(this.props);
}
render() {
return (<h1>The Posts Page</h1>)
}
};
export default Posts;
and this.props in Posts is an empty object.
How can I get this.props.match.params.id in this case?
A:
Wrap Posts with withRouter from react-router-dom
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class Posts extends Component {
componentDidMount() {
console.log(this.props);
}
render() {
return (<h1>The Posts Page</h1>)
}
};
export default withRouter(Posts);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
child element overlapped by box-shadow
Hy guys,
i've got a problem: The box-shadow from .elem3 should not overlap .elem2.
I tried to fix this with the z-index. First I thought it was a bug in IE,
but in all Browsers it's the same result.
Does anybody know an answer?
..sry for my bad English I'm german :)
HTML:
`
<div class="elem1">
<div class="elem2">
</div>
</div>
<div class="elem3">
</div>`
CSS:
`
body {
margin: 0;
}
.elem1 {
position: absolute;
height: 50px;
width: 400px;
background: linear-gradient(top, #70ACD7, #005DA8);
background: -moz-linear-gradient(top, #70ACD7, #005DA8);
background: -webkit-linear-gradient(top, #70ACD7, #005DA8);
z-index: 1;
margin-top: 20px;
}
.elem2 {
position: absolute;
height: 50px;
width: 100px;
margin-left: 100px;
background: linear-gradient(top, #CCC, #AAA);
background: -moz-linear-gradient(top, #CCC, #AAA);
background: -webkit-linear-gradient(top, #CCC, #AAA);
background: -ms-linear-gradient(bottom, rgb(170,170,170) 43%, rgb(204,204,204) 72%);
z-index: 3;
box-shadow: 0px 0px 8px black;
}
.elem3 {
position: absolute;
top: 70px;
left: 100px;
width: 150px;
height: 100px;
background: linear-gradient(top, #AAA, #CCC);
background: -moz-linear-gradient(top, #AAA, #CCC);
background: -webkit-linear-gradient(top, #AAA, #CCC);
background: -ms-linear-gradient(bottom, rgb(170,170,170) 43%, rgb(204,204,204) 72%);
z-index: 2;
box-shadow: 0px 0px 8px black;
}
`
A:
That's not going to be possible as elem2 is a child of elem1 and a child can't have a higher z-index than it's parent, you will have to remove elem2 from elem1, like this:
<div class="elem1"></div>
<div class="elem2"></div>
<div class="elem3"></div>
You can position it back where it was by adding a margin-top: 20px to elem2. Then give elem1 a z-index of 1, elem2 a z-index of 3 and elem3 a z-index of 2.
Hope that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
POST-ing a tweet using libcurl and liboauth in C
I'm trying to post a tweet to Twitter with the following code, but keep getting the error "Could not authenticate you","code":32":
curl_global_init(CURL_GLOBAL_ALL);
CURL *curl = curl_easy_init();
char *signedurl = malloc(sizeof(char) * 1024); /* Not how it will be, but works in this example. */
char *url = "https://api.twitter.com/1.1/statuses/update.json";
signedurl = oauth_sign_url2(url, NULL, OA_HMAC, "POST", consumer_key, consumer_secret, user_token, user_secret);
char *status = "status=test";
curl_easy_setopt(curl, CURLOPT_URL, signedurl); /* URL we're connecting to, after being signed by oauthlib */
curl_easy_setopt(curl, CURLOPT_USERAGENT, "dummy-string"); /* Not the actual string, just a dummy for this example */
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, status);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
int curlstatus = curl_easy_perform(curl); /* Execute the request! */
curl_easy_cleanup(curl);
free(signedurl);
Now, I looked at Twitter's documentation and the discussion on their website, and they recommend three things:
Regenerate your access tokens. I've done this, and tried to post to Twitter via them using the developers console in the Twitter desktop program I have, and that works. This makes me think that the problem is elsewhere.
Include Content-Type: application/x-www-form-urlencoded in the header of the request. My understanding is that this is default for how I'm using cURL, and indeed, when I use the VERBOSE option, I can see that it is in the header.
Properly encode the url. I know that oauth_sign_url2 does this correctly when fetching things from Twitter, and I've tried using oauth_url_escape("status=test") on the status (even though I don't think I'm supposed to do that). That doesn't work either.
I have a feeling it's something completely obvious, but I am stumped.
A:
What was missing from my original code was to properly build the header. The following code works.
char *ttwytter_request(char *http_method, char *url, char *url_enc_args)
{
struct curl_slist * slist = NULL;
char * ser_url, **argv, *auth_params, auth_header[1024], *non_auth_params, *final_url, *temp_url;
int argc;
ser_url = (char *) malloc(strlen(url) + strlen(url_enc_args) + 2);
sprintf(ser_url, "%s?%s", url, url_enc_args);
argv = malloc(0);
argc = oauth_split_url_parameters(ser_url, &argv);
free(ser_url);
temp_url = oauth_sign_array2(&argc, &argv, NULL, OA_HMAC, http_method, consumer_key, consumer_secret, user_token, user_secret);
free(temp_url);
auth_params = oauth_serialize_url_sep(argc, 1, argv, ", ", 6);
sprintf( auth_header, "Authorization: OAuth %s", auth_params );
slist = curl_slist_append(slist, auth_header);
free(auth_params);
non_auth_params = oauth_serialize_url_sep(argc, 1, argv, "", 1 );
final_url = (char *) malloc( strlen(url) + strlen(non_auth_params) );
strcpy(final_url, url);
postdata = non_auth_params;
for (int i = 0; i < argc; i++ )
{
free(argv[i]);
}
free(argv);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "dummy-string");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
int curlstatus = curl_easy_perform(curl); /* Execute the request! */
curl_easy_cleanup(curl);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
python requests randomly breaks with JSONDecodeError
I have been debugging for hours why my code randomly breaks with this error: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This is the code I have:
while True:
try:
submissions = requests.get('http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since).json()['submission']['records']
break
except requests.exceptions.ConnectionError:
time.sleep(100)
And I've been debugging by printing requests.get(url) and requests.get(url).text and I have encountered the following "special "cases:
requests.get(url) returns a successful 200 response and requests.get(url).text returns html. I have read online that this should fail when using requests.get(url).json(), because it won't be able to read the html, but somehow it doesn't break. Why is this?
requests.get(url) returns a successful 200 response and requests.get(url).text is in json format. I don't understand why when it goes to the requests.get(url).json() line it breaks with the JSONDecodeError?
The exact value of requests.get(url).text for case 2 is:
{
"submission": {
"columns": [
"pk",
"form",
"date",
"ip"
],
"records": [
[
"21197",
"mistico-form-contacto-form",
"2018-09-21 09:04:41",
"186.179.71.106"
]
]
}
}
A:
Looking at the documentation for this API it seems the only responses are in JSON format, so receiving HTML is strange. To increase the likelihood of receiving a JSON response, you can set the 'Accept' header to 'application/json'.
I tried querying this API many times with parameters and did not encounter a JSONDecodeError. This error is likely the result of another error on the server side. To handle it, except a json.decoder.JSONDecodeError in addition to the ConnectionError error you currently except and handle this error in the same way as the ConnectionError.
Here is an example with all that in mind:
import requests, json, time, random
def get_submission_records(client, since, try_number=1):
url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
headers = {'Accept': 'application/json'}
try:
response = requests.get(url, headers=headers).json()
except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError):
time.sleep(2**try_number + random.random()*0.01) #exponential backoff
return get_submission_records(client, since, try_number=try_number+1)
else:
return response['submission']['records']
I've also wrapped this logic in a recursive function, rather than using while loop because I think it is semantically clearer. This function also waits before trying again using exponential backoff (waiting twice as long after each failure).
Edit: For Python 2.7, the error from trying to parse bad json is a ValueError, not a JSONDecodeError
import requests, time, random
def get_submission_records(client, since, try_number=1):
url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
headers = {'Accept': 'application/json'}
try:
response = requests.get(url, headers=headers).json()
except (requests.exceptions.ConnectionError, ValueError):
time.sleep(2**try_number + random.random()*0.01) #exponential backoff
return get_submission_records(client, since, try_number=try_number+1)
else:
return response['submission']['records']
so just change that except line to include a ValueError instead of json.decoder.JSONDecodeError.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maximal number of subsets with 3 elements and small intersection - special Constant Weight Codes
in the middle of some proof I encountered a combinatorial problem and tracked it back to the theory of Constant Weight Codes. Those problems seem hard to solve, but my question is rather specific, so I am still posting it in the hope for ideas:
Assume you have a set $X$ of $N$ elements (all numbers are finite). What is the largest number $k=k(N)$ such that there exist subsets $Y_1, \dots, Y_k\subseteq X$ with
$|Y_i|=3$ for all $i=1,\dots, k$
$|Y_i\cap Y_j|\leq 1$ for all $i\neq j$.
Ultimately I am not even interested in the explicit number, but rather in an answer to the following
Question: Does there exist some natural number $N$, such that $k(N)\geq 2N$?
In the language of Constant Weight Codes, the number $k(N)$ seems to refer to the maximal number $A(N,4,3)$ of Codewords in a binary Constant Weight Code with length $N$, Hamming distance $4$ and constant weight $3$.
I would be very thankful for suggestions.
Cheers,
Sofie
A:
I'll just adress you question as to whether there is $N$ so that $k(N)\geq 2n$. Yes, it is very possible. In fact if $N$ is $1$ or $3\bmod 6$ we can always find $\frac{n(n-1)}{6}$ subsets with this property by taking a steiner triple system.
In particular a Steiner triple system of size $13$ would have $\frac{13\cdot12}{6}=26$ subsets of size $3$. So indeed it is possible for $k(N)$ to be greater than $2n$, or $sn$ for any integer $s$ for that matter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make Next.js server waiting until action creator is fully done?
I'm using Next.js with Redux and I need to wait until action creator is fully done (including request to the external server) so data will be already in the initial rendering. I will try to explain this case in example.
I'm using HOC from example in docs and wrap page with it.
So, below you can see code example:
index.js in pages folder.
import withRedux from '../utils/withRedux'
import RunningLineContainer from '../src/containers/news/RunningLineContainer'
const IndexPage = () => <RunningLineContainer />
export default withRedux()(IndexPage)
RunningLineContainer.jsx
import React, { Component } from 'react'
import { connect } from 'react-redux'
import RunningLine from '../../components/RunningLine'
import { fetchLatestNews } from '../../actions/wp_news'
class RunningLineContainer extends Component {
componentDidMount() {
if (!this.props.lastestNews) {
this.props.fetchLatestNews('&count=6')
}
}
render() {
const { latestNews, isLoading } = this.props
return <RunningLine data={latestNews} isLoading={isLoading} />
}
}
const mapStateToProps = ({ newsState }) => {
const { latestNews, isLoading } = newsState
return {
latestNews,
isLoading
}
}
export default connect(mapStateToProps, { fetchLatestNews })(RunningLineContainer)
Currently, request is being made on the client side thus data from request is not rendered by the server and data content not being seen by search engines. My aim to make this data being responded on initial loading (rendered by the server).
Action creator code below:
export function fetchLatestNews(params) {
return function (dispatch) {
dispatch({ type: newsTypes.FETCH_WP_LATEST_NEWS_REQUEST })
newsApi.fetchLatestNews(params)
.then(response => {
dispatch({
type: newsTypes.FETCH_WP_LATEST_NEWS_SUCCESS,
payload: response.data,
})
})
.catch(error => {
dispatch({
type: newsTypes.FETCH_WP_LATEST_NEWS_FAILURE,
payload: error,
})
})
}
}
I've tried to use static method getInitialProps in index.js page like this:
import withRedux from '../utils/withRedux'
import RunningLineContainer from '../src/containers/news/RunningLineContainer'
const IndexPage = () => <RunningLineContainer />
IndexPage.getInitialProps = async ({ store }) => {
await store.dispatch(fetchLatestNews())
}
export default withRedux()(IndexPage)
Unfortunately, it doesn't work for me.
How can I solve this task? Is there any workaround?
Thanks in advance!
A:
Finally, I have resolved this task.
Actual solution is to make returning function in action creator asynchronous and add await to the API request.
So, I use static method as mentioned above like this:
import withRedux from '../utils/withRedux'
import RunningLineContainer from '../src/containers/news/RunningLineContainer'
const IndexPage = () => <RunningLineContainer />
IndexPage.getInitialProps = async ({ store }) => {
await store.dispatch(fetchLatestNews())
}
export default withRedux()(IndexPage)
My action creator looks like this:
export const fetchLatestNews = params => {
return async dispatch => {
dispatch({ type: newsTypes.FETCH_WP_LATEST_NEWS_REQUEST })
await newsApi.fetchLatestNews(params)
.then(response => {
dispatch({
type: newsTypes.FETCH_WP_LATEST_NEWS_SUCCESS,
payload: response.data,
})
})
.catch(error => {
dispatch({
type: newsTypes.FETCH_WP_LATEST_NEWS_FAILURE,
payload: error,
})
})
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Parsing embedded JSON with Aeson
I'm trying to parse embedded JSON of the form
{
"foo":"bar",
"baz":"\{\"somekey\":\"someval\"\}"
}
with Aeson in Haskell. Here are my types:
data BaseType = BaseType { foo :: String, baz :: EmbeddedType } deriving(Show)
instance FromJSON BaseType where
parseJSON = withObject "BaseType" $ \o -> do
foo <- o .: "foo"
baz <- o .: "baz"
return $ BaseType { foo=foo, baz=baz }
data EmbeddedType = EmbeddedType { somekey :: String }
instance FromJSON EmbeddedType where
parseJSON = withObject "EmbeddedType" $ \o -> do
somekey <- o .: "somekey"
return $ EmbeddedType {somekey=somekey}
Obviously, the FromJSON instance for BaseType doesn't work, since it sees it as a Value String instead of as more JSON for it to parse. I tried to find a way to use decodeEither in my FromJSON BaseType instance, but that required that I do some black magic to convert from String to ByteString, and I feel like there must be a neater way, possibly related to withEmbeddedJSON.
How can I make this work correctly?
A:
I guess it would be something like this (untested):
instance FromJSON BaseType where
parseJSON = withObject "BaseType" $ \o -> do
foo <- o .: "foo"
bazText <- o .: "baz"
baz <- withEmbeddedJSON "EmbeddedType" parseJSON (String bazText)
return $ BaseType { foo=foo, baz=baz }
Or you could consider moving the call to withEmbeddedJSON into the EmbeddedType instance; then o .: "baz" should Just Work in the BaseType instance, at the cost of no longer having a handle onto a parser that just does EmbeddedType parsing without de-stringifying:
instance FromJSON BaseType where
parseJSON = withObject "BaseType" $ \o -> do
foo <- o .: "foo"
baz <- o .: "baz"
return $ BaseType { foo=foo, baz=baz }
instance FromJSON EmbeddedType where
parseJSON = withEmbeddedJSON "EmbeddedType" . withObject "EmbeddedType" $ \o -> do
somekey <- o .: "somekey"
return $ EmbeddedType {somekey=somekey}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cleanup MovieClips on Scene Change in ActionScript 2
for(i=0;i<itemLength;i++)
{
duplicateMovieClip("tvmenuitem", "tvmenuitem"+i, i);
...
However when I change the scene using: gotoAndPlay('main',1);
The main scene is overlayed with all the MovieClips I had in the previous scene.
How can I automagically clean them up?
A:
store references to the created clips when you generate them:
// store your clip references here
var clips:Array = [];
for(i=0;i<itemLength;i++)
{
// create you duplicated clip and store a reference in your clips array
var dupe:MovieClip = duplicateMovieClip("tvmenuitem", "tvmenuitem"+i, i);
clips.push(dupe);
}
and then use the removeMovieClip method to destroy the clips when neccessary:
// loop through the clips array and destroy the clips in your array
for(i=0, l=clips.length; i<l; i++)
{
clips[i].removeMovieClip();
}
// reset the array
clips = [];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extra tables or non-specific foreign keys?
There are several types of objects in a system, and each has it's own table in the database. A user should be able to comment on any of them. How would you design the comments table(s)? I can think of a few options:
One comments table, with a FK column for each object type (ObjectAID, ObjectBID, etc)
Several comments tables, one for each object type (ObjectAComments, ObjectBComments, etc)
One generic FK (ParentObjectID) with another column to indicate the type ("ObjectA")
Which would you choose? Is there a better method I'm not thinking of?
A:
@palmsey
Pretty much, but the variation on that pattern that I've seen most often gets rid of ObjectAID et al. ParentID becomes both the PK and the FK to Parents. That gets you something like:
Parents
ParentID
ObjectA
ParentID (FK and PK)
ColumnFromA NOT NULL
ObjectB
ParentID (FK and PK)
ColumnFromB NOT NULL
Comments would remain the same. Then you just need to constrain ID generation so that you don't accidentally wind up with an ObjectA row and an ObjectB row that both point to the same Parents row; the easiest way to do that is to use the same sequence (or whatever) that you're using for Parents for ObjectA and ObjectB.
You also see a lot of schemas with something like:
Parents
ID
SubclassDiscriminator
ColumnFromA (nullable)
ColumnFromB (nullable)
and Comments would remain unchanged. But now you can't enforce all of your business constraints (the subclasses' properties are all nullable) without writing triggers or doing it at a different layer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there way to send email through JavaMail without implicity setting password in Java?
Is there way to send email through JavaMail without implicity setting password in Java code (or properties file)?
A:
I assume that by "without implicity setting password in Java code " you mean "without hardcoding the password such that others can see it".
If your SMTP server requires a password then the client program (the one sending the emails) must provide it, and get it from somewhere. The three choices are
Hardcode in Java
Store in Properties file
Provide manually on startup
That's about it. If your client is not running in a secure environment (where you control who has access to the properties file) it probably shouldn't be accessing a secure service in this fashion.
One possible alternative is to write your own intermediate service. The client connects to your service, which can examine and discard anything inappropriate, and which connects to the real email server (with the password) only for those send attempts that pass verification. Your service wouldn't need to implement SMTP; it could be a simple POST servlet.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Override parent theme's include file from child theme
I am trying to override a parent theme's include file from a child theme. Here is the code:
parentTheme/functions.php
<?php
define ( "_CRYOUT_THEME_NAME", "fluida" );
define ( "_CRYOUT_THEME_VERSION", "1.2.6" );
require_once( get_template_directory() . "/admin/main.php" );
require_once( get_template_directory() . "/includes/setup.php" );
require_once( get_template_directory() . "/includes/styles.php" );
require_once( get_template_directory() . "/includes/loop.php" );
require_once( get_template_directory() . "/includes/comments.php" );
require_once( get_template_directory() . "/includes/core.php" );
require_once( get_template_directory() . "/includes/hooks.php" );
require_once( get_template_directory() . "/includes/meta.php" );
require_once( get_template_directory() . "/includes/landing-page.php" );
childTheme/functions.php
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
?>
And I want to override the /includes/core.php file
I have a childTheme/includes/core.php file
But when I change it, there are no changes on my site.
I have tried to add this code on my childTheme/functions.php :
require_once( get_stylesheet_directory() . "/includes/core.php");
But it renders a blank page on my site.
EDIT :
I have tryed this :
<?php
/**
* Enqueues child theme stylesheet, loading first the parent theme stylesheet.
*/
require_once( get_stylesheet_directory() . "/includes/core.php" ); // Core functions
function themify_custom_enqueue_child_theme_styles() {
wp_enqueue_style( 'parent-theme-css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'themify_custom_enqueue_child_theme_styles', 11 );
But I got this error :
Cannot redeclare xxx_function_name
(previously declared in /var/www/html/mywebsite/wp-content/themes/***childTheme***/includes/core.php:340)
in /var/www/html/tpevegetarisme/wp-content/themes/***parentTheme***/includes/core.php on line 340
So how can I do to prevent parent theme to redeclare a function
A:
You cannot simply override that file.
You can however override what the core.php file does:
Use remove_filter / remove_action to remove filters you do not want to be run:
remove_action ( 'cryout_headerimage_hook', 'fluida_header_image' );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Tkinter buttons - no text
I'm having a bit of a play with tkinter buttons. Im wanting to insert some buttons into a clock script I have.
Inserting the button Exit (3rd line from bottom) inserts a button ok, and the button works, but it refuses to show any text on the button.
How can I show text on this button?
import sys
if sys.version_info[0] == 2:
from Tkinter import *
import Tkinter as tk
else:
from tkinter import *
import tkinter as tk
from time import *
fontsize=75
fontname="Comic Sans MS" #font name - use Fontlist script for names
fontweight="bold" #"bold" for bold, "normal" for normal
fontslant="roman" #"roman" for normal, "italic" for italics
def quit():
clock.destroy()
def getTime():
day = strftime("%A")
date = strftime("%d %B %Y")
time = strftime("%I:%M:%S %p")
text.delete('1.0', END) #delete everything
text.insert(INSERT, '\n','mid')
text.insert(INSERT, day + '\n', 'mid') #insert new time and new line
text.insert(INSERT, date + '\n', 'mid')
text.insert(INSERT, time + '\n', 'mid')
clock.after(900, getTime) #wait 0.5 sec and go again
clock = tk.Tk() # make it cover the entire screen
w= clock.winfo_screenwidth()
h= clock.winfo_screenheight()
clock.overrideredirect(1)
clock.geometry("%dx%d+0+0" % (w, h))
clock.focus_set() # <-- move focus to this widget
clock.bind("<Escape>", lambda e: e.widget.quit())
text = Text(clock, font=(fontname, fontsize, fontweight, fontslant))
text.grid(column = 1, columnspan = 1, row = 2, rowspan = 1, sticky='')
Exit = Button(clock, text="Close Tkinter Window", width = w, height = 1, command=quit).grid(row = 1, rowspan = 1, column = 1, columnspan = w)
clock.after(900, getTime)
clock.mainloop()
A:
Sort of solved it. The button was showing text - it was just off the screen. Solved it by adjusting the width of the tkinter text window and the buttons.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Puzzled by the spawned actor from a Spray route
I am doing some Http request processing using Spray. For a request I spin up an actor and send the payload to the actor for processing and after the actor is done working on the payload, I call context.stop(self) on the actor to wind the actor down.The idea is to prevent oversaturation of actors on the physical machine.
This is how I have things set up..
In httphandler.scala, I have the route set up as follows:
path("users"){
get{
requestContext => {
val userWorker = actorRefFactory.actorOf(Props(new UserWorker(userservice,requestContext)))
userWorker ! getusers //get user is a case object
}
}
} ~ path("users"){
post{
entity(as[UserInfo]){
requestContext => {
userInfo => {
val userWorker = actorRefFactory.actorOf(Props(new UserWorker(userservice,requestContext)))
userWorker ! userInfo
}
}
}
}
}
My UserWorker actor is defined as follows:
trait RouteServiceActor extends Actor{
implicit val system = context.system
import system.dispatcher
def processRequest[responseModel:ToResponseMarshaller](requestContex:RequestContext)(processFunc: => responseModel):Unit = {
Future{
processFunc
} onComplete {
case Success(result) => {
requestContext.complete(result)
}
case Failure(error) => requestContext.complete(error)
}
}
}
class UserWorker(userservice: UserServiceComponent#UserService,requestContext:RequestContext) extends RouteServiceActor{
def receive = {
case getusers => processRequest(requestContext){
userservice.getAllUsers
}
context.stop(self)
}
case userInfo:UserInfo => {
processRequest(requestContext){
userservice.createUser(userInfo)
}
context.stop(self)
}
}
My first question is, am I handling the request in a true asynchronous fashion? What are some of the pitfalls with my code?
My second question is how does the requestContext.complete work? Since the original request processing thread is no longer there, how does the requestContext send the result of the computation back to the client.
My third question is that since I am calling context.stop(self) after each of my partial methods, is it possible that I terminate the worker while it is in the midst of processing a different message.
What I mean is that while the Actor receives a message to process getusers, the same actor is done processing UserInfo and terminates the Actor before it can get to the "getusers" message. I am creating new actors upon every request, but is it possible that under the covers, the actorRefFactory provides a reference to a previously created actor, instead of a new one?
I am pretty confused by all the abstractions and it would be great if somebody could break it down for me.
Thanks
A:
1) Is the request handled asynchronously? Yes, it is. However, you don't gain much with your per-request actors if you immediately delegate the actual processing to a future. In this simple case a cleaner way would be to write your route just as
path("users") {
get {
complete(getUsers())
}
}
def getUsers(): Future[Users] = // ... invoke userservice
Per-request-actors make more sense if you also want to make route-processing logic run in parallel or if handling the request has more complex requirements, e.g. if you need to query things from multiple service in parallel or need to keep per-request state while some background services are processing the request. See https://github.com/NET-A-PORTER/spray-actor-per-request for some information about this general topic.
2) How does requestContext.complete work? Behind the scenes it sends the HTTP response to the spray-can HTTP connection actor as a normal actor message "tell". So, basically the RequestContext just wraps an ActorRef to the HTTP connection which is safe to use concurrently.
3) Is it possible that "the worker" is terminated by context.stop(self)? I think there's some confusion about how things are scheduled behind the scenes. Of course, you are terminating the actor with context.stop but that just stops the actor but not any threads (as threads are managed completely independently from actor instances in Akka). As you didn't really make use of an actor's advantages, i.e. encapsulating and synchronizing access to mutable state, everything should work (but as said in 1) is needlessly complex for this use case). The akka documentation has lots of information about how actors, futures, dispatchers, and ExecutionContexts work together to make everything work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Aligning data arrays by closest time
I have 2 data vectors with corresponding time vectors. This data is sampled nearly simultaneously but they have slightly different timestamps (from machine precision transmission delays etc.). One or both of the data vectors experience occasional data losses & occasional double samples due to telemetry issues.
I want to match up the data arrays to where their times match to perform some math operations between them. Essentially remove points from y1 & y2 where they do not have corresponding times x1 & x2 (within about 1/2 of the sample rate to be considered a match).
Note I do not want to interpolate y1 & y2
%Sample time stamps: Real ones are much faster and not as neat.
x1 = [1 2 3 4 5 5.1 6 7 8 10 ]; %note double sample at ~5.
x2 = [.9 4.9 5.9 6.9 8.1 9.1 10.1]; %Slightly different times.
%Sample data: y is basically y1+1 if no data was missing
y1 = [1 2 3 4 5 5 6 7 8 10];
y2 = [2 6 7 8 9 10 11];
So the result should look like:
y1_m = [1 5 6 7 8 10];
y2_m = [2 6 7 8 9 11];
What I have so far: I used interp1 to find the closest time points between the 2 time arrays. Then got the time delta between them like this:
>> idx = interp1(x2,1:numel(x2),x1,'nearest','extrap')
idx =
1 1 2 2 2 2 3 4 5 7
>> xDelta = abs(x2(idx) - x1)
xDelta =
0.1000 1.1000 1.9000 0.9000 0.1000 0.2000 0.1000 0.1000 0.1000 0.1000
Now what I think I need to do is for each unique idx find the min xDelta and that should get me all the matching points. However, I haven't come up with a clever way of doing that... It seems like accumarray should be useful here but so far I failed at using it.
A:
Here is a solution based on @Cris Luengo's comment on the original question.
It uses a sortrows & unique to get the lowest time error for each pairing of data points.
%Sample time stamps: Real ones are much faster and not as neat.
x1 = [1 2 3 4 5 5.1 6 7 8 10 ]; %note double sample at ~5.
x2 = [.9 4.9 5.9 6.9 8.1 9.1 10.1]; %Slightly different times.
%Sample data: y is basically y1+1 if no data was missing
y1 = [1 2 3 4 5 5 6 7 8 10];
y2 = [2 6 7 8 9 10 11];
%Find the nearest match
idx = interp1(x2,1:numel(x2),x1,'nearest','extrap');
xDiff = abs(x2(idx) - x1);
% Combine the matched indices & the deltas together & sort by rows.
%So lowest delta for a given index is first.
[A, idx1] = sortrows([idx(:) xDiff(:)]);
[idx2, uidx] = unique(A(:,1),'first');
idx1 = idx1(uidx); %resort idx1
%output
y1_m = y1(idx1)
y2_m = y2(idx2)
y1_m =
1 5 6 7 8 10
y2_m =
2 6 7 8 9 11
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check if firebase has finished adding items to database
I am sending data from my android app to a realtime firebase database.
I would like to check when firebase has finished adding these items into the database, as I will be calling a script on the server that will access the data in the database (through an asynctask).
But before I call the script, I need to make sure that firebase has finished adding all the items as to avoid any conflicts in the data. The code would be something like this:
myRef.child(userID).setValue(items); //add items to firebase database
new SendPostRequest().execute(); //call script on the server that will connect
to firebase database and retrieve data.
I was wondering if the script would be called whilst firebase is adding data to the database therefore it would retrieve partial data, so I need to make sure that firebase has finished adding the items into the database first.
A:
You can add a completion listener to setValue() to get notified when the call has completed.
See the section add a completion callback in the Firebase documentation for a full example.
mDatabase.child("users").child(userId).setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Write was successful!
// ...
}
})
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Don't give Informed badge if user hasn't fully read About page
I've just looked through About page for several seconds. After that I got Informed badge - "Read the entire about page". But it's not true - I've only scrolled it from top to bottom.
I propose to measure the amount of time that user spent in each section. It should be at least 3 seconds to get the badge.
A:
There's no real sure-fire way of making sure somewhere reads all of it. You can add in complicated things, like making users click-to-expand every section of the FAQ, but that still doesn't really guarantee anything. All it guarantees is they know how to click their mouse.
If people really don't want to read it, they're not going to read it. All the badge really does is get the user to the page so they know about it, and encourage them to look it over.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Images Get Stretched on Circle Image - Bootstrap & SCSS
PLEASE HELP !!!
I am using bootstrap cards to make a section of my website.I am facing issue in circle image of the cards.I want my images do not get stretch when i put them in image circle of card.Is there a way i can zoom in middle of the image while showing it in circle or am i doing something wrong in my scss code ??
Here is the issue:
Expected Output:
Dimensions of these Images:
910x592 , 1230x802 , 1230x794
Bootstrap Code:
<section class="about-cards-section">
<div class="container">
<div class="row">
<div class="col-sm-4 card-wrapper">
<div class="card card-style" >
<img class="card-img-top rounded-circle circle-image" src="img/about/card-one.png" alt="Card image cap">
<!-- <img src="img/about/card-one.png" class="img-circle" alt="Cinque Terre" width="250" height="236"> -->
<div class="card-body">
<h3 class="card-title">Our Facilities</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
<div class="col-sm-4 card-wrapper">
<div class="card card-style">
<img class="card-img-top rounded-circle circle-image" src="img/about/card-two.png" alt="Card image cap">
<div class="card-body">
<h3 class="card-title">Our Research</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
<div class="col-sm-4 card-wrapper">
<div class="card card-style">
<img class="card-img-top rounded-circle circle-image" src="img/about/card-three.png" alt="Card image cap">
<div class="card-body">
<h3 class="card-title">Our Expertise</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
</div>
</div>
</section>
SCSS of the Cards Section:
.about-cards-section{
.card-wrapper{
margin: 5% 0;
.card-style{
text-align: center;
border-radius: initial;
border: initial;
.circle-image{
width: 60%;
height: 200px;
text-align: center;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
.card-title{
text-transform: uppercase;
letter-spacing: 1.1px;
}
.card-text{
font-family: MerriweatherRegular;
font-size: 22px;
line-height: initial;
}
}
}
A:
The way I see it, you just need to adjust the width, height of .circle-image class and add object-fit: cover; property. But since you're using Bootstrap we can minimize your css using the pre-defined class in BS4
Example:
.card-wrapper {
margin: 5% 0;
}
/* You can adjust the image size by increasing/decreasing the width, height */
.custom-circle-image {
width: 20vw; /* note i used vw not px for better responsive */
height: 20vw;
}
.custom-circle-image img {
object-fit: cover;
}
.card-title {
letter-spacing: 1.1px;
}
.card-text {
font-family: MerriweatherRegular;
font-size: 22px;
line-height: initial;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<section class="about-cards-section">
<div class="container">
<div class="row">
<div class="col-sm-4 card-wrapper">
<div class="card border-0">
<div class="position-relative rounded-circle overflow-hidden mx-auto custom-circle-image">
<img class="w-100 h-100" src="https://source.unsplash.com/910x592" alt="Card image cap">
</div>
<div class="card-body text-center mt-4">
<h3 class="text-uppercase card-title">Our Facilities</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
<div class="col-sm-4 card-wrapper">
<div class="card border-0">
<div class="position-relative rounded-circle overflow-hidden mx-auto custom-circle-image">
<img class="w-100 h-100" src="https://source.unsplash.com/1230x802" alt="Card image cap">
</div>
<div class="card-body text-center mt-4">
<h3 class="text-uppercase card-title">Our Research</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
<div class="col-sm-4 card-wrapper">
<div class="card border-0">
<div class="position-relative rounded-circle overflow-hidden mx-auto custom-circle-image">
<img class="w-100 h-100" src="https://source.unsplash.com/1230x794" alt="Card image cap">
</div>
<div class="card-body text-center mt-4">
<h3 class="text-uppercase card-title">Our Expertise</h3>
<p class="card-text">A short caption detailing an aspect of the brand which is worth mentioning.</p>
</div>
</div>
</div>
</div>
</div>
</section>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
reevaluate wildcard in make
In my Makefile, I want to check if a certain file exists, do something, and check again. Using gnu make, I cannot. Here is the simple example:
$(info $(wildcard OK))
$(shell touch OK)
$(info $(wildcard OK))
If I run make once, I see two empty lines. If I run make again, both lines are OK.
I thought, maybe $(eval) will let me get the updated answer. Alas,
$(eval $$(info $$(wildcard OK)))
produces the same answer, as if make has some way to predict all wildcard calculations before it starts evaluating other commands.
I need this to satisfy the checks performed by Android NDK: I must generate a prebuilt shared library on the fly.
A:
This cannot work because, for performance, make maintains an internal cache of the directory contents. Currently that cache is only updated when make runs a rule: then the target the rule is defined to create will be added to the cache. In your situation make has no way to know that the filesystem has been modified so it won't update the cache.
You have to use the shell, rather than wildcard; the shell doesn't know about make's internal caches:
$(info $(wildcard OK))
$(shell touch OK)
$(info $(shell [ -f OK ] && echo OK))
Clearly this is a bogus example but I'm sure your real code is significantly different than this.
The only other alternative is to turn the command you need to run into a rule. But again, since the question bears little relation to what you're really trying to do I can't suggest a solution that would work for that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Relationship between degrees and number of edges
Why
$(\sum_{v_iv_j \in E(G)} \sqrt{d(i)d(j)} )(\sum_{v_iv_j \in E(G)}\frac{1}{ \sqrt{d(i)d(j)}}) \ge m^2$
is true? I mean, how to proof it?
$m$ is number of edges and $d_1,d_2,\dots ,d_n$ is degree sequence.
A:
Use Cauchy–Schwarz inequality for $N$-dimensional space
$$
(x_1^2 + \cdots + x_N^2)(y_1^2 + \cdots + y_N^2) \geq (y_1x_1 + \cdots + y_Nx_N)^2.
$$
All degrees $d(i)$ and their square roots are positive, thus you can safely assume $\sqrt{d(i)d(j)} = x_k^2$ and $1/\sqrt{d(i)d(j)} = y_k^2$.
Note: For $n$ vertices there are $N = n(n-1)/2$ possible pairs of vertices. It is always the case $N \geq m$ with equality if and only if the graph is full.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find elements of a list matching specific patterns
I have defined several symbolic function f[x],g[x,y],h[x,y,z] etc... And I have a list made of elements which are product of these functions with different arguments; for example,
list = { f[a]f[-a], f[a]g[c,d]h[-a,-c,-d], f[c]f[-c] ,
f[d]g[a,y]h[-d,-a,-y] , f[b]f[-a] , f[-c]f[c] ,
f[d]g[a,y]h[-d,-a,-z] }
Actually, these functions are just symbolic. They do not return any value. You can think the functions' arguments as tensorial indexes.
I want to find an efficient function checkPattern[list_] which does the following
1) Take the first element f[a]f[-a] and find if there are others elements matching this pattern; so, for example, the third element of list is "equal" to the first one, in the sense that f[a]f[-a]~f[c]f[-c]~f[-c]f[c] irrespectively of the arguments. Note that the elements f[a]f[-a] and f[b]f[-a] are different.
2) Take the second element (which is more complicated) and does the same check as the step 1.
So the result would be
checkPattern[list]
(* {{1,3,6},{2,4},{5},{7}}*)
A:
Here is your list:
list = {f[a] f[-a], f[a] g[c, d] h[-a, -c, -d], f[c] f[-c],
f[d] g[a, y] h[-d, -a, -y], f[b] f[-a], f[-c] f[c],
f[d] g[a, y] h[-d, -a, -z]};
Borrowing from here, we can find a list of all distinct patterns as follows:
patterns = Quiet[
SortBy[
DeleteDuplicates[
list /.
p : Alternatives[a | b | c | d | x | y | z] :>
Pattern[p, Blank[]],
Internal`ComparePatterns[##] == "Identical" &
],
MemberQ[{"Identical" , "Specific"}, Internal`ComparePatterns[##]] &]
];
Observe that I had to specify which symbols may be used as "indices".
A first approximation to the ultimate result could be
allpos = Map[Flatten@Position[list, #] &, patterns]
{{1, 3, 6}, {1, 3, 5, 6}, {2, 4}, {2, 4, 7}}
This can be cleaned up by utilizing that patterns is already ordered:
Table[Complement[allpos[[i]], Union @@ allpos[[1 ;; i - 1]]], {i, 1, Length[allpos]}]
{{1, 3, 6}, {5}, {2, 4}, {7}}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Populating Drop down list with ViewBag in Asp.net
I have made a View named ManageSalesman, it has two sub Views named AddOrEdit and it contains a form. Here I want to populate the Vendor companies list in the drop down from the Vendor table in the database, for that I get them in view bag in the following code.
ViewBag.Vendor = new SelectList(db.Vendors, "Id", "name");
and make drop down list in AddOrEdit by the following line of code.
@Html.DropDownListFor(model => model.CompanyId, new SelectList(ViewBag.Vendor, "Id", "name"), "Select Vendor Company", new { @class = "form-control" })
but when I run it, it will show me: Argument null exception "Additional information: Value cannot be null." Kindly tell me what I am doing wrong.
A:
I have not make a list of selected vendor in a controller.The correct way is as follow.
List<Vendor> VendorList = db.Vendors.ToList();
ViewBag.Vendor = new SelectList(VendorList, "Id", "name");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL - Count Null Linked Values
I have 2 tables and need to return the counts of some items grouped by category. The category names are contained in another table so it looks like this and not every item has a status associated with it
Table 1
Item1 | ID1 |StatusID1
Item2 | ID2 |StatusID2
Item3 | ID3 |StatusID2
Item4 | ID4 |
Table 2
StatusID1 | StatusA
StatusID2 | StatusB
I Basically need to see
StatusA | CountStatusA
StatusB | CountStatusB
I can get them to display when there is a status but cannot get anything when there is no status assigned.
Thanks
A:
Go for a condition check where if status is null then either count it or display it as per your requirement. Assuming that no status means a null value.
You can do it like this(If the status id in first table is just space )
select table2.status,count(table1.id) from table2,table1 where table1.statusid=table2.statusid group by table1.statusid
union
select 'No status Id',count(table1.id) from table1 where table1.statusid=''
OR
You can do it like this(If the status id in first table is null )
select table2.status,count(table1.id) from table2,table1 where table1.statusid=table2.statusid group by table1.statusid
union
select 'No status Id',count(table1.id) from table1 where table1.statusid is null
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Counting the number of isomorphism types of abelian groups of order 2000
Number of isomorphism abelian groups of order 2000?
$2000 = 2^4 5^3$, and the non-isomorphic groups is just $4\times 3$.
A:
The isomorphism classes of abelian groups of order $p^m$ ($p$ a prime, $m\gt 0$) correspond to the number of ways in which we can partition $m$, since such a group must be of the form
$$C_{p^{a_1}}\oplus\cdots\oplus C_{p^{a_k}}$$
with $0\lt a_1\leq a_2\leq\cdots\leq a_k$ and $a_1+\cdots+a_k = m$. So you want to count the number of ways to partition $4$ (to get all the isomorphism types of abelian groups of order $2^4$) and all the ways to partition $3$ (to get all the isomorphism types of abelian groups of order $5^3$. Then multiply them together, since the group is isomorphic to the product of its $p$-parts, and they can be chosen independently.
A:
GAP tells me there are 15 of them, so there is something wrong with your method.
Interestingly, according to GAP there are $963$ groups of alder $2000$ in all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
calling c++ dll from c# and accessviolation issue, what are my choices?
I have a 64 bit C++ DLL that I do not have code for.
I do have the .h and .lib corresponding files.
I can call 2 of the APIs without issues. They return the version number. So this tells me the DLL is loaded correctly in my application and all is good.
The problematic API takes const char *:
bool func(const char *a, const char *b, const char *c, const char *d, const char *e, int number);
I have created a C# wrapper for this:
[DllImport(mDllName, CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern bool func(string a,
string b,
string c,
string d,
string e,
int number);
I know this wrapper is ok, because the parameters are filenames. If I pass in an non existing filename I get a dialog generated from the DLL saying so and so filename doesn't exist. However this function crashes with "Access violation reading location 0x3C".
So my take is that there is no issue with the c# wrapper I wrote. I know the C++ dll works ok as I am trying to convert an existing working c++ application to c#. The c++ application already uses the DLL in question.
So what may be going on here? My take is maybe there is a bug in the actual DLL but the problem is not severe enough to present in the c++ application as perhaps memory is not checked more rigidly as in the C# application?
If this is the case is there any setting I can turn off to check memory less rigidly in c#? Or what are my options, taking into account I do not and will never gain access to the source code of the DLL. I really want this application in c#.
FURTHER ANALYSIS:
I created a simple WIN32 64bit DLL that has these APIs:
__declspec(dllexport) char *hello()
{
return "Hello from DLL !";
}
__declspec(dllexport) int number()
{
return 1979;
}
I have C# wrappers as below:
[DllImport("MAFuncWrapper.dll", CharSet=CharSet.Ansi)]
public static extern string hello();
[DllImport("MAFuncWrapper.dll")]
public static extern int number();
I can succesfully call number() but trying to call hello() gives me:
First-chance exception at 0x00000000774B4102 (ntdll.dll) in WindowsFormsApplication1.exe: 0xC0000374: A heap has been corrupted (parameters: 0x000000007752B4B0).
If there is a handler for this exception, the program may be safely continued.
A:
The p/invoke appears fine, modulo the return value which should be marshaled as UnmanagedType.U1.
There's no magic switch you can use to suppress this error. You have to fix the fault.
If you have a C++ program that succeeds when calling the function, and your C# program fails, then it seems that the C# program differs in some way. Remove the differences to solve the problem.
Regarding the other question you asked in your edit, this is wrong:
[DllImport("MAFuncWrapper.dll", CharSet=CharSet.Ansi)]
public static extern string hello();
The string return value leads to the marshaller calling CoTaskMemFree on the returned pointer. Hence the error.
You have to declare the return type as IntPtr and pass it to Marshal.PtrToStringAnsi.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Align Textviews in different rows using layout_weight parameter
I want to show a list of flights on a listview. And I want to have them all of them align. I have used a LinearLayout, with gravity and padding. But I want to reduce the space for the 4th column, so then I can do bigger the size of the text. I have tried to set the layout_weight of this element to 0 and all of the rest to 1. But it doesnt work. So far I have this
Any ideas?
A:
If you are going to use ListView with a list of LinearLayout view's (I would go with a TableRow list put into a TableLayout), then I would suggest predefining the width of each column in percentage of the total space (i.e. how much of the screen would you allow the column to allocate). Something among the lines:
// basically you build your adapter here
LinearLayout.LayoutParams wrapWrapLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int[] columnWidths = new int[]{20, 20, 20, 20, 20};
ArrayList<LinearLayout> tableRows = new ArrayList<LinearLayout>();//this is the adapter
LinearLayout row = new LinearLayout(this);
//add a header
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(headerColor);
row.addView(makeTableRowWithText(headerForCol1, columnWidths[0]));
row.addView(makeTableRowWithText(headerForCol2, columnWidths[1]));
row.addView(makeTableRowWithText(headerForCol3, columnWidths[2]));
row.addView(makeTableRowWithText(headerForCol4, columnWidths[3]));
row.addView(makeTableRowWithText(headerForCol5, columnWidths[4]));
tableRows.add(row);
for(int i = 0; i < numberOfItemsInTheFlightsTable; i++) {
row = new LinearLayout(this);
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.addView(makeTableRowWithText(col1Text, columnWidths[0]));
row.addView(makeTableRowWithText(col2Text, columnWidths[1]));
row.addView(makeTableRowWithText(col3Text, columnWidths[2]));
row.addView(makeTableRowWithText(col4Text, columnWidths[3]));
row.addView(makeTableRowWithText(col5Text, columnWidths[4]));
tableRows.add(row);
}
//util method
private TextView recyclableTextView;
public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
recyclableTextView = new TextView(this);
recyclableTextView.setText(text);
recyclableTextView.setTextColor(Color.BLACK);
recyclableTextView.setTextSize(20);
recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);
return recyclableTextView;
}
I mean, the trick is that you predefine the percentage of screen allocated by each column.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
1950-60's movie about alien that crashes to Earth and loses its hand which proceeds to attack people
Does anyone know about an old movie (I think it's black & white) in which an alien that crashes to Earth loses its hand. The thought has occurred to me that this may not be a movie, but a TV show episode.
The hand then crawls away from the crash site to become a stow-away in a woman's car. The alien's hand is cut just above the wrist and veins or tendons trail from it as it crawls. It has thin fingers. The setting is the daytime when it gets into the woman's car. When she gets home, the hand crawls into the house and hides in the closet where it crawls up to the top shelf and then jumps on the woman when she opens the door and strangles her. I think it goes on to hurt more people.
It is not the movie title, The Hand.
A:
Is it possible you're thinking of The Crawling Hand?
Astronauts keep going crazy and blowing up on their way back to the ground, and scientists can't figure out why. The latest astronaut to fall to this mysterious syndrome manages to contact his scientist superiors just before doing himself in; he alternates between pleas to "push the red" Self-Destruct Mechanism and violent urges to "Kill! Kill!" Finally the "red" is pushed, the astronaut is blown to shards and the scientists are still stumped.
Meanwhile, over in California, young med student Paul frolicks on the beach with his girlfriend when they happen upon the severed arm of the dead astronaut. Against his girl's wishes, Paul returns to the beach and takes the arm home with him (for what reason, we're not told). Soon, it becomes apparent to everyone (in the audience, at least) that whatever malediction had possessed the astronaut still possesses the arm, which promptly goes on a killing spree (said spree resulting in a grand total of ONE death). Paul himself is a prime suspect in the murder, but the two scientists arrive with their own theories. Then the mysterious murderous force begins to infect Paul as well, and he attacks a Malt Shop owner and his own girlfriend. After realizing what he's doing, Paul takes the hand out to a junkyard with the intent of destroying it, and between a fever of over 100 and some hungry cats, the evil is defeated... er, handily.
It's not an actual alien, but I think it otherwise matches.
A:
Invasion of the Hell Creatures (also known as Invasion of the Saucer Men) (1957)
A lot of the reviews on IMDb mention the aliens can detach their hands which attack people, for example:
In this one, a young couple accidentally run over an alien but its hand comes alive and terrorises people. The local farmer doesn't like the teenagers using his land for snogging in their cars. More aliens then appear and kill one of the teens with an overdose of alcohol as revenge for their mate being killed. A flying saucer then blows up with the military in attendance and the aliens are done away with at the end by light, their weakness. With a drunken bull.
Edward L. Cahn directed this cult classic about a pair of teenagers on a date who accidentally run over a newly arrived alien. Strangely, its hand falls off and comes to life on its own. Meanwhile, drunken friend Joe(played amusingly by Frank Gorshin) takes one home, but is injected by an alien with a fatal overdose of alcohol, and the authorities don't believe the teenagers' story of alien invaders.
I saw this movie in the early '60s, when I saw about 6 or 7. I have never been able to forget that severed hand, with the needles coming out of the fingertips, as it crawled up the car seat toward the unsuspecting teens.
The aliens look like the below:
It is available in full on YouTube here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle: Analytic Function partitioned over nullable values
I DON't want to count NULL values. Because NULL should not be equal to NULL.
Look at this query result: link
WITH temp as (
SELECT 'A' as master , 1 Col from dual
UNION SELECT 'A' , 3 from dual
UNION SELECT 'B' , 1 from dual
UNION SELECT 'B' , 2 from dual
UNION SELECT 'C' , 1 from dual
UNION SELECT NULL , 1 from dual
UNION SELECT NULL , 2 from dual)
SELECT
master,
count(Col) over (partition by master)
FROM
temp
A:
Alternatively, filter them out:
1 WITH temp as (
2 SELECT 'A' as master , 1 Col from dual
3 UNION SELECT 'A' , 3 from dual
4 UNION SELECT 'B' , 1 from dual
5 UNION SELECT 'B' , 2 from dual
6 UNION SELECT 'C' , 1 from dual
7 UNION SELECT NULL , 1 from dual
8 UNION SELECT NULL , 2 from dual)
9 SELECT
10 master,
11 count(Col) over (partition by master)
12 FROM
13 temp
14* WHERE master is not null
SQL> /
M COUNT(COL)OVER(PARTITIONBYMASTER)
- ---------------------------------
A 2
A 2
B 2
B 2
C 1
A:
If you don't want to filter out the rows where master IS NULL, you can do something like
SELECT master,
SUM( CASE WHEN master IS NULL
THEN 0
ELSE 1
END) OVER (PARTITION BY master)
FROM temp
SQL> ed
Wrote file afiedt.buf
1 WITH temp as (
2 SELECT 'A' as master , 1 Col from dual
3 UNION SELECT 'A' , 3 from dual
4 UNION SELECT 'B' , 1 from dual
5 UNION SELECT 'B' , 2 from dual
6 UNION SELECT 'C' , 1 from dual
7 UNION SELECT NULL , 1 from dual
8 UNION SELECT NULL , 2 from dual)
9 SELECT master,
10 SUM( CASE WHEN master IS NULL
11 THEN 0
12 ELSE 1
13 END) OVER (PARTITION BY master)
14* FROM temp
SQL> /
M SUM(CASEWHENMASTERISNULLTHEN0ELSE1END)OVER(PARTITIONBYMASTER)
- -------------------------------------------------------------
A 2
A 2
B 2
B 2
C 1
0
0
A:
Null isn't equal to null. But from the perspective of aggregation, null is equivalent to null. It's not the analytics that do that; it's the aggregation itself.
1 WITH temp as (
2 SELECT 'A' as master , 1 Col from dual
3 UNION SELECT 'A' , 3 from dual
4 UNION SELECT 'B' , 1 from dual
5 UNION SELECT 'B' , 2 from dual
6 UNION SELECT 'C' , 1 from dual
7 UNION SELECT NULL , 1 from dual
8 UNION SELECT NULL , 2 from dual )
9 SELECT
10 master,
11 count(Col)
12 FROM
13* temp group by master
SQL> /
M COUNT(COL)
- ----------
2
A 2
B 2
C 1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Default python unittests returns false positives
I have a python 2.7 project in visual studio using the python tools plugin.
I have created a basic test generated by the Visual studio template,
import unittest
class Test_test1(unittest.TestCase):
def test_A(self):
self.fail("Not implemented")
if __name__ == '__main__':
unittest.main()
The issue I am getting is that if i run the tests through test explorer they pass even though they include the self.fail.
If I debug the tests they will fail without hitting a break on any line of the file.
Has anyone had this issue before or know what could be causing this issue?
A:
I have solved this issue now, the only solution I could find was to uninstall then reinstall the python tools for visual studio.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find document in MongoDB collection based on time condition and write timestamp back?
I have a DB with "accounts" collection like this:
{u'timestamp': u'2016-06-09 23:29:50.083093', u'account': u'admin:password', u'_id': ObjectId('5766932f6f340ca9a70cdb16'), u'is_valid': u'True'}
I need to select one document based on this condition: if is_valid is true and if timestamp has passed 24 hours. So it should be True and current time 2016-06-10 23:29:50.083093 to pass the condition. Then I have to update timestamp of this document with current time.
How can I achieve this? I know how to apply the first condition:
import pymongo
from datetime import datetime
try:
conn=pymongo.MongoClient()
db = conn.instagram
collection = db.accounts
res = collection.find_one({"is_valid": "True"})
print res
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
A:
Use the $lt operator with a datetime instance passed as an argument:
from datetime import datetime, timedelta
dt = datetime.now() - timedelta(hours=24)
res = collection.find_one({"is_valid": "True", "timestamp": {"$lt": dt}})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
trading interview question: Find the probability of two line segment intersecting with each other.
Find the probability of two line segment intersecting with each other. The end points of lines are informally sampled from an uniform distribution between 0 and 1.
There are similar problems in this site however, i don't see any posts address the end points of lines are drawn from uniform distribution.
Here's my attempt, since the only case the intersection won't happen is if they were parallel. Say They are 8 numbers that we need to draw from the distribution. the first 4 numbers (2 points) are basically free, and we can have another point anywhere also, but the remaining one point has to be the "chosen one" for the two lines to be parallel, so I have $$1 -\frac{(2)}{(n)}$$ This is correct?
A:
The probability is $\frac 23$. There are four points drawn from the interval and all that matters is which point is paired with the lowest of the four. If it is the second lowest, the line segments will not intersect. If it is either of the other two, the line segments will intersect.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the difference between "mov (%rax),%eax" and "mov %rax,%eax"?
What is the difference between mov (%rax),%eax and mov %rax,%eax? I'm sure this is a simple question, but I can't find the answer anywhere.
Here is the original code that prompted my question:
mov -0x8(%rbp),%rax
mov (%rax),%eax
lea (%rax,%rax,1),%edx
mov -0x8(%rbp),%rax
mov %edx,(%rax)
mov -0x8(%rbp),%rax
mov (%rax),%eax
A:
In AT&T syntax, the instruction:
mov (%rax), %eax # AT&T syntax
or, equivalently in Intel syntax:
mov eax, DWORD PTR [rax] ; Intel syntax
dereferences the memory address stored in rax, reads a 32-bit value from that memory address, and stores it in the eax register.
Because the memory address being dereferenced is stored in rax, it can be a 64-bit address, which is necessary when running on a 64-bit operating system.
However, the data pointed to by that memory address is only 32 bits in size, so it can be stored in the 32-bit eax register.
Note that this instruction will implicitly zero the upper 32 bits of the rax register, so that the lower 32-bit half (called eax) will contain the loaded data, and the upper 32-bit half will be empty.
The parentheses in AT&T syntax (or the square brackets in Intel syntax) are your clue that this instruction treats the contents of the register as if they were a pointer.
This is what makes it different from, for example:
mov %rcx, %rax # AT&T syntax
mov rax, rcx ; Intel syntax
This simply copies the contents of the rcx register into the rax register. There is no dereferencing being done. The values in the register(s) are acted on directly.
Note that the above example was similar to the other example from your question:
mov %rax, %eax # AT&T syntax (INVALID!)
mov eax, rax ; Intel syntax (INVALID!)
but not identical. This last case is actually an invalid instruction because there is an operand-size mismatch. If it were valid, the instruction would be copying the contents of the 64-bit rax register into the 32-bit eax register. Of course, this is impossible. Narrowing conversions are not allowed, so it will not assemble.
If you really wanted to do this, you would have to decide which half of the 64-bit value in rax that you wanted to throw away. If you decided to throw away the upper bits and copy only the lower bits to eax, you wouldn't need to do anything—just use eax directly. If, however, you wanted to throw away the lower bits and use only the upper bits, you would first do a right-shift by 32.
Note that this is a fairly simple, general-reference question. You could have looked up the answer in any book on x86 assembly language, and a tutorial should have taught you about the significance of the parentheses/brackets syntax. Please see the x86 tag wiki for some tutorials and other general-reference information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How I can center a block vertically and horizontally with Bootstrap?
I have this form:
<div class="container-fluid">
<div class="span5 well">
<h2>Authentification</h2>
<form method="POST">...</form>
</div>
</div>
How I can center that block (div span5 well) vertically and horizontally? Thank you.
A:
Horizontal centering can be done by adding margin: 0 auto to an element that has no siblings.
A:
<style>
.well
{
position:absolute;
width:200px;
height:200px;
top: 50%;
left: 50%;
margin-top:-100px; /* negative number 1/2 height */
margin-left:-100px; /* negative number 1/2 width */
outline:1px solid #CCC;
}
</style>
<div class="container-fluid">
<div class="span5 well">
<h2>Authentification</h2>
<form method="POST">...</form>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring : binding object with and without @ModelAttribute
I am new in Spring and registering a user.I did like this.
@RequestMapping("/register")
public String register(@ModelAttribute User user,BindingResult result){
if(!result.hasErrors()){
userSerive.register(user);
}
return "welcome";
}
This worked fine,but problem here is I don't need this user object in my welcome.jsp page,so why make model object heavier.So I tried without @ModelAttribute, this also works for me like below.
@RequestMapping("/register")
public String register(User user,BindingResult result){
if(!result.hasErrors()){
userSerive.register(user);
}
return "welcome";
}
So I just want to know what are pros & cons of both and which is the best practice if I really don't need user object in jsp. Is @ModelAttribute does any other thing apart from adding object to Model,which spring implicit binding not does.Is @ModelAttribute safer way of binding or else?
I want to categories my query in following 4 type of request.what would be difference with and without @ModelAttribute if I need not to send data in view and my request is any of-
query string ie form data in GET
request payload or body ie form data in POST
json data in ajaxified GET requst
json data in POST requst- I guess this would not be bind in any of both. @RequestBody is required.
A:
There is probably (see below...) no difference in the behaviour between the two method signatures in your case.
Both will bind the request parameters to user and add the resulting object to the model as the attribute user - this attribute name being derived from the decapitalised type name of the method argument, User.
@ModelAttribute can be used to customise the name of the attribute, e.g. @ModelAttribute("theUser"), or to give a hint to the reader of your code that this argument is used in the view. But as you say, neither of these apply in your use case.
Exactly the same code in Spring will be used to populate the argument whether you use the @ModelAttribute annotation or not - the code in question is org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.
It therefore makes more sense to me for you to use the public String register(User user, BindingResult result) signature in your code. Adding a @ModelAttribute annotation to method arguments that are not required in the model could be confusing to people reading your code.
The slightly longer answer is that there could just about be a reason for specifying @ModelAttribute in your case - but it's quite arcane and unlikely.
Method arguments in Spring handler methods are populated by HandlerMethodArgumentResolver instances. These are configurable and are attempted in turn for each parameter.
The default handler method argument resolvers look like this (see RequestMappingHandlerAdapter):
resolvers.add(new ServletModelAttributeMethodProcessor(false));
...
resolvers.add(new ServletModelAttributeMethodProcessor(true));
If you were to add your own in the middle, e.g. a UserHandlerMethodArgumentResolver, you could then use @ModelAttribute to tell Spring to process a specific argument in the default way, rather than use your custom argument resolver class.
A:
This question is very useful, but I don't see the reply here answer the question properly.
I read through more threads in stackoverflow, and found this one very useful:
https://stackoverflow.com/a/26916920/1542363
For myself how to decide which one to use, if I only need the binding and do not want to store the parameter object in model, then don't use @ModelAttribute.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
An ignorant question about the incompleteness theorem
Let me preface this by saying that I have essentially no background in logic, an I apologize in advance if this question is unintelligent. Perhaps the correct answer to my question is "go look it up in a textbook"; the reasons I haven't done so are that I wouldn't know which textbook to look in and I wouldn't know what I'm looking at even if I did.
Anyway, here's the setup. According to my understanding (i.e. Wikipedia), Godel's first incompleteness theorem says that no formal theory whose axioms form a recursively enumerable set and which contain the axioms for the natural numbers can be both complete and consistent. Let $T$ be such a theory, and assume $T$ is consistent. Then there is a "Godel statement" $G$ in $T$ which is true but cannot be proven in $T$. Form a new theory $T'$ obtained from $T$ by adjoining $G$ as an axiom. Though I don't know how to prove anything it seems reasonably likely to me that $T'$ is still consistent, has recursively enumerable axioms, and contains the axioms for the natural numbers. Thus applying the incompleteness theorem again one deduces that there is a Godel statement $G'$ in $T'$.
My question is: can we necessarily take $G'$ to be a statement in $T$? Posed differently, could there be a consistent formal theory with recursively enumerable axioms which contains arithmetic and which can prove every true arithmetic statement, even though it can't prove all of its own true statements? If this is theoretically possible, are there any known examples or candidates?
Thanks in advance!
A:
You are right that $T'=T+G$ must be consistent. If it were not, then we could prove a contradiction from $T$ together with $G$, which would amount to a proof by contradiction of $\neg G$ in $T$. But that contradicts the fact that $G$ is independent of $T$!
On the other hand, when you ask
Posed differently, could there be a consistent formal theory with recursively enumerable axioms which contains arithmetic and which can prove every true arithmetic statement, even though it can't prove all of its own true statements?
that cannot be, because the independent statement $G$ produced by Gödel's construction is always an arithmetic statement. ($G$ is often popularly explained as stating something about provability or not, which is correct so far as it goes -- but the major achievement of Gödel's work is to show how such claims can be expressed as arithmetic statements).
Indeed, if the original theory $T$ was something like Peano Arithmetic, the language of the theory does not allow one to even state any sentence that is not arithmetic -- and no amount of added axioms can change that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails controller rendering last template of iteration for all tests
I had controller tests that check that the right template is rendered for varying status codes. They worked.
I am trying to refactor the tests using iteration as follows:
context 'renders multiple views based on status code' do
VIEW_MAP = {
404 => 'not_found', 500 => 'server_response', 402 => 'client_response'
}
VIEW_MAP.each do |status_code, view|
retrieve_deal(status_code)
it 'renders the #{view} template for status code #{status_code}' do
get :show, params: { id: 'id' }
expect(response).to render_template(view)
end
end
end
where retrieve_deal method mocks an API call with a status code, and sends the response to the controller.
However, the last template ('client_response') is rendered for all the tests. Any ideas where I am going wrong?
A:
I think each iteration needs to be in a context, and:
retrieve_deal(status_code)
needs to be in something like before.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ConstraintViolationTransactionFailureException when deleting all nodes from Neo4j
When attempting to delete all nodes from my Neo4j graph database, which I have successfully done many times in the past on smaller datasets, I consistently ran across Error: undefined - undefined after running this query
MATCH (n) DETACH
DELETE n
I figured the number of nodes I was attempting to delete at once may be too large (>100000), so I then tried this query
MATCH (n)
OPTIONAL MATCH (n)-[r]-()
WITH n,r LIMIT 10000
DELETE n,r
and many variations of it, acting on mostly what I read in this post: Best way to delete all nodes and relationships in Cypher. All returned this error
org.neo4j.kernel.api.exceptions.ConstraintViolationTransactionFailureException: Cannot delete node<32769>, because it still has relationships. To delete this node, you must first delete its relationships.
and each time, the node Neo4j could not delete differs. Is there any way of resolving this issue?
Perhaps also noteworthy, while desperately running variations of the previous query, when I ran this query
MATCH ()-[r]-()
OPTIONAL MATCH (n)-[r]-()
WITH r,n LIMIT 10000
DELETE r,n
I got this rather unique error
Java heap space
in the console, which showed up as Neo.DatabaseError.General.UnknownError in the banner.
A:
One of the problems with the way your queries are written is that each DELETE is only attempting to delete a single node/relationship pair at a time. If any nodes have more than one relationship, you will get that constraint violation error, since in order to delete a node you have to delete all of its relationships (either beforehand or at the same time).
To delete 10000 nodes (and all their relationships), use this query:
MATCH (n)
WITH n LIMIT 10000
DETACH DELETE n;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the gain margin of the system, when the phase crossover frequency does not exist?
I have a simple questions
I have a system in which the system will never reach -180 degrees for any frequency.
Does that make the gain margin infinite ?
If yes, does that mean that the system will always be stable for any gain ?
Thanks
A:
What is the gain margin of the system, when the phase crossover
frequency does not exist?
You use the word "exist" and in any circuit that "exists", due to the speed of light being finite, there will always be a frequency where there is an inversion of signal aka 180 degrees phase shift.
I have a system in which the system will never reach -180 degrees for
any frequency.
No you don't - not in this universe.
A signal with a frequency of 300 MHz has a 1 metre wavelength (or less) hence: -
A 50 mm long wire at 3 GHz produces an end-to-end phase shift of 180 degrees.
At 30 GHz, 180 degrees phase shift is obtained with a 5 mm long wire.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculating coefficients of interpolating polynomial using Neville's algorithm
First of all, sorry for my bad math terminology as it's not my native language and I may misuse some terms in English.
I've been tasked with writing an application which calculates the general formula of interpolating polynomial (being given a set of $X_i$ and $Y_i$), however, I have to use Neville's algorithm for that. I know Lagrange's method can be used, but I've been told to use Neville's algorithm specifically.
So, my question is - is it even possible? If so, how should I calculate the coefficients of the interpolating polynomial using this algorithm $(a_0, a_1,\dots ,a_n)$?
I feel like I'm missing a point somewhere (maybe because I'm not that good at maths), but I can't find a solution to this.
I'll be honest with it - this is homework. But I'm not asking for a solved code, just need help with understanding this.
A:
I think you can calculate the coefficients of the interpolation polynomial as follows.
The algorithm given on the Wikipedia page http://en.wikipedia.org/wiki/Neville%27s_algorithm works not only for the value of the interpolation polynomial at a given point x, but also for the complete interpolation polynomial (in a mathematical sense, regarding the interpolation polynomial as an element of the polynomial ring $\mathbb R[X]$). More specifically, the initial polynomials $p_{i,i}(X) = y_i$ are constant. From there, we can calculate the intermediate polynomials $$p_{i,j}(X) = ((x_j - X) p_{i,j-1}(X) + (X - x_i) p_{i+1,j}(X))/(x_ j - x_i)$$until we reach the complete interpolation polynomial.
Now, all you have to do is to translate this recursive scheme for polynomials into a form suitable for mainstream programming languages :-). You can do this by identifying a polynomial with its coefficient vector. We know that, given n + 1 interpolation points $(x_i, y_i)$, the interpolation polynomial has degree n, and more generally, the polynomial $p_{i,j}$ from the recursive scheme with $0 \leq i < j \leq n$ has degree $j - i \leq n$. So, all the polynomials we have to consider, and their corresponding coefficient vectors are of the form $$p(X) = a_0 + a_1 X + \cdots + a_n X^n <-> (a_0, \ldots, a_n).$$
And of course, in a programming language, a coefficient vector is just an array :-).
With this correspondence, we can translate the recursive scheme from above into a recursive scheme for coefficient vectors.
First, the initial polynomial $p_{i,i}(X) = y_i$ has coefficient vector $(y_i, 0, \ldots, 0)$.
Next, we have to figure out the coefficient vector of $Xp_{i,j-1}(X)$ given the coefficient vector of $p_{i,j-1}(X)$. But that's easy. Multiplying a polynomial by $X$ shifts its coefficient vector to the right. So, if we denote the coefficient vector of the polynomial $p(X)$ by $V(p(X))$ and on coefficient vectors define the shift operator $$S((a_0, \ldots, a_n)) = (0, a_0, \ldots, a_{n - 1}),$$ then we have $$V(Xp(X)) = S(V(p(X)).$$Check that :-).
Now we can rewrite the recursion for polynomials from above as a recursion for their coefficient vectors and get
$$V(p_{i,j}(X)) = (x_jV(p_{i,j-1}(X)) - S(V(p_{i,j-1}(X))) + S(V(p_{i+1,j}(X))) - x_iV(p_{i+1,j}(X))) / (x_j - x_i).$$
Now you have a recursive scheme for coefficient vectors of polynomials which takes you from the coefficient vectors of the initial, constant polynomials $p_{i,i}$ all the way to the coefficient vector of the complete interpolation polynomial.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hierarachy viewer is not working in google LG nexus 4?
I was trying to open hierarchy viewer of web apps using google nexus 4 . But it has not working. Then i am searching some form and sites regarding this issue but there are telling the way root the device then If root the device may be void the warranty. Is there any way to open hierarchy. i saw one site regarding hierarchy but there are mentioning like void the warranty then we can revoke the warranty. Here my concern is it correct? can we revoke the warranty?
Link is :http://android.sc/how-to-root-google-nexus-4/
A:
For security purposes, hierarchyviewer only works on debug / developer devices.
The Nexus 4 does qualify, but you WILL need to unlock the phone first before you can do so. Since you're concerned with warranty, then you shouldn't do that.
The closest thing you can do is to apply Romain Guy's ViewServer romainguy/ViewServer on your application, then you can use HierarchyViewer on your app.
(Note: Yes, you can relock the bootloader and unroot from guides in XDA, but it is up to you if you want to do that and pretend your warranty still holds.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Screen Sharing on iPhone
Is it possible on the iPhone to share the screen live? In other words I would have an app on the iPhone that would allow a person to see my screen live while they watched via a secure URL.
I have seen some apps that allow for screen sharing of files from the iPhone but not the actual screen.
If it is not possible to share the screen live is it possible to record a video of the screen?
Notes: I am not looking for ways to control another iPhone just show the screen live, I am not on a jailbroken iPhone, and I am running iOS 6. Also I am curious to the same for the iPad.
A:
So if you're looking for a solution to "stream" your iPhone screen directly to the Internet, the answer is NO.
But if you are willing to break the problem down to two, that might be possible with an external computer, PC or Mac, though PC is recommended.
Two break it into two parts, you first want your iPhone screen to appear on the Mac or PC's screen. We'll use something called "Airplay Mirroring", and on Mac and PC, "Air Server", or an app on Mac "Reflector". You can find both Air Server and Reflector on the Internet, and both offers trial.
Then you want to stream your Mac or PC's screen to the Internet. On Mac, I DON'T prefer any application, they are all slow and have poor quality. This is what I like, "321ShowIt", which is Java-based, but works better than the solutions here.
There's also a down side to 321ShowIt, it streams to a webpage that needs Java to watch. But those other solutions streams to Twitch, where people need only Flash, and have dedicated apps on both iOS and Android.
On PC, you of course can use 321ShowIt, but I prefer XSplit Broadcaster, it's an amazing high quality streaming application for a wide range of platform, including Justin.tv and so on.
So, if those don't suit your need, a jailbreak will be required. But even so, you will be limited to providing VNC connection. Streaming from iOS device is really not a good option since compressing the H.264 stream and serving it live will cause a noticeable performance hit on even the fastest Apple A6.
Anyway, good luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Essentials "worth.yml" inconsistency
I'm trying to set prices for all items in the Essentials plugin's "worth.yml" config file.
The server is running 1.11.2.
Only some items in the config are recognized, and I don't see the problem.
For example, the line for beacon in config is
beacon: 15000.0
and the game responds correctly, when asked "/price beacon",
The line for iron horse armor is
ironhorsearmor: 44.0
but when asked "/price ironhorsearmor" (a valid name in essentials), the game answers
Why are some items unrecognized?
All prices across the file are configued the same way
"Working" items "work" for /price, /buy, and /sell
"Broken" items do not work for /price, /buy, or /sell
Examples of working items are beacons, stone, all clay colors, saplings
Examples of broken items are carrots, all horse armors, all dye colors
The whole file can be found here
A:
I believe the problem from what I saw is that the official Minecraft id for iron horse armor is:
iron_horse_armor
And not,
ironhorsearmor
so I believe this is the problem I would suggest changing this and trying it again. If that doesn't fix it then its probably the actual mod and I would need to see it.
Plus if this does fix it then you will need to change the other horse armors as well.
Minecraft Id List
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linux/Unix variant for training system administrators
Is there a Linux/Unix based operating system used for training sysadmins?
Some bugs would be deliberately included in the system and the training candidate is supposed to solve all of them. It should be something similar to WebGoat.
A:
To my knowledge, there is not a specific distro for this, but you might want to look at http://trouble-maker.sourceforge.net/ and make use of it on your favorite distro.
A:
there is a college professor that put together a good tutorial site called linuxzoo.net with assorted tutorials that will familiarize you with Unix/Linux basics, all the way up to beginning/intermediate administration topics...it's a great safe environment to start in where you don't have to worry about breaking anything.
Creating an account is free and its usage is also free.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get around the Circular Reference issue with JSON and Entity
I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON.
I am using the code first method to create my database. When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)
class parent
{
public List<child> Children{get;set;}
public int Id{get;set;}
}
class child
{
public int ParentId{get;set;}
[ForeignKey("ParentId")]
public parent MyParent{get;set;}
public string name{get;set;}
}
When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent.
I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point.
I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).
Base.baseParent basep = (Base.baseParent)parent;
return Json(basep, JsonRequestBehavior.AllowGet);
The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name). This method seems forced although it works.
NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model. In my searching I have not seen a good method to overcome this problem.
My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data. While maintaining a consistant model across layers (or as best as I can come up with).
A:
I see two distinct subjects in your question:
How to manage circular references when serializing to JSON?
How safe is it to use EF entities as model entities in you views?
Concerning circular references I'm sorry to say that there is no simple solution. First because JSON cannot be used to represent circular references, the following code:
var aParent = {Children : []}, aChild = {Parent : aParent};
aParent.Children.push(aChild);
JSON.stringify(aParent);
Results in: TypeError: Converting circular structure to JSON
The only choice you have is to keep only the composite --> component part of the composition and discard the "back navigation" component --> composite, thus in you example:
class parent
{
public List<child> Children{get;set;}
public int Id{get;set;}
}
class child
{
public int ParentId{get;set;}
[ForeignKey("ParentId"), ScriptIgnore]
public parent MyParent{get;set;}
public string name{get;set;}
}
Nothing prevents you from recomposing this navigation property on your client side, here using jQuery:
$.each(parent.Children, function(i, child) {
child.Parent = parent;
})
But then you will need to discard it again before sending it back to the server, for JSON.stringify won't be able to serialize the circular reference:
$.each(parent.Children, function(i, child) {
delete child.Parent;
})
Now there is the issue of using EF entities as your view model entities.
First EF is likely to using Dynamic Proxies of your class to implement behaviors such as change detection or lazy loading, you have to disable those if you want to serialize the EF entities.
Moreover using EF entities in the UI can be at risk since all the default binder will mapping every field from the request to entities fields including those you did not want the user to set.
Thus, if you want you MVC app to be properly designed I would recommended to use a dedicated view model to prevent the "guts" of your internal business model from being exposed to the client, thus I would recommend you a specific view model.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a UI widget that allows the user to select between two options (left or right)?
I need to implement a UI element that the user will use to select between two options (left and right).
Similar to a seekbar, but if the user drags all the way to one side or another, it will trigger an action depending which side was selected. If the user lets go without touching either side, the thumb knob will bounce back to the center.
I think this is a common UI element but I can't seem to think of an example.
EDIT: A similar element would be the slider which is found on the iPhone lock screen. In my case, the thumb knob would start in the middle and could be dragged in either direction.
Does anybody know of a library that might contain this, or will I need to extend the seekbar to implement it?
A:
Implement your own segment control like this:
Source code of this segment control is available in https://github.com/makeramen/android-segmentedradiobutton
A:
I would make a subclass of a view and use onTouchEvent() and onDraw() to determine where the user is touching and draw the screen accordingly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
npm audit fix --force causes error: Data path ".builders['app-shell']" should have required property 'class'
I got this message after I installed a package:
added 1 package from 8 contributors and audited 49729 packages in 23.754s
found 25 vulnerabilities (1 low, 24 high)
run `npm audit fix` to fix them, or `npm audit` for details
So I ran npm audit fix and it fixed some of the vulnerabilities.
...
+ @angular-devkit/[email protected]
+ @angular-devkit/[email protected]
added 125 packages from 72 contributors, updated 8 packages and moved 16 packages in 65.005s
fixed 12 of 25 vulnerabilities in 49729 scanned packages
3 package updates for 13 vulns involved breaking changes
(use `npm audit fix --force` to install breaking changes; or refer to `npm audit` for steps to fix these manually)
It suggested use npm audit fix --force, I used it and now when I try run the Angular app it get this error:
Schema validation failed with the following errors:
Data path ".builders['app-shell']" should have required property 'class'.
Error: Schema validation failed with the following errors:
What is going on, should I be using npm audit fix or ignore the warnings. How can I get my app working again?
It shows this message after I run the force fix but it's too late already ran the command:
npm WARN using --force I sure hope you know what you are doing.
The packages installed:
https://stackblitz.com/edit/typescript-uuubb8
A:
Always be careful with the --force flag. It's like shutting down a computer by pulling out the cable. You basically "force" NPM to do what you want it to do, even if NPM knows that your app will crash then.
To fix this you have to revert the changes manually.
You can also try to run npm update. It will update every package (but backup your project before!). Maybe this is enough to fix it.
If you have to fix a vulnerability in the future, do it without the --force flag. If that doesn't work, do it manually by running npm audit: It will show you the details of the issue, without doing anything.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Interval Selection Event in Primefaces Chart
I have a dynamic LineChart. I am setting the zoom to false but I want to be able to trigger an Ajax Event when selecting an area in the Chart (like the zoom functionnality when selecting the area you want to zoom), I want to call a server method and getting the max and min x axis values of the selected area.
Can anyone help with this?
Else if I set the zoom to true, is there any way to get the values from the zoomed area ?
A:
PrimeFaces and JSF is in this context nothing more than an html/javascript/css generator. If you look at the source of the generated page in your browser developer tool, you'll see a lot of javascript, including all datapoints.
<script id="j_idt87_s" type="text/javascript">
$(function(){PrimeFaces.cw('Chart','chart'{
id:'j_idt87',
type:'line',
data:[[[1,2],[2,1],[3,3],[4,6],[5,8]],[[1,6],[2,3],[3,2],[4,7],[5,9]]],
title:"Zoom",
legendPosition:"e",
axes:{
xaxis:{
label:"",
renderer:$.jqplot.LinearAxisRenderer,
tickOptions:{angle:0}},
yaxis: {
label:"",
min:0,
max:10,
renderer:$.jqplot.LinearAxisRenderer,
tickOptions:{angle:0}}
},
series:[{label:'Series 1',renderer: $.jqplot.LineRenderer,showLine:true,markerOptions:{show:true, style:'filledCircle'}},{label:'Series 2',renderer: $.jqplot.LineRenderer,showLine:true,markerOptions:{show:true, style:'filledCircle'}}],zoom:true,datatip:true},'charts');});
</script>
So the answer to this question is valid for the PrimeFaces charts as well.
Running the following code (from the link above) in your browser developer tool on the zoom examples will show you the data points that fall in your zoom region
chart = PF('chart').plot;
PF('chart').plot.target.bind('jqplotZoom', function(ev, gridpos, datapos, plot, cursor){
var plotData = plot.series[0].data;
for (var i=0; i< plotData.length; i++) {
if(plotData[i][0] >= chart.axes.xaxis.min && plotData[i][0] <= chart.axes.xaxis.max ) {
//this dataset from the original is within the zoomed region
//You can save these datapoints in a new array
//This new array will contain your zoom dataset
//for ex: zoomDataset.push(plotData[i]);
console.log(plotData[i]);
}
}
});
Replacing PF(çhart') with PF('myLineChartWV') will make it work for your example to
Once you have gathered the data, you can use this in e.g. a PrimeFaces remoteCommand to pass it to the server.
Notice that this only takes the x-axis value of the zoom into account. If you want the y-axis taken into account to (so the real zoom area), add
plotData[i][1] >= chart.axes.yaxis.min && plotData[i][1] <= chart.axes.yaxis.max
to the if-statement in the loop.
Also notice it just takes the first series. If you have multiple, you have some simple homework to do.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add 1Password extensions support to the SE iOS app
Please implement the URL scheme to call 1Password for password lookups on the iOS app.
http://blog.agilebits.com/2013/01/24/developers-heres-how-to-add-a-little-1password-to-your-ios-apps/
a URL scheme for switching to 1Password to search item titles for a custom term, usually a service name like “twitter” or “evernote”. This speeds up the process for the user so they can copy something like their password and get back to your app
That will ease sign up speed using long, complicated or unmemorable passwords for many users of both apps. In the two years since the above blog was published there are now updated instructions for implementation and code on github:
https://agilebits.com/onepassword/devoutreach
https://github.com/AgileBits/onepassword-app-extension
A:
We discussed this briefly and while nobody was opposed to doing this, really, it just isn't very high on the list. We still have plenty of bugs coming in that are crashing issues, and we still have a lot of features to implement before we will be ready for the app store. It's not a bad idea, we just aren't going to get to it soon.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Estimate the error of approximation of $ln(1+x)$
Estimate the error of approximation
$ln(1+x) ≈x-x^2/2+x^3/3-x^4/4$
For $|x|≤0.5.$
I use Taylor formula and got this
$r_5 (x)= f^5 (x_0)/(5!) *(x^5)$
what do I do next to get the actual number.
A:
In general, for the $n$'th order error term we have
$$
R_n(x)= (-1)^n \frac{1}{n!} \int_0^x (t-x)^n f^{(n+1)} (t) \; dt.
$$
Now, evaluate at $x=0.5$ and take $n=5$, i.e. $|R_5(0.5)|$ is the error term.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to override values set in properties file for java.util.logging programatically?
I have an application for which I want to have the logging level set to INFO unless Debug Mode is set in which case I want to set the level to FINEST.
If I set the level in the properties file it does not get overridden from the program using logger.setLevel(Level.FINEST) also, if I do not set anything for the .level field in the properties file, by default the INFO level is taken and again I cannot override to use FINEST if isDebugEnable().
How can I make this level configurable based on the condition ?
try(InputStream configFile = getClass().getClassLoader().getResourceAsStream("logging.properties")) {
LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException e) {
throw new IllegalStateException("Unable to load default logging properties.", e);
}
if (isDebugEnabled()) {
logger.setLevel(Level.FINEST);
} else {
logger.setLevel(Level.INFO);
}
My config file is as follows:
handlers= java.util.logging.ConsoleHandler
.level= INFO
# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
# Enable console to set level to FINEST and above.
java.util.logging.ConsoleHandler.level = FINEST
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
I can do this using as follow, but would like to know if there is a better way to do this. (May be using properties file)
ConsoleHandler consoleHandler = new ConsoleHandler();
setLogLevel();
consoleHandler.setLevel(Level.FINEST);
logger.addHandler(new ConsoleHandler());
A:
If you are setting a DEBUG option before startup of the JVM then just package a 2nd logging.properties file called debug.properties and change the java.util.logging.config.file to point to the debug.properties when you want debug options.
handlers= java.util.logging.ConsoleHandler
.level= FINEST
# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
# Enable console to set level to show all levels.
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
If you have to set the levels at runtime you'll run in to problems with readConfiguration not resetting all everything after boot of the JVM. Under JDK 8 or older all you can do is call readConfiguration to populate the defaults and add more code to fix the broken behavior. Since you just need to set the level on handlers then just add that code.
try(InputStream configFile = getClass().getClassLoader().getResourceAsStream("logging.properties")) {
LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException e) {
throw new IllegalStateException("Unable to load default logging properties.", e);
}
Level lvl;
if (isDebugEnabled()) {
lvl = Level.FINEST;
} else {
lvl = Level.INFO;
}
logger.setLevel(lvl);
for(Handler h : logger.getHandlers()) {
h.setLevel(lvl);
}
JDK 9 provides an updateConfiguration method that will work around the broken behavior of the readConfiguration method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use stackable trait pattern with Akka actors?
I'm trying to implement a Pub/Sub trait to mix into other akka actors using a stackable trait.
Here is what I came up with:
trait PubSubActor extends Actor {
abstract override def receive =
super.receive orElse {
case Subscribe(topic) => /* ... */
case Publish(topic, msg) => /* ... */
}
}
class MyActor extends Actor with PubSubActor {
override def receive = {
case SomeMessage(a, b, c) => /* ... */
}
}
At which point, the compiler throws back an error:
error: overriding method receive in trait MyActor... method receive needs `abstract override' modifiers.
Can you explain to me why this isn't working? How can I fix it so it works?
Thanks!
UPDATE
The following works:
trait PubSubActor extends Actor {
abstract override def receive =
super.receive orElse {
case Subscribe(topic) => /* ... */
case Publish(topic, msg) => /* ... */
}
}
class MyActor extends Actor {
override def receive = {
case SomeMessage(a, b, c) => /* ... */
}
}
class MyActorImpl extends MyActor with PubSubActor
But why? Why can I get the behavior I want this way but not the other? Any reasons? I can't seem to figure out the underlying difference between these two samples that makes the difference.
A:
There's a simple and concise solution:
Define a Receiving trait that chains multiple receive functions using orElse :
trait Receiving {
var receivers: Receive = Actor.emptyBehavior
def receiver(next: Actor.Receive) { receivers = receivers orElse next }
def receive = receivers // Actor.receive definition
}
Using this in actors is easy:
trait PubSubActor extends Receiving {
receiver {
case Publish => /* I'm the first to handle messages */
}
}
class MyActor extends PubSubActor with Receiving {
receiver {
case SomeMessage => /* PubSubActor didn't handle, I receive the message */
}
}
First PubSubActor's receive will be called. If message wasn't handled it will be passed to MyActor's receive.
A:
You can certainly achieve what you are looking for using Akka's composable actor feature. This is described a bit in Extending Actors using PartialFunction chaining.
First, the infrastructure code (straight from the docs):
class PartialFunctionBuilder[A, B] {
import scala.collection.immutable.Vector
// Abbreviate to make code fit
type PF = PartialFunction[A, B]
private var pfsOption: Option[Vector[PF]] = Some(Vector.empty)
private def mapPfs[C](f: Vector[PF] => (Option[Vector[PF]], C)): C = {
pfsOption.fold(throw new IllegalStateException("Already built"))(f) match {
case (newPfsOption, result) => {
pfsOption = newPfsOption
result
}
}
}
def +=(pf: PF): Unit =
mapPfs { case pfs => (Some(pfs :+ pf), ()) }
def result(): PF =
mapPfs { case pfs => (None, pfs.foldLeft[PF](Map.empty) { _ orElse _ }) }
}
trait ComposableActor extends Actor {
protected lazy val receiveBuilder = new PartialFunctionBuilder[Any, Unit]
final def receive = receiveBuilder.result()
}
Then the behaviors you want to be able to compose into actors:
trait PubSubActor { self:ComposableActor =>
receiveBuilder += {
case Subscribe(topic) => /* ... */
case Publish(topic, msg) => /* ... */
}
}
trait MyActor { self:ComposableActor =>
receiveBuilder += {
case SomeMessage(a, b, c) => /* ... */
}
}
And lastly, an actual actor that uses these composable behaviors:
class MyActorImpl extends ComposableActor with PubSubActor with MyActor
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does h2o.splitFrame account for class proportion for multinomial classification?
Does h2o.splitFrame account for class proportion for multinomial classification? For example, if my original dataset has three classes with proportion of 20%, 70%, and 10%, when I create train, valid and test datasets, would they have similar class proportion?
Thank you for your input!
A:
No it does not.
It does the simplest possible random split, handling each row independently with a "coin flip" row-by-row.
The thinking is, since H2O-3 is intended to handle big data, there are enough samples to not worry about it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails polymorphic relationship - need to use both has_many and has_one
Here are the models/relationships from the Rails Guides example on polymorphism:
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
In my case a Product with many Pictures is fine, but I don't want an Employee to ever have more than one Picture. I want the Employee model to be:
class Employee < ActiveRecord::Base
has_one :picture, :as => :imageable
end
This would allow me to use @employee.picture rather than @employee.pictures.first (using @employee.pictures.first has just a bit of stink to it - isn't representative of the true intent of the relationship.)
Does rails support a has_one ____ :as => :imageable relationship?
A:
First, you must create a join table (something like picturings). Then you will have next models for pictures:
class Picture < ActiveRecord::Base
has_many :picturing, :dependent => :destroy
end
class Picturing < ActiveRecord::Base
belongs_to :picture
belongs_to :picturable, polymorphic: true
end
Product model:
class Product < ActiveRecord::Base
# Many pictures
has_many :picturing, as: :picturable
end
Employee model:
class Employee < ActiveRecord::Base
has_one :picturing, as: :picturable
has_one :picture, through: :picturing
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
uploading different types of files mostly pdfs
I would like to upload different types of files pressumably pdfs to a certain directory I am currently trying to get this one script working that I found on snipplr but it is not working as I assumed it would, here is my code.
Never mind I had an extra comma in my code
UPDATE: I added some more code in comments below, I want to also add the filename to a field in a datatbase, currently the script I have breaks the page nothing loads I am not sure why since it seems to work on other pages I have.
<?php
if( isset($_POST['submit']) )
{
$target_path = "../downloads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";
/*
$title = basename( $_FILES['uploadedfile']['name']);
$sql = sprintf("INSERT INTO forms (title)VALUES('%s')",
mysql_real_escape_string($title)
);
$results = mysql_query($sql)or die(mysql_error());
*/
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<input type="file">
<input type="submit" name="submit" value="submit" />
</form>
A:
Apart from the directory existing, file permissions, etc., you might want to give your input a name:
<input type="file" name="uploadedfile">
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What makes Drupal better/different from Joomla
I talked to a few friends who say that Drupal is amazing, and it is a way better than Joomla. What are the major differences/advantages?
A:
The general consensus is that programmers prefer Drupal whereas mere mortals prefer Joomla. Joomla is praised for having a simpler user interface. (I personally don't agree with that; I think Joomla's UI is pretty painful to use. But then again, I'm looking at it with a programmer's eye.) Drupal, on the other hand, is praised for its high level of extensibility, along with its large library of high-quality (more or less) plug-ins that add features ("modules" in Drupal lingo) and many of which are extensible themselves.
Start using Joomla today, and you'll probably end up with a decent but not quite perfect web site tonight. Start using Drupal today, and you'll be able to build exactly the web site you're wishing for - once you've put the time in.
If you're considering parlaying your skills into a paid job one day, you should definitely side with Drupal.
A:
The community around drupal - theres a module to do just about everything. Sometimes, theres more than one way to do something too.
If you want to change almost anything, from presentation (themes) to function (hooks), its possible. However, its not MVC and it does take a lot of getting used to.
With Views + CCK + Panels Module, you rarely need to touch code to create a wide variety of pages.
Finally, Drupal's User and Roles system is much more flexible.
A:
The API. Every form and pretty much every bit of functionality can be modified via a module that hooks into the API, without having touch core code. This makes upgrades much easier, as your customisations aren't overwritten.
The code it outputs by default is much nicer, as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Derivatives Applications Problem
My teacher dropped this problem in class but no one seemed to answer it correctly. Any help?
A man is walking from his front door to his car. The length of garden from his door to the road is 4 m. The car is parked 10 m up the road. Because of snow, he can only walk at 0.4 m/s through the garden, and 0.5 m/s on the road. What route should he take to minimize the time taken to get to his car?
Set it up like this: Let x be the from the end of the path to the point on the road that he aims for.
Then find expressions for each of the two parts of his journey, and use the corresponding speeds to determine the time taken for each part.
Find an expression for the total time and minimize it.
A:
How far have you got already?
Write the total time $T = t_{road} + t_{snow} = f(x)$. The time taken for the road segment is
$$t_{road} = \frac{Distance}{Speed} = \frac{10-x}{0.5} = 20 - 2x$$
What's the expression for $t_{snow}$? And hence what is $T = f(x)$?
Added: From below, the total time is $$T = f(x) = \frac{5}{2} \sqrt{x^2 + 16} - 2x + 20$$ Differentiating,
$$f'(x) = \frac{5}{2} \frac{x}{\sqrt{x^2 + 16}} - 2$$
which is equal to zero if $$5x = 4\sqrt{x^2 + 16}$$ Can you take it from here?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error trying to load data from Excel
I'm in SSIS and trying to populate a table in my database with results on a formatted Spreadsheet. I'm using the SQL command within the Excel source editor and bring through data
I can see that some values within the rates colunms are blank. The error im geeting is .
An OLE DB record is available. Source: "Microsoft SQL Server Native Client 11.0" Hresult: 0x80004005 Description: "Invalid character value for cast specification".
This there an connection?
A:
This here works for me, so you can try somethin similar:
All column datatypes is of nvarchar(255) except sc which is a float(but you can change this to nvarchar if you wish)
Try to get this working first. If you then get data loaded, you can always change datatypes as you go further or make a new dataflow where you handle your datatypes.
Excel Sheet:
Package start:
Excel source Editor
Excel Source Columns
Destination connection and create new table
Destination mappings
SQL Table Result
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Cut" the string on HTML
For my HTML, I use a smarty variable;
<div class="ty-blog__date">{$subpage.timestamp|date_format:"`$settings.Appearance.date_format`"}</div>
{$subpage.timestamp|date_format:"$settings.Appearance.date_format"} On compilation, the date appears as: Авг 17, 2016
Where: Авг - month, 17 - date, 2016 - year. However, it is a single string.
I want to slice this string into consecutive parts in order to display each part as a separate HTML element.
An example:
<span>month</span><span>date</span><span>year</span>
How can I do this?
A:
<span>{$subpage.timestamp|date_format:"%B"}</span><span>{$subpage.timestamp|date_format:"%e"}</span><span>{$subpage.timestamp|date_format:"%Y"}</span>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Environment variables are not passed from .htaccess to PHP
I am trying to pass an environment variable from .htaccess through to PHP. This works just fine on my local WAMP server, but on the server where my website is hosted, it fails without reason.
Here's my test configuration:
.htaccess:
SetEnv TEST_VARIABLE test_value
test.php:
<pre>
getenv('TEST_VARIABLE') = <?php print getenv('TEST_VARIABLE'); ?>
getenv('REDIRECT_TEST_VARIABLE') = <?php print getenv('REDIRECT_TEST_VARIABLE'); ?>
</pre>
On my local server, getting test.php correctly returns:
getenv('TEST_VARIABLE') = test_value
getenv('REDIRECT_TEST_VARIABLE') =
But on the production server, it returns:
getenv('TEST_VARIABLE') =
getenv('REDIRECT_TEST_VARIABLE') =
Things I've ruled out:
mod_env is not installed/enabled by the host. Can't be, because then SetEnv would not be recognized and I'd get a 500 while processing the .htaccess.
AllowOverrides in httpd.conf for this directory doesn't include FileInfo. Can't be, because then Apache would throw an error "SetEnv not allowed here" when encountering the SetEnv directive and I'd get a 500 again.
variables_order in php.ini doesn't include 'E'. This would explain the $_ENV superglobal being empty (which it is), but not why getenv() doesn't return values for these variables.
Entire environment is screwed up. Can't be, because getenv('PATH') and getenv('SERVER_NAME') still return valid values.
At this point I'm at a loss as to what configuration could be causing this.
A:
I don't think using setenv normally works in .htaccess. It's a shell script command (bash, C shell, etc.). If your server does support setenv, according to https://kb.mediatemple.net/questions/36/Using+Environment+Variables+in+PHP#gs you need to have the variable name start with HTTP_.
A:
If you are running your home server on a Mac or have suEXEC enabled, there are security measures in place to strip any non-http environment variables that are defined, therefore they won't appear in $_ENV['APPLICATION_ENV']. You CAN, however access these through a native PHP function to get the same thing.
$var = apache_getenv('APPLICATION_ENV');
That function will get any environment variable defined with SetEnv in your .htaccess file, or any environment variable that is set in php.ini, even if PHP removes these from the $_ENV variable.
You could then define the environment variable within PHP if you want, although not recommended.
$_ENV['APPLICATION_ENV'] = apache_getenv('APPLICATION_ENV');
Or the better solution: just define a global:
define('APPLICATION_ENV', apache_getenv('APPLICATION_ENV'));
Once you do that, it should work as desired.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Have MLE estimators for Generalized Pareto Distribution. Given a known value of $c$, how do I calculate $a$ and $b$ using the provided estimators?
I am doing research into the three parameter Generalized Pareto Distribution
$$
f(x|a,b,c) = \frac 1 b\left(1+a\left(\frac{x-c}{b}\right)\right)^{\big(-1-\frac 1 a\big)}
$$
for finding VaR and CVaR. $x$ is a vector of returns greater than or equal to $c$. The paper Parameter Estimation for 3-parameter gpd by the principle of maximum entropy by Singh and Guo (paper) provides MLE estimators in equations (45) and (46). Given a known value of $c$, how do I calculate $a$ and $b$ using the provided estimators?
A:
Later edit: I give what seems to be a better solution here.
Note that the paper uses a different parameterization from the form given in the question. As Yves noted in comments, it uses $-a$ in place of your $a$ (both are common parameterizations; the only difficulty may be when it is unclear which parameterization is being used). If you convert answers back to your parameterization you'll have to make the corresponding change.
The paper says:
The MLE estimators can be expressed as:
$\sum_{i=1}^n \frac{(x_i-c)/b}{1-a(x_i-c)/b}=\frac{n}{1-a}\qquad\qquad\qquad$ (45)
$\sum_{i=1}^n \ln[1-a(x_i-c)/b]=-na\qquad\,$ (46)
[...] Clearly the likelihood function is maximum with respect to $c$ when $c=x_1$.
In fact there's some minor issues with the exposition; at the point where they set the derivative of the log-likelihood to zero, they're no longer dealing with $a,b$ and $c$ but with the estimators, $\hat{a},\hat{b}$ and $\hat{c}$. So they should really have:
i. $\hat{c} = x_{(1)}$ (at least it didn't appear that the sample was ordered until at that point they suddenly declare $x_1$ to be smallest; better to be explicit)
ii. Given the ML estimate of $c$, the parameters $a$ and $b$ are then estimated by simultaneously solving these two equations:
$\sum_{i=1}^n \frac{(x_i-\hat{c})/\hat{b}}{1-\hat{a}(x_i-\hat{c})/b}=\frac{n}{1-\hat{a}}\qquad\qquad\qquad$ (45)
$\sum_{i=1}^n \ln[1-\hat{a}(x_i-\hat{c})/\hat{b}]=-n\hat{a}\qquad$ (46)
for $\hat{a}$ and $\hat{b}$.
The idea is that given $\hat{c}$, you find $\hat{a}$ and $\hat{b}$ that make equations (45) and (46) true.
If you were to solve this pair of nonlinear equations simultaneously, generally you'd need some iterative scheme set up* that you can update the estimates numerically until (45) and (46) are very close to true.
*(starting with some reasonable guesses, such as method of moments or quantile-based estimates or by assuming $a=0$ and using the resulting ML estimate from an exponential for $\hat{b}$)
It's certainly possible to do so... however, most people would back up a step; rather than taking the derivative and setting it equal to zero and looking for an iterative scheme to solve the equations for $\hat{a}$ and $\hat{b}$, we can simply employ optimization methods to minimize the negative of the log-likelihood function and take as our parameter estimates the values of the parameters that give that minimum. That's what's usually done for the generalized Pareto.
This would again start with some reasonable guesses for $\hat{a}$ and $\hat{b}$ and iterate to reduce $-\ell=-\log\mathcal{L}$ until some minimum was effectively reached. One benefit of doing so is that once you've found your minimum, it's easier to get second derivative estimates out and so get asymptotic standard errors for the estimates.
[In practice with ML, since the likelihood function might not always be unimodal, it's often a good idea to evaluate it over a grid of plausible values to identify whether there are multiple local minima in $-\ell$ or other issues that might be relevant.]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I run JUnit 4 to test Scala code from the command line?
If so, how? I haven't come across the proper incantation yet.
If not, what's the best approach to unit-testing Scala code from the command line? (I'm a troglodyte; I use IDEs when I have to, but I prefer to play around using Emacs and command-line tools.)
A:
Since compiled Scala is just Java bytecode (OK, with a lot more $ characters in class names), it would be exactly as for running JUnit 4 tests against Java code, i.e. from the command line by passing the test classes as arguments to org.junit.runner.JUnitCore. As JUnit 4 out of the box only has command line support, you don't even have to worry about suppressing GUI based test runners.
That said, the specific Scala test frameworks (ScalaTest, ScalaCheck) do provide a more idiomatic set approach to testing code written in this more functional language.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clearing specific rows using RODBC
I would like to use the RODBC package to partially overwrite a Microsoft Access table with a data frame. Rather than overwriting the entire table, I am looking for a way in which to remove only specific rows from that table -- and then to append my data frame to its end.
My method for appending the frame is pretty straightforward. I would use the following function:
sqlSave(ch, df, tablename = "accessTable", rownames = F, append = T)
The challenge is finding a function that will allow me to clear specific row numbers from the Access table ahead of time. The sqlDrop and sqlClear functions do not seem to get me there, since they will either delete or clear the entire table as a whole.
Any recommendation to achieve this task would be much appreciated!
A:
Indeed, consider using sqlQuery to subset your Access table of the rows you want to keep, then rbind with current dataframe and finally sqlSave, purposely overwriting original Access table with append = FALSE.
# IMPORT QUERY RESULTS INTO DATAFRAME
keeprows <- sqlQuery(ch, "SELECT * FROM [accesstable] WHERE timedata >= somevalue")
# CONCATENATE df to END
finaldata <- rbind(keeprows, df)
# OVERWRITE ORIGINAL ACCESS TABLE
sqlSave(ch, finaldata, tablename = "accessTable", rownames = FALSE, append = FALSE)
Of course you can also do the counter, deleting rows from table per specified logic and then appending (NOT overwriting) with sqlSave:
# ACTION QUERY TO RUN IN DATABASE
sqlQuery(ch, "DELETE FROM [accesstable] WHERE timedata <= somevalue")
# APPEND TO ACCESS TABLE
sqlSave(ch, df, tablename = "accessTable", rownames = FALSE, append = TRUE)
The key is finding the SQL logic that specifies the rows you intend to keep.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to authorize a Blazor WebAssembly SPA app using Identity Server
I am writing a demo Blazor WebAssembly SPA technical demo app, but I have some problems with authentication.
I'm going to use Identity Server to do the authorization but i can't find any libraries to support it.
All the tutorials I found guided to use Blazor Server or add an ASP.net Core hosted, but it's not really make sense for my demo app.
I am glad if anyone can help.
Thank you
A:
March 12th, 2020
To add OIDC to an existing Blazor WASM app using an existing OAuth identity provider read Secure an ASP.NET Core Blazor WebAssembly standalone app with the Authentication library.
The new Microsoft.AspNetCore.Components.WebAssembly.Authentication support automatic silent renew.
If you prefere to use a configuration file instead of hard coded values, you can setup the app like this
Visit theidserver.herokuapp.com/ for a full fonctional sample.
Upgrade your app to 3.2.0 Preview 2
Read Upgrade an existing project paragraph
Add package Microsoft.AspNetCore.Components.WebAssembly.Authentication
dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Authentication::3.2.0-preview2.20160.5
Add AuthenticationService.js to index.html
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<app>Loading...</app>
...
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Add an oidc.json file in application's wwwroot folder with this structure
{
"authority": "https://myidp.com", // Uri to your IDP server
"client_id": "myclientid", // Your client id
"redirect_uri": "https://localhost:44333/authentication/login-callback", // Uri to the application login callback
"post_logout_redirect_uri": "https://localhost:44333/authentication/logout-callback", // Uri to the application logout callback
"response_type": "code", // OAuth flow response type. For `authorization_code` flow the response type is 'code'. For `implicit` flow, the response type is 'id_token token'
"scope": "BlazorIdentityServer.ServerAPI openid profile" // list of scope your application wants
}
Configure Api authorization to read config from your oidc.json file
Update your Program.cs to be :
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
namespace BlazorIdentityServer.Client
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddBaseAddressHttpClient();
builder.Services.AddApiAuthorization(options => options.ProviderOptions.ConfigurationEndpoint = "oidc.json");
await builder.Build().RunAsync();
}
}
}
March 11th, 2020
3.2.0-preview2 provides a way to use Blazor Wasm with IdentityServer
Read
Secure an ASP.NET Core Blazor WebAssembly hosted app with Identity Server
ASP.NET Core Blazor WebAssembly additional security scenarios
March 9th, 2020
At the moment there are some blazor OIDC lib you can use but none are certified and implement all features.
HLSoft.BlazorWebAssembly.Authentication.OpenIdConnect
Authfix/Blazor-Oidc
sotsera/sotsera.blazor.oidc
MV10/BlazorOIDC
If you are curious, I write my own to support token silent renew but it's not finished yet and I stuck by this issue : [wasm] WasmHttpMessageHandler, Provide fetch options per message.
The issue is fixed in this not yet merged PR. So have to wait or implement my own WasmHttpMessageHandler.
A second approach is to wrap oidc.js using JS interop
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I prevent websites from disabling zoom?
I've noticed that more and more websites are disabling the ability to zoom on an ipad using Safari (or other mobile browsers, it seems).
Is there a setting to turn this ability off, or some other way to prevent this?
A:
I created a bookmark in Mobile Safari with this url
javascript:document.querySelector('meta%5Bname=viewport%5D').setAttribute('content','width=device-width,initial-scale=1.0,maximum-scale=10.0,user-scalable=1');
The easiest way to setup this bookmark is by:
Add a bookmark to any page
Edit the bookmark and set the url to the url I have above
Now anytime you are on page that you can't zoom then click the bookmark icon and select the bookmark you setup. Then you can pinch and zoom.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to remove all html characters in snowflake, dont want to include all html special characters in query (no hardcoding)
Want to remove below kind of characters from string..pl help
'
&
A:
You may try this one to remove any HTML special characters:
select REGEXP_REPLACE( 'abc&def³»ghi', '&[^&]+;', '!' );
Explanation:
REGEXP_REPLACE uses regular expression to search and replace. I search for "&[^&]+;" and replace it with "!" for demonstration. You can of course use '' to remove them. More info about the function:
https://docs.snowflake.com/en/sql-reference/functions/regexp_replace.html
About the regular expression string:
& is the & character of a HTML special character
[^&] means any character except &. Tthis prevents to REGEXP to replace all characters between the first '&' char and last ';'. It will stop when it see second '&'
+ means match 1 or more of preceding token (any character except &)
; is the last character of a HTML special character
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to show message to user when new tab is opened
The code below uses onbeforeunload to display a message before the user leaves the site.
$(window).on('beforeunload', function(){
// Was the <a> tag clicked?
if(isClicked)
{
// Reset isClicked
isClicked = false;
// Display the message
return 'You are leaving the site.';
}
});
// Define a clicked state variable with a default value;
isClicked = false;
$(window).load(function(){
// Get all tags with the specified className
var anchors = $('.leaveSite');
// Add the "onclick" listener to each one of them
anchors.each(function(index) {
$(this).click(function(){
isClicked = true;
});
});
});
I thought that onbeforeunload worked when new windows/tabs were opened.
How do I make the same happen when a user clicks on a <a class="leaveSite"> that opens a new window/tab?
A:
To display a message, should you write the onbeforeunload function like this
$(window).on('beforeunload', function(){
// Was the <a> tag clicked?
if(isClicked)
{
// Reset isClicked
isClicked = false;
// Display the message
alert 'You are leaving the site.';
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Uploading multiple images from Share Extension
I currently have a share extension set up that will upload an image selected from the Photo app to a server. This works fine using the code below.
int fileNum=10;
NSItemProvider *attachment = inputItem.attachments[0];
if ([attachment hasItemConformingToTypeIdentifier:(NSString*)kUTTypeImage])
{
[attachment loadItemForTypeIdentifier:(NSString*)kUTTypeImage options:nil completionHandler:^(id item,NSError *error)
{
if (item)
{
NSLog (@"image %@",item);
//upload image here
NSData *data=[NSData dataWithContentsOfURL:item];
activityRecord.activityType=@"Images";
AppRecord *appRecord=[[AppRecord alloc] init];
appRecord.fileName=[NSString stringWithFormat:@"activity_%@%i(%i).jpg",activityRecord.supplierID,activityRecord.activityID,fileNum];
appRecord.fileBytes=data;
[fileRecords addObject:appRecord];
activityRecord.activityFiles=fileRecords;
[[Settings getInstance] uploadActivityRecord:activityRecord withDelegate:self];
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}
}];
}
I had a previous problem where the loadItemForTypeIdentifier method wasn't being called, and it was resolved by calling completeRequestReturningItems within the completion block.
The problem I have now is that if I want to upload multiple files then I need to call loadItemForTypeIdentifier within a for loop (for each image) but how can I do that if the completeRequestReturningItems method will be called after the first image/item?
Many Thanks
Paul
A:
I ran into the same problem recently and was able to resolve it by adding a counter and counting down as the images successfully completed their block. Within the loadItemForTypeIdentifier completion block I then check to see if all items have been called before calling the completeRequestReturningItems within a dispatch_once block (just for safety's sake).
__block NSInteger imageCount;
static dispatch_once_t oncePredicate;
NSItemProvider *attachment = inputItem.attachments[0];
if ([attachment hasItemConformingToTypeIdentifier:(NSString*)kUTTypeImage])
{
[attachment loadItemForTypeIdentifier:(NSString*)kUTTypeImage options:nil completionHandler:^(NSData *item ,NSError *error)
{
if (item)
{
// do whatever you need to
imageCount --;
if(imageCount == 0){
dispatch_once(&oncePredicate, ^{
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
});
}
}
}];
}
I can't say I feel like this is an overly elegant solution however, so if someone knows of a more appropriate way of handling this common use case I'd love to hear about it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should / How do I include my school's GPA Scale in my CV / Application
I'm preparing my grad school applications (CV, letter of intent, etc) and in these I need to include my GPA. My school uses the 4.3 scale and I feel as though not including this information is misleading since my GPA will look better when compared to someone who is actually marked out of a 4.0.
But I have not seen this in any online example nor have I seen it in any of the outlines that schools give for their expected applications.
Should I include the GPA scale and if so how do I do this? Would 3.9 / 4.3 be reasonable?
Update / Solution
By the general look of the comments it is best to avoid ambiguity by stating the scale up front. So, I think the general consensus is GPA/grades should be reported along side their scales.
A:
I had the experience of sitting on a graduate admissions committee during my years in graduate school. (This was at a "top-10" school in my field, though not a "top-5".) In my experience, the raw GPA number was mainly used to make a "first cut" to weed out the fraction of applications that were almost certainly sub-par. (Things like super-low GRE scores were also used at this stage as well.) Once the applications got beyond this initial screening, committee members would read carefully through them; and at this point, the raw GPA was put aside in favor of the more detailed grade information on the transcript. Almost every transcript, especially those from US colleges or universities, had an explanation on the back about the system used to assign grades and calculate the GPA. There's enough variety in the systems used by different institutions (even within the US—foreign institutions had even more variety) that I always had to read through this information to contextualize what I saw on the transcript.
Which is to say: it's probably best to be honest about your GPA in the CV. But if you don't mention it specifically, the committee members will almost certainly still be able to figure out that your school had a 4.3 scale; and they almost certainly won't hold it against you for not mentioning it once they've figured it out.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle: Pivoting data into date ranges
I have data in the following format:
Date Quantity
-----------------------
1-Jan-2014 5
6-Jan-2014 15
10-Jan-2014 67
21-Jan-2014 42
What Oracle SQL can I use to produce the result:
StartDate EndDate Quantity
----------------------------------
1-Jan-2014 5-Jan-2014 5
6-Jan-2014 9-Jan-2014 15
10-Jan-2014 20-Jan-2014 67
21-Jan-2014 null 67
I'm thinking along the lines of using RANK OVER PARTITION with a join against a subquery for R = R+1 then doing StartDate-1 for the EndDate but can't seem to get this to work.
A:
You can use LEAD function to get the next row and subtract one from it.
select date as startdate,
lead(date) over (order by date) - 1 as enddate,
quantity
from table;
SQLFiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Solr CSVResponseWriter set csv.mv.escape to none
The CSV writing parameter for Solr csv.mv.escape defaults to \. I don't want the multi-valued fields to be escaped but can't find a way of doing it.
http://localhost:8983/solr/default/select?
q=*:*
&wt=csv
&csv.header=true
&csv.mv.escape=\
To remove the default escaping I'm wanting to be able to do something like this
http://localhost:8983/solr/default/select?
q=*:*
&wt=csv
&csv.header=true
&csv.mv.escape=none
How can this be achieved?
A:
As far as I can see in the source, the escape value is set when the CSVStrategy is created, and then only set to a different value if a different value is provided. So I don't think there's a way to make Solr skip the escape.
CSVStrategy mvStrategy = new CSVStrategy(strategy.getDelimiter(), CSVStrategy.ENCAPSULATOR_DISABLED,
CSVStrategy.COMMENTS_DISABLED, '\\', false, false, false, false, "\n");
My only, bad, hackish suggestion is, if this only for one time task, to use a value that doesn't occur in the text as the escape value, then replace that value after retrieving the CSV structure.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to exclude end of lines of textfiles via terminal?
Given a file ./wordslist.txt with <word> <number_of_apparitions> such as :
aš toto 39626
ir 35938
tai 33361
tu 28520
kad 26213
...
How to exclude the end-of-lines digits in order to collect in output.txt data such :
aš toto
ir
tai
tu
kad
...
Note :
Sed, find, cut or grep prefered. I cannot use something which keeps [a-z] things since my data can contain ascii letters, non-ascii letters, chinese characters, digits, etc.
A:
I suggest:
cut -d " " -f 1 wordslist.txt > output.txt
Or :
sed -E 's/ [0-9]+$//' wordslist.txt > output.txt.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.