text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Android Jetpack Compose. Using Stack layout
Does anyone know how to work with the composable Stack layout?
I understand, that it has to work similar to the RelativeLayout we all know. However, I am not getting the result I need. Instead of one view being drawn over the other, the first one completely covers the second (or the second does not get drawn at all).
I am trying to place a Text in the center of the Toolbar and a Button aligning the right side of the screen.
TopAppBar(
title = {
Stack(modifier = Modifier.None) {
Align(alignment = Alignment.Center) {
Text(
text = "MyApp",
style = (+themeTextStyle { h6 }).withOpacity(0.7f)
)
}
Align(alignment = Alignment.CenterRight) {
CircleImageButton(
resource = Res.drawable.ic_action_reload,
onCLick = onRefreshClick
)
}
}
},
color = Color.White
)
A:
With 1.0.0-alpha01 the Stack is a composable that positions its children relative to its edges.
Just an example with a rectangle of 300x300 in the Center, and 2 rectangles of 150x150 in the TopStart/BottomEnd angles using the Use StackScope.gravity
Stack {
Box(
backgroundColor = Color.Blue,
modifier = Modifier
.gravity(Alignment.Center)
.width(300.dp)
.height(300.dp))
Box(
backgroundColor = Color.Green,
modifier = Modifier
.gravity(Alignment.TopStart)
.width(150.dp)
.height(150.dp))
Box(
backgroundColor = Color.Red,
modifier = Modifier
.gravity(Alignment.BottomEnd)
.width(150.dp)
.height(150.dp))
}
About the TopAppBar you can use something like:
TopAppBar(
title = {
Text(text = "TopAppBar")
},
navigationIcon = {
IconButton(onClick = { }) {
Icon(Icons.Filled.Menu)
}
},
actions = {
// RowScope here, so these icons will be placed horizontally
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Favorite)
}
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Favorite)
}
}
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability distribution that includes the extinction probability of a branching process
Let $(p_k)_{k \in \mathbb{N}_0}$ be a probability mass function on $\mathbb{N}_0$ such that $p_0 > 0$. Furthermore, let $q$ be the extinction probability of the branching process $(Z_t)_{t \in \mathbb{N}_0}$ such that $Z_0 = 1$ and $P(Z_1 = k) = p_k, k \in \mathbb{N}_0.$
Prove that $p'_k := q^{k-1}p_k, k \in \mathbb{N}_0$ defines another probability distribution on $\mathbb{N}_0$.
This is just the first part of the excercise, and I already solved the other parts, but I just don't see why this is another probability distribution. Obviously, if $q = 1$, then $p'_k = p_k$, and thus it would be again a probability distribution. I think we can also exclude the case $q = 0$ since $p_0 > 0$, so we'd have to consider the case $q \in (0,1)$. But then, $lim_{k \rightarrow \infty} \ q^{k-1} = 0,$ so $\sum_{k=0}^{\infty} p'_k$ shouldn't equal $1$?
A:
Notice that
$$\sum_{k=0}^\infty p'_k = \sum_{k=0}^\infty q^{k-1} \mathbb{P}(Z_1 = k) = \mathbb{E}\left[q^{Z_1-1} \right] = \frac{G(q)}{q},$$
where $G(s) = \mathbb{E}[s^{Z_1}]$ is the PGF of $Z_1$. So your question is equivalent to showing that $q$ is a fixed point of $G$.
To prove this, you can consider $q_n \colon \!= \mathbb{P}(Z_n = 0)$ and show that:
$\lim_{n\to \infty}q_n = q$,
$q_n = G_n(0)$ where $G_n$ is the PGF of $Z_n$,
$G_n = G\circ \cdots \circ G$ ($n$ times).
It follows that $q_{n+1} = G_{n+1}(0) = G(G_n(0)) = G(q_n)$, then letting $n \to \infty$ proves that $q = G(q)$ by continuity of $G$. See here(Proposition 1.4 and Theorem 1.7) for more details. There might be a more direct approach but I don't see one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I rely on event execution order for base classes to avoid unnecessary virtual members?
Sometimes I want my derived class to react on some base class event and change the state before any other subscribes can be notified.
Do I need to duplicate protected virtual void HandleXBeforeOthers(...) for each event or can I rely on event execution order like this?
public class BaseClass
{
public event X EventA;
void RaiseA(...)
{
if (EventA != null) EventA(this, ...);
}
...
}
public class Derived : BaseClass
{
public Derived()
{
EventA += ...
}
}
The "protected virtual" approach would be:
public class BaseClass
{
public event X EventA;
void RaiseA(...)
{
HandleEventABeforeOthersCan(...);
if (EventA != null) EventA(this, ...);
}
protected virtual void HandleEventABeforeOthersCan(...)
{
...
}
...
}
public class Derived : BaseClass
{
protected override void HandleEventABeforeOthersCan(...)
{
...
}
}
A:
The answer depends on what kind of guarantee you want.
Constructors are executed after field initializers, and base class constructors are executed before derived class constructors. So, just as your own Derived class is adding a subscriber to the event in its constructor, so too could have a base class done so before yours.
To make matters worse, while it's definitely frowned upon, there is nothing to stop a base class constructor from passing this out to some other code, where it would get a chance to subscribe to the event before your Derived class does.
Finally, only the class implementing the event has complete control over the actual order of execution of the event handlers. Normally, it would just invoke the delegate instance representing the event, which would execute each handler in the order in which it was subscribed. But there is nothing stopping the implementer of an event from maintaining and using the event subscriptions in some other way.
E.g. it could implement the event explicitly and do something like eventField = value + eventField; in the add method (reversing subscription at the time of subscription) or, when raising the event, explicitly enumerating the invocation list for the event's delegate object and invoking the handlers in reverse order.
Of course, all of those scenarios should be very rare, especially that last one (which would be really weird). Code that deviated from the normal event implementation is and should be very uncommon. But can you be guaranteed the code isn't like that? Not without a promise from the person who wrote the code (and even there, people are fallible and may forget or accidentally break their promise).
So if you want something close to an iron-clad guarantee that your code will execute before any other, you need to make your own class sealed (so no one else can override the event-raising method), and do your processing before calling the base class implementation of the method by overriding the virtual method that actually raises the event.
Even there, you are relying on an implicit promise that the event won't be raised via any other mechanism. But that's about as good a guarantee as you're going to get.
| {
"pile_set_name": "StackExchange"
} |
Q:
IF ARRAY Formula
I am trying to find the SUM of a multipart IF statement using a separate spreadsheet:
=SUM(IF(AND([Doc.xlsx]Sheet1!$B$7:$B$348="APPL*", C15=[Doc.xlsx]Sheet1!$C$4:$BG$4),[Doc.xlsx]Sheet1!$I$7:$J$348))
NOTE: C15 = "A1"
I've tried breaking this formula down into these two separate parts:
=IF(C15=[Doc.xlsx]Sheet1!$A$4:$BG$4,TRUE)
and
=IF([Doc.xlsx]Sheet1!$B$7:$B$348 = "APPL*",TRUE)
However, these all fail out.
How can you find a single output using two criteria such as a column head and a row header?
Here is an image of what I'm working with. I need to sum all of the numbers met by the criteria from the grid by using the Column header and Row header.
A:
As per my comments one must have uniform output to input ranges; same number of rows as the row headers and same number of columns as the column headers.
This will then find where the two intersect and sum the corresponding intersections.
With Array formula on cannot use AND() or OR() functions. Use * or + respectively to accomplish the same thing.
So something like:
=SUM(IF((A2:A12=B15)*(B1:K1=B16),B2:K12))
Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode. If done correctly then Excel will put {} around the formula.
But one can do the same with SUMPRODUCT() without the need for Ctrl-Shift-Enter.
=SUMPRODUCT((A2:A12=B15)*(B1:K1=B16),B2:K12)
SUMPRODUCT does not need the Ctrl-Shift-Enter to enter but the normal entry method. It is still an array type formula.
Now to the second part IF/SUMPRODUCT do not use wild cards so you will need to use SEARCH() which will allow the use of wildcards.
=SUM(IF((ISNUMBER(SEARCH("APPL*",[Doc.xlsx]Sheet1!$B$7:$B$348)))*(C15=[Doc.xlsx]Sheet1!$C$4:$BG$4),[Doc.xlsx]Sheet1!$C$7:$BG$348))
The SUMPRODUCT:
=SUMPRODUCT((ISNUMBER(SEARCH("APPL*",[Doc.xlsx]Sheet1!$B$7:$B$348)))*(C15=[Doc.xlsx]Sheet1!$C$4:$BG$4),[Doc.xlsx]Sheet1!$C$7:$BG$348)
| {
"pile_set_name": "StackExchange"
} |
Q:
Slide back in UINavigationController like in Facebook for iOS
I saw the Facebook app update for iOS (6.1.1) and it has a rely nice slide back function. For now I have a UISlideGestureRecognizer that when is called a do a [self.navigationController popViewController:YES];. But how can I make it with a UIPanGestureRecognizer like in the Facebook app? Should I build my own UINavigationController?
I do not know more than this (yet):
backView1 = [[self.navCon.viewControllers objectAtIndex:self.navCon.viewControllers.count - 2] view];
backView2 = [[self.navCon.viewControllers objectAtIndex:self.navCon.viewControllers.count - 1] view];
Please help in advance!
UPDATE:
Screenshot:
A:
I've created a subclass of UINavigationController to do that. Here you go: https://github.com/MarcoSero/MSSlideNavigationController
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot find Microsoft.Http.dll
I am using Visual Studio 2010 Ultimate SP1 and have set my project's target framework to .NET Framework 4 but I do not see Microsoft.Http.dll as a reference I can add to my project.
Can someone point me to it's install location on the HDD or to a download somewhere? I have read that this is supposed to be part of the VS2010 but can't find it.
A:
I was able to find these DLLs by downloading the REST Starter Kit found here. I extracted the project and then plucked the DLLs out and saved to my computer. Unfortunately, I cannot say if these are up to date or not.
Never did find out though why these DLLs are not part of VS2010 Ultimate like MS says.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did NASA assess 3 separate and over 6 hours long EVAs are needed to replace a single failed Pump Module (S1 PM)?
I'm currently following US EVA-24 with Rick Mastracchio (EV1) and Mike Hopkins (EV2) tasked to replace a failed Pump Module (S1 PM), one of two external pump modules of the US section of the International Space Station (ISS). The schedule is also visible on this screen taken off live stream a few minutes before the EVA, scheduled to start on December 21, 2013 at 12:10 UTC (which it did):
Spacewalks overview for the US EVA-24 as broadcast on NASA TV (credit: NASA)
Currently, good half an hour into EVA 1, Mike and Rick are already 15 minutes ahead of schedule, and it seems they were even asked to perform a few additional checks (e.g. gloves check) that were not on the checklist as read to them by Koichi Wakata inside the station. So this naturally begs the question:
Why did NASA assess that they will require so much time (3 spacewalks each over 6 hours long) to replace a single Pump Module? Is this merely scheduling procedures with a good measure so astronauts don't have to hurry? Or do they always prepare flexed schedules like this for some other reason?
Update: A good hour into EVA, the two astronauts are roughly 25 minutes ahead of schedule. Here's another screen captured off the live stream, showing Pump Module design:
A:
NASA scheduled these three EVA based on previous experience. In 2010, the International Space Station (ISS) suffered similar problems that also required one of the two Pump Modules (PM) be replaced. Douglas Wheelock and Tracy Caldwell Dyson of Expedition 24 took three EVA to complete that, each lasting over 7 hours. To be more precise:
Expedition 24 EVA 2 on 7 August 2010 lasted 8 hours and 3 minutes (11:19 - 19:22 UTC)
Expedition 24 EVA 3 on 11 August 2010 lasted 7 hours and 26 minutes (12:27 - 19:53 UTC)
Expedition 24 EVA 4 on 16 August 2010 lasted 7 hours and 20 minutes (10:20 - 17:40 UTC)
Reason for such long EVAs was stuck Quick Disconnects (QD) on the PM that would not release.
The QD task was considered an easy one as the hardware was built for
frequent and fast mating/demating, but when Doug Wheelock tried to
remove the QDs from the S1 Pump Module, the QDs showed how hard it was
to get them detached. Teams battled with the hardware for hours before
calling it a day and heading back inside the airlock to re-group for a
second EVA that used modified procedures to get the stubborn QDs
demated.
And from the same source:
After the trouble encountered when performing a Pump Module R&R in
2010, this task is now known as a major undertaking and NASA expects
that two to four EVAs will be needed.
Source of both quotes: Spaceflight101: ISS Expedition 38 - US EVA-24 Updates
Problems during the first US EVA-15 egress by Doug Wheelock and Tracy Caldwell-Dyson are described in detail in this NASA's ISS On-Orbit Status 08/07/10 update.
So as Rick Mastracchio (EV1) and Mike Hopkins (EV2) have an added advantage of being able to study in detail the 2010 PM R&R EVAs, and they also had videos of those previous EVAs available, this schedule is computed based on previous NASA's experience with replacement of PM and they're even shortened a bit to account for better preparedness of the two Expedition 38 spacewalkers.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I add a variable in a code block in a Discord message
How can I write a code block (using the discord.js library) in a Discord message like this:
I am trying with the variable num, but it still gets recognized as text and doesn't get replaced with the actual value
.addField("```change ${num}```");
A:
The image you put is not an embed, it's just a message where someone has been mentioned, and so it's yellow.
To make a code block in Discord you have to type a normal message like this:
```
your code text here
```
Discord will then use markdown to display it as a code block. For further help on Discord markdown, please see this article.
If you're trying to use that num variable inside a string, you should start and end that string with backticks (`). Please note that if you want to put other backticks in the string you have to escape them with a backward slash (\).
Here's an example:
`\`\`\`\nYour text: ${num}\n\`\`\``
You can always append the variable with a plus + operator:
"```\nYour text: " + num + "\n```"
| {
"pile_set_name": "StackExchange"
} |
Q:
Subtracting two points, the math.
I would like to confirm the math of subtracting two points. I've looked online but all of the sources I have seen want to end up with a vector, I need to end with a point.
I am looking at this function in this link,
/*
Calculate the intersection of a ray and a sphere
The line segment is defined from p1 to p2
The sphere is of radius r and centered at sc
There are potentially two points of intersection given by
p = p1 + mu1 (p2 - p1)
p = p1 + mu2 (p2 - p1)
Return FALSE if the ray doesn't intersect the sphere.
*/
int RaySphere(XYZ p1,XYZ p2,XYZ sc,double r,double *mu1,double *mu2)
{
double a,b,c;
double bb4ac;
XYZ dp;
dp.x = p2.x - p1.x;
dp.y = p2.y - p1.y;
dp.z = p2.z - p1.z;
a = dp.x * dp.x + dp.y * dp.y + dp.z * dp.z;
b = 2 * (dp.x * (p1.x - sc.x) + dp.y * (p1.y - sc.y) + dp.z * (p1.z - sc.z));
c = sc.x * sc.x + sc.y * sc.y + sc.z * sc.z;
c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z;
c -= 2 * (sc.x * p1.x + sc.y * p1.y + sc.z * p1.z);
c -= r * r;
bb4ac = b * b - 4 * a * c;
if (ABS(a) < EPS || bb4ac < 0) {
*mu1 = 0;
*mu2 = 0;
return(FALSE);
}
*mu1 = (-b + sqrt(bb4ac)) / (2 * a);
*mu2 = (-b - sqrt(bb4ac)) / (2 * a);
return(TRUE);
}
specifically at the comments at the top of the function.
I have programmatically found my mu and now need to apply them to the points. So to make sure subtracting $(x_1, y_1)$ from $(x_2, y_2)$ would go
$$(x_1-x_2,\quad y_1-y_2)$$
Then applying mu to a point would just be
$$(x\cdot\mu,\quad y\cdot\mu)$$
A:
The "subtraction" of two points does produce a vector in the way you are describing. The idea is that this subtraction gives you the displacement vector between the two points. So if we have $P=(x_1,y_1)$ and $Q=(x_2,y_2)$ then the operation: $$P-Q = (x_1 - x_2, y_1- y_2)$$ is the vector that when you add it to the point $Q$ it will get you to the point $P$.
In this context the operations you are expecting hold true. That is the operation of vector addition and subtraction as well as scalar multiplication.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get sum of total counts with most recent hourly / daily / weekly / yearly interval in cakephp 3?
I've a table as following-
Now I need to make report of total number of counts in every hour, week, month and year. It may have sum 0 but should be include on the result. For example I need the result as follows-
$hourlyResult = array(
'00:01' => '5',
'00:02' => '9',
'00:03' => '50',
'00:04' => '5',
..............
..............
'00:55' => '95',
'00:56' => '0',
'00:57' => '20',
'00:58' => '33',
'00:59' => '5',
);
$weeklyResult = array(
'SAT' => '500',
'SUN' => '300'
.............
.............
'FRI' => '700'
);
How can I build the query in cakephp 3? I got the following link but can't go so far.
GROUP BY WEEK with SQL
What I've done-
$this->loadModel('Searches');
$searches = $this->Searches
->find('all')
->select(['created', 'count'])
->where('DATE(Searches.created) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)')
->group(WEEK(date))
->hydrate(false)
->toArray();
pr($searches);
A:
Here is how you can do it.
Sum By Year
$query = $this->Searches->find();
$query = $this->Searches
->find()
->select([
'total_count' => $query->func()->sum('count'),
'year' => $query->func()->year(['created' => 'literal'])
])
->group(['year'])
->hydrate(false);
Or
$query = $this->Searches
->find()
->select(['total_count' => 'SUM(count)', 'year' => 'YEAR(created)'])
->group(['year'])
->hydrate(false);
Sum By Day Of Week
$query = $this->Searches->find();
$query = $this->Searches
->find()
->select([
'total_count' => $query->func()->sum('count'),
'day_of_week' => $query->func()->dayOfWeek('created')
])
->group(['day_of_week'])
->hydrate(false);
Or
$query = $this->Searches
->find()
->select(['total_count' => 'SUM(count)', 'day_of_week' => 'DAYOFWEEK(created)'])
->group(['day_of_week'])
->hydrate(false);
The same way you can get total sum by hour or month.
Here you can read about CakePHP > Using SQL Functions and date and time functions in MySQL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery and IE8 animate opacity solution
I am trying to animate opacity with Jquery an it is working fine in every browser except, you guess it dreaded IE8! Problem: on animation I am seeing some ugly artifacts:(
I know that I can solve this by removing background and adding the same background color to my animated div and to my container div,but it is NOT an option in my case. Can somebody suggest solution to this?
My code:
$(document).ready(function() {
$(".img").animate({
opacity: 0
});
$(".glow").click(function() {
$(".img").animate({
opacity: 1
}, 5000);
});
});
A:
By adding IE filters to my CSS I have partially solved this issue (much better now and no black halo).
Lost whole day with this so I hope it will help someone more fortunate than me:)
.img{
display:block;
width:230px;
height:300px;
owerflow:hidden;
position:relative;
outline:none;
/*Notice (ugly) IE filter here and Source to my PNG image */
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=http://www.robertpeic.com/glow/glow.png) alpha(opacity=0);
background:none;
margin:0px auto;
padding-top:10px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Django ALLOWED_HOSTS env. variable formated right in settings.py
I'm facing the following issue. My .env files contains a line like:
export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format
But the variable called SERVERNAMES is used multiple times at multiple locations of my deployment so i can't declare this as compatible list of strings that settings.py can use imidiatly. beside I don't like to set multiple variables of .env for basically the same thing. So my question is how can I format my ALLOWED_HOSTS to be compatible with my settings.py. Something like this does not seem to work it seems:
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(',')
Thanks and kind regards
A:
Simply split your SERVERNAMES variable using space as separator instead of comma
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(' ')
| {
"pile_set_name": "StackExchange"
} |
Q:
Degree of $\mathbb{Q}(\zeta_n)$ over $\mathbb{Q}(\zeta_n+\zeta_{n}^{-1})$
Let $\zeta_n$ be a $n$-th primitive root of unity. How to prove that $[\mathbb{Q}(\zeta_n):\mathbb{Q}(\zeta_n+\zeta_{n}^{-1})]=2$ ?
A:
This is only true for $n>2$. Since $\zeta_n$ is a root of the polynomial
$$X^2 -(\zeta_n+\zeta_n^{-1})X + 1 = (X-\zeta_n)(X-\zeta_n^{-1})\in \mathbb Q(\zeta_n+\zeta_n^{-1})[X],
$$
it follows that $[\mathbb Q(\zeta_n): \mathbb Q(\zeta_n+\zeta_n^{-1})]\le 2$. Now, we have $\mathbb Q(\zeta_n+\zeta_n^{-1})\subseteq \mathbb R$ and $\zeta_n\notin \mathbb R$. Together it follows that $\mathbb Q(\zeta_n)\neq \mathbb Q(\zeta_n+\zeta_n^{-1})$ and hence the degree must be 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
UWP : Transitions not being clipped?
I have a problem in which I've got transitions such as EntranceThemeTransition on some controls which means they appear in a pleasant manner. However, these transitions seem to ignore the regular clip of the containing control, i.e. the ListView or ScrollViewer.
It means that for a split second my elements appear outside of the ListView as they are animating, but once the animation is over, the elements respect the clipping path and every works great.
Basically, I want the transition animations to respect the clip of the containing element, just as they do once the clip is over. It's not just ListView that has the problem, FlipView seems to also.
For a split second, I'll see the animation happen inside a FlipViewItem which isn't the current one! I don't see how that can't be a bug in FlipView.
Anyway, is there any way to get those transition animations to respect the clip? It's very ugly to see a split second of animation outside of the ListView etc.
A:
In case of ListView you can't influence the behavior too much, because that is how the transition works. You can however tweak it using EntranceThemeTransition's FromHorizontalOffset and FromVerticalOffset properties.
In case of FlipView it is not a bug per se. FlipView is basically a ScrollViewer with special behavior (only one item visible at a time), but the items preload even then (especially the immediate previous and immediate next). That means when the page loads, the FlipView appears and its children get loaded and you might see a glimpse of the transitions outside the item currently displayed. To circumvent this you have several options:
Transition only the first displayed item's children
Add EntranceThemeTransition only to the FlipView itself
Create a custom animation using Storyboard or implicit animations and start it manually when the flip view item changes
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing files in a directory without x-permission?
I am having a bit of trouble understanding what the execute permission means for directories. Do I understand it correctly that anything in a directory for which a user does not have x-rights is inaccessible even if the things inside the directory gives specific rights to the user?
Or will the user still have direct access to the things in the directory, but simply cannot list what is in the directory?
(What I am really trying to understand is how safe a directory is from access from other users if they do not have x-permission for it.)
A:
x bit for directory is also called as search bit. Actually, it enables you to access the inodes of the files listed inside the folder.
So if you want to access /home/user/foo/bar.txt then you must have search access on every ancestor of bar.txt
Quoting from the page
Because directories are not used in the same way as regular files, the
permissions work slightly (but only slightly) differently. An attempt
to list the files in a directory requires read permission for the
directory, but not on the files within. An attempt to add a file to a
directory, delete a file from a directory, or to rename a file, all
require write permission for the directory, but (perhaps surprisingly)
not for the files within. Execute permission doesn't apply to
directories (a directory can't also be a program). But that
permission bit is reused for directories for other purposes.
Execute permission is needed on a directory to be able to cd into it
(that is, to make some directory your current working directory).
Execute is needed on a directory to access the inode information of
the files within. You need this to search a directory to read the
inodes of the files within. For this reason the execute permission on
a directory is often called search permission instead.
Search permission is required in many common situations. Consider the
command cat /home/user/foo. This command clearly requires read
permission for the file foo. But unless you have search permission on
/, /home, and /home/user directories, cat can't locate the inode of
foo and thus can't read it! You need search permission on every
ancestor directory to access the inode of any file (or directory), and
you can't read a file unless you can get to its inode.
Please read more at file permission directory section.
Update: Leo raised a very good question. If we know the inode then can we access a file from a directory having it's x bit unset?
I believe, we should not be able to do so. I did not test it by c program but rather used some handy bash commands to confirm it.
user@user-desktop:~/test$ ls -lart
total 12
drwxr-xr-x 49 user user 4096 2011-11-30 22:37 ..
drwxr-xr-x 3 user user 4096 2011-11-30 22:37 .
drwxr-xr-x 2 user user 4096 2011-11-30 22:38 level1
user@user-desktop:~/test$ ls -lart level1/
total 12
drwxr-xr-x 3 user user 4096 2011-11-30 22:37 ..
drwxr-xr-x 2 user user 4096 2011-11-30 22:38 .
-rw-r--r-- 1 user user 8 2011-11-30 22:38 file1
user@user-desktop:~/test$ stat level1
File: `level1'
Size: 4096 Blocks: 8 IO Block: 4096 directory
Device: 808h/2056d Inode: 95494 Links: 2
Access: (0755/drwxr-xr-x) Uid: ( 1000/ user) Gid: ( 1000/ user)
Access: 2011-11-30 22:46:16.576702105 +0530
Modify: 2011-11-30 22:38:12.386701913 +0530
Change: 2011-11-30 22:46:08.876702102 +0530
user@user-desktop:~/test$ stat level1/file1
File: `level1/file1'
Size: 8 Blocks: 8 IO Block: 4096 regular file
Device: 808h/2056d Inode: 60775 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ user) Gid: ( 1000/ user)
Access: 2011-11-30 22:38:19.846701917 +0530
Modify: 2011-11-30 22:38:16.366701915 +0530
Change: 2011-11-30 22:38:16.366701915 +0530
user@user-desktop:~/test$ chmod -x level1
user@user-desktop:~/test$ stat level1/file1
stat: cannot stat `level1/file1': Permission denied
user@user-desktop:~/test$ ls -lart level1/
ls: cannot access level1/..: Permission denied
ls: cannot access level1/.: Permission denied
ls: cannot access level1/file1: Permission denied
total 0
-????????? ? ? ? ? ? file1
d????????? ? ? ? ? ? ..
d????????? ? ? ? ? ? .
user@user-desktop:~/test$ cat level1/file1
cat: level1/file1: Permission denied
user@user-desktop:~/test$ find . -inum 95494
./level1
user@user-desktop:~/test$ find . -inum 60775
user@user-desktop:~/test$ find ./level -inum 60775
find: `./level': No such file or directory
user@user-desktop:~/test$ find ./level1 -inum 60775
A:
Since you are asking for directories:
read means: read the contents, ie listing them with ls.
write means: write into the director. ie creating files or subdirectories.
execute means: enter into that directory.
read and execute permissions could be a bit tricky for directories.
For instance if you have read permissions but not execute, you can list the contents of the directory but can not drop into it. Also you can not list specific files or directories even though you know its names.
If you have execute permission but not read, you can drop into it but can not list the files directly. But, if you know names of the files or directories you can list them.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the difference between a normal/bare git repository?
This post says
in a bar Git repository, there is no working copy and the folder
(let's call it repo.git) contains the actual repository data
however after experiment,I found it's not true.
There's still .git directory in a bare repository.
So what's the difference at all?
A:
Reiterating...
A standard git repository is a working copy with the git data stored in the .git directory.
A bare git repository does not have a working copy, and is in essence only the .git directory (but is not named .git, it's named whatever you called it).
That post you found is exactly correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Closing credits for Brave: subtle nods towards Tangled and Frozen?
The Frozen Theory is fascinating, and very interesting, but this question is not about that.
Anyway, in the Brave end credits there seems to be quite a few six-pointed sun symbols shown in the background which bear a striking resemblance to the emblem of the Kingdom of Corona (the setting of Tangled). Also in the Brave credits are quite a few snowflakes, which seemed like maybe a reference to Frozen, which makes extensive use of snowflake visuals.
(Above images are from Tangled and Frozen; not from Brave.)
The appearance of the snowflakes could possibly be explained by the fact that Brave is set in Scotland, and the film was originally planned to contain a lot more snow than it eventually did. But it seems more than that to me. Does anybody know if they are deliberate nods towards the (at the time) most recently released, and next planned Disney princess films?
UPDATE: The plot thickens. I was just re-watching Tangled (my kids are obsessed with it at the moment, so I get to watch it several times a week) and noticed something in the end credits for that film too. The credits (which can be seen on Youtube) include various scenes from the film such as Flynn ascending Rapunzel's tower, "Wanted" posters, the man with the hook playing piano in the Snuggly Duckling, Flynn being chased by a bear, a map of the Kingdom... wait a minute... back up a bit... Flynn being chased by a bear?! There are no bears in Tangled, so what's with the bear in the credits?! A forward reference to Brave?
A:
I've found no references about this anywhere online, so I'm going to say no, they are not (deliberate) references. There are plenty of Easter Eggs that Disney, and Pixar in particular, are famous for. For an example of these, see this link.
However, no member of the production team for any of these films has made any comment about observations like yours, so it seems likely there are coincidence.
I would also add that because you want to believe this so much, you will find more evidence in support of it than there perhaps really is. That's not to suggest you're wrong or that these scenes in the movies can't be interpreted this way - just that, based on all the evidence available, it seems unlikely they are intentional nods to other Disney films.
| {
"pile_set_name": "StackExchange"
} |
Q:
unresolved external link2019 confusion
I'm trying to resolve an unresolved external (link2019 error). There are many posts on StackOverflow about this issue, but either I am not understanding the error or I am blind to it.
The error is caused by my generate_maze function (specifically by the rand_neighbor() call, right?) but my understanding is that these are all "resolved".
I truncated the code a little bit because it is quite verbose. I hope this was appropriate.
void generate_maze (Vector<int> &coords, Grid<bool> &included, Maze &m);
int main() {
Grid<bool> included = initialize_grid();
Vector <int> coords = rand_coords();
Vector <int> current_point = coords;
generate_maze(coords, included, m);
return 0;
}
void generate_maze (Vector<int> &coords, Grid<bool> &included, Maze &m) {
while (gridIsTrue == false) {
Vector<int> neighbor = rand_neighbor(coords, included);
pointT neighborpoint = {neighbor[0], neighbor[1]};
pointT current_point = {coords[0], coords[1]};
if (included.get(neighbor[0], neighbor[1]) == false) {m.setWall(current_point, neighborpoint, false); included.set(neighbor[0], neighbor[1], true); current_point = neighborpoint;}
}
}
Vector<int> rand_neighbor(Vector<int> &coords, Grid<bool> &included) {
while (1) {
int randomint;
randomint = randomInteger(1,4);
if (randomint == 1) {if (included.inBounds(coords[0], coords[1]+1)) {coords[1] = coords[1]+1; break;}}
if (randomint == 2) {if (included.inBounds(coords[0], coords[1]-1)){coords[1] = coords[1] -1; break;}}
if (randomint == 3) {if (included.inBounds(coords[0] -1, coords[1])){coords[0] = coords[0] -1; break;}}
if (randomint == 4) {if (included.inBounds(coords[0] +1, coords[1])){coords[0] = coords[0] + 1; break;}}
}
return coords;
Error:
error LNK2019: unresolved external symbol "class Vector<int> __cdecl rand_neighbor(class Vector<int>,class Grid<bool> &)" (?rand_neighbor@@YA?AV?$Vector@H@@V1@AAV?$Grid@_N@@@Z) referenced in function "void __cdecl generate_maze(class Vector<int> &,class Grid<bool> &,class Maze &)" (?generate_maze@@YAXAAV?$Vector@H@@AAV?$Grid@_N@@AAVMaze@@@Z)
1>C:\Users\com-user\Desktop\New folder\maze\assign3-maze-PC\Maze\Debug\Maze.exe : fatal error LNK1120: 1 unresolved externals
A:
Using the nice web c++ demangler here you can see that your undefined reference ?rand_neighbor@@YA?AV?$Vector@H@@V1@AAV?$Grid@_N@@@Z actually means class Vector __cdecl rand_neighbor(class Vector,class Grid &). The parameters are missing from your error message.
Now, do you see the difference between the declaration and the definition of your function?
class Vector __cdelc rand_neighbor(class Vector,class Grid &);
Vector<int> rand_neighbor(Vector<int> &coords, Grid<bool> &included) { /* ... */}
Let me normalize them a bit:
Vector<int> rand_neighbor(Vector<int>, Grid<bool> &);
Vector<int> rand_neighbor(Vector<int> &, Grid<bool> &) { /* ... */}
You forgot a reference (&) in the prototype of the function! Thus, your definition is of a different function.
A:
As the linker is telling you, the problem is with the rand_neighbor() function. You provided a declaration for it (if you didn't you would get a compiler error rather than a linker error), but you haven't provided a definition.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax form - image upload | access denied in ie
I'm creating a facebook application, and want to implement an ajax-like picture upload using the jquery form plugin. Everything is ok in chrome/ff but in iexplorer i get the folowing error:
Message: Access Denied
Line: 349
Char: 5
Code: 0
URI: http://application.my_domain.gr/apps/new_app/js/jquery.form.js
I am aware of the cross domain issues, but can't understand why this is happening, since all scripts i'm curently using are on the same domain.
Here's how i've done it working in firefox/chrome:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
<script>
$('#photoimg').bind('change', function() {
$("#preview").html('');
$("#preview").html('<img src="img/loader.gif" alt="Upload in progress"/>');
$("#imageform").ajaxForm({
target: '#preview',
success: function() {
$("#preview img").attr("id", "uploaded_img");
}
}).submit();
});
</script>
</body>
</html>
Any ideas why this is happening?
Thanks in advance.
A:
OK, it's a while since I posted the question, but here's what finally worked for me:
I just added my domain to "App Domains" in the app's Basic Settings (Basic Info section) and everething worked ok!
| {
"pile_set_name": "StackExchange"
} |
Q:
Perl reset variable
I'm learning Perl, and I made a script that will use defined variables in the beginning of my script to establish connection,pull records, modify them, then close connection.
the second part of my work involve repeating the same steps but for different server.
is there is a way to un-set whatever variables has been set before? and then use new defined settings and repeat the steps?
Thank you
A:
Define your variables in their own scope.
{
my $server = '123.123.123.123';
my $username = 'user1';
ping($server);
login($username);
}
{
my $server = '222.222.123.123';
my $username = 'user2';
ping($server);
login($username);
}
Even better, use a function definition:
sub doSomethingToServer
{
my ($server, $username) = @_;
ping($server);
login($username);
}
doSomethingToServer('123.123.123.123', 'user1');
doSomethingToServer('222.222.123.123', 'user2');
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple radio buttons ajax post
I'm new in web programming and I really need your help. I have a form with several radio buttons and I want to insert them into mysql through an ajax post. I can do it for a single button but for more than one I don't have idea how to do it.
This is a part of my html and jquery:
<html>
<script>
$(document).ready(function () {
$("#submit").click(function () {
var q1 = $('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.ajax({
type: "POST",
url: "ajax-check.php",
data: "q1=" + q1,
success: function () {
$("#msg").addClass('bg');
$("#msg").html("value Entered");
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="msg"></div>
<form method="post" action="">
<div class="Clear">
question1:bla bla bla
<input class="star required" type="radio" name="q1" value="1" />
<input class="star" type="radio" name="q1" value="2" />
<input class="star" type="radio" name="q1" value="3" />
<input class="star" type="radio" name="q1" value="4" />
<input class="star" type="radio" name="q1" value="5" />
</div>
<br />
<div class="Clear">
question2:bla bla bla
<input class="star required" type="radio" name="q2" value="1" />
<input class="star" type="radio" name="q2" value="2" />
<input class="star" type="radio" name="q2" value="3" />
<input class="star" type="radio" name="q2" value="4" />
<input class="star" type="radio" name="q2" value="5" />
</div>
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
And here is how I insert the button in mysql:
<?php
$query = mysql_connect("localhost", "root", "");
mysql_select_db('db', $query);
if (isset($_POST['q1'])) {
$choice1 = $_POST['q1'];
$choice2 = $_POST['q2'];
mysql_query("INSERT INTO tb VALUES('','$choice1')");
}
?>
I've tried to make a var for each button but dosen't worked.
How could I post all values in php and what should I change into my ajax and php?
Thanks!
This is how I did the .php
<?php
$query=mysql_connect("localhost","root","");
mysql_select_db('cosmote',$query);
$q = array();
for ($i = 1; $i <= 2; $i++) {
$q[$i] = isset($_POST['q'+$i]) ? mysql_real_escape_string($_POST['q'+$i]) : 0;
}
mysql_query("INSERT INTO tabel (q1,q2) VALUES ('$q[1]','$q[2]')");
?>
A:
OK, here is how to do it. First, add an id to the form:
<form id="myform" method="post" action="">
This will make it easier to access via jQuery. Then, pass the serialized form as the POST data to your PHP script:
$(document).ready(function () {
$("#submit").click(function () {
if ($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.ajax({
type: "POST",
url: "ajax-check.php",
data: $("#myform").serialize(),
success: function () {
$("#msg").addClass('bg');
$("#msg").html("value Entered");
}
});
}
return false;
});
});
After that, you can get the radio button values from the $_POST array in your PHP script:
$_POST['q1'] // value of q1, can be 1-5
$_POST['q2'] // value of q1, can be 1-5
EDIT: The problem with your PHP code is that you used + instead of . for concatenating strings. Write this instead:
$q[$i] = isset($_POST['q'.$i]) ? mysql_real_escape_string($_POST['q'.$i]) : 0;
After this, I'm pretty sure it will work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Shared bias voltage for quad op-amp
I'm pretty inexperienced in EE, but I'm adapting the circuit given in this question to amplify microphone inputs to drive an ADC.
I am going to be driving 4 ADC channels (on a Beaglebone Black) from 4 microphones, so I'm planning to use a quad op-amp.
The upper left of the circuit is a voltage divider providing bias voltage, with a 1MΩ resistor R3 isolating it.
My naive question is this: How much of the bias voltage circuit do I have to replicate per-channel? Can I drive all four channels from the node at the right of a single copy of R3?
A:
The input signal is present on the node at the right of R3, so R3 must be duplicated for each channel (otherwise you would be joining all the inputs together!). R1, R2 and C2 can be common to all channels.
There are two possible issues with using a common voltage divider - bias current, and crosstalk.
OP295 op-amps have a maximum bias current of 20nA each, so in the worst case you could have 80nA flowing in or out of the voltage divider. The DC impedance at this point is 50k (100k in parallel with 100k) so the maximum voltage change that might be caused by bias currents is 50k*80nA = 4mV, which is probably not significant in your application.
Without C2, signals could leak from one channel to another through R3 (greatly attenuated perhaps, but still might be audible). However C2 should shunt virtually all of this crosstalk to ground.
The only thing I would be concerned about is the 1.8V supply voltage. The OP295 is only rated down to 3V.
A:
You can use the same divider for all channels but you need to replicate R3 for each channel.
In other words, there can be a single version of R1, R2, and C2, but there should be an \$R3_A\$, \$R3_B\$, \$R3_C\$, \$R3_D\$, where they all connect to the same node on the left, but each connects to the appropriate input on the right.
| {
"pile_set_name": "StackExchange"
} |
Q:
isPrototypeOf() usage when dealing with inheritance in JavaScript
//I have this base Rectangle constructor function
function Rectangle (length, width){
this.length = length;
this.width = width;
}
Rectangle.prototype.getArea = function (){
return this.length * this.width;
};
//Creating Square constructor function that will inherit from Rectangle...
function Square(size){
this.length = size;
this.width = size;
}
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
//creating rectangle and square instances
var rect = new Rectangle(5, 10);
var square = new Square(6);
console.log(rect.getArea()); //50
console.log(square.getArea()); //36
console.log(Rectangle.prototype.isPrototypeOf(Square.prototype)); //true
console.log(Rectangle.prototype.isPrototypeOf(rect)); //true
console.log(Square.prototype.isPrototypeOf(square)); //true
my question is when i do the below console.log(), I expected it to print false. However, I got true.
console.log(Rectangle.prototype.isPrototypeOf(square)); //true
1) Does this mean isPrototypeOf goes to multiple levels?
2) if isPrototypeOf goes multiple levels, what is the point of using isPrototypeOf instead of using instanceof?
I've read this Why do we need the isPrototypeOf at all? but didn't understand how it applies in my use-case.
A:
isPrototypeOf checks if an object is within another object's prototype chain so yes it does go multiple levels
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf
They can be used for the same purpose. You can do square instanceof Square or Square.prototype.isPrototypeOf(square) but as you can see, instanceof has a specific purpose to match objects with their constructors where as isPrototypeOf can be used more broadly to check if any object is within the prototype chain of another.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
| {
"pile_set_name": "StackExchange"
} |
Q:
Tabs became blue on all visual studio themes
I have multiple visual studio color themes and I don't know why, but window tabs became blue in all themes. It happened after installing web essentials 2017 and visual studio productivity power tools extensions, I disabled both of them but changed design still remains, and what can I do to get my theme back without uninstall/reinstall visual studio. Here is the image to specify my problem
All tabs must be transparent and red when it is chosen, but they are always blue as it is in the picture above, only color themes tab gains themes design properly.
A:
After looking for the problem on Stackoverflow I found this:
Visual Studio tab header color in the IDE
They had the same problem and solved it. Have a look at it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving tripartite graph is always planar
Consider the complete tripartite graph $K_{a,b,c}$ on $a+b+c$
vertices. Provide an embedding to show that $K_{1,1,n}$ is always
planar (for $n\geq 1$). How many faces will this graph have?
I am really not sure how to approach either part. I think I should use euler's formula for the second part, which gives $v + f - e = 2$. Here, we'd have $v = n + 2$ and so we obtain $e = n + f$. Not so sure if I can get a better value.
I will appreciate your help in solving this problem
A:
For the embedding, consider placing one vertex at $(-1,0)$, one at $(1,0)$, and the other $n$ along the positive $y$ axis.
You have the correct $v$, so if you compute $e=1\cdot 1+1\cdot n +1\cdot n$, you can use Euler’s formula to deduce $f$. Or just count $f$ directly from your embedding, remembering to include the unbounded outer face.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problema com SQLite.Net.Interop
Estou tentando usar o namespace SQLite.Net.Interop para usar a classe ISQLitePlatform mas o package "SQLite.Net PCL" está como descontinuado.
Gostaria de saber se tem alguma alternativa para resolver esse problema.
Meu projeto está em Xamarin.Forms e preciso saber qual plataforma para poder obter o caminho certo de armazenamento do aquivo de banco de dados.
A:
Tive o mesmo problema um tempo atrás, consegui resolver utilizando sqlite-net-pcl
A atualização foi relativamente tranquila.
Pa obter o caminho eu utilizo:
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, _fileName);
var connection = new SQLiteConnection(path);
return connection;
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference in Admiral Pike's Rank insignia and Capt Kirk's in Star Trek Into Darkness
If you look at Admiral Pike's rank insignia in Star Trek Into Darkness, and then look at Captain Kirk's insignia, they look pretty much the same. I am not able to really tell the difference. Both of them have 4 pins of some sort on their shoulder boards. The only possibility I can come up with is the spacing of them. Admiral Marcus has 5 so it's easy to see the difference with his, and Spock has 3.
A:
The rank seems to be indicated not only by the pips on the shoulder board. It's a combination of that and their tunic.
The higher ranked Admirals (e.g. Pike and Marcus) have a white pillar on the front of the uniforms.
The lower ranked Captains/Commanders (e.g. Spock and Kirk) just have solid gray tunics.
So Admirals get 4-5 pips on the shoulder boards, plus white on the tunic. Captains and Commanders get 3-4 pips on the shoulder boards, with no white on the tunic.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you enable SSL for PHP cURL on Linux?
That's all there is to my question: how do you enable SSL for PHP cURL on Linux (specifically Ubuntu)? I'm not finding the answer by Googling it.
A:
apt-get install php5-curl does the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
Editing a tablerow with MVC and AngularJS and Entity Framework
I'm trying to create a function that enables you to edit registered users. I'm trying to edit FirstName, LastName and Email.
In this method I get the stuff that is written into the input fields, but Id is null so naturally editedUser is always null aswell. How can I get the users Id into the method so editedUser get's set to the user being edited?
[HttpPost]
public User EditUser([FromBody]EditUserModel model)
{
var editedUser = db.Users.FirstOrDefault(u => u.UserID == model.Id);
editedUser.FirstName = model.FirstName;
editedUser.LastName = model.LastName;
editedUser.Email = model.Email;
db.SaveChanges();
return editedUser;
What my js function looks like:
service:
editUser: function (user) {
return $http.post('/api/userspa', user)
controller:
$scope.editUser = function () {
var user = $scope.selectedUser;
UserService.editUser(user).success(function (data) {
console.log('Updated', data)
})
From the developer console: "
You clicked on: Object {UserID: 58, FirstName: "test1", LastName: "testsson", Email: "[email protected]", RegistrationDate: "2015-01-14T15:48:04.777"}"
EDIT: added js controller.
angular.module('myApp')
.controller('userCtrl', ['$scope', '$http', 'UserService', function ($scope, $http, UserService) {
UserService.getUsers()
.success(function (data) {
$scope.users = data;
})
.error(function () {
$scope.error = "Couldnt load data or there was none.";
}
)
$scope.selectUser = function (user) {
UserService.getUser(user.UserID).success(function (data) {
console.log("user ", data);
$scope.selectedUser = user;
})
}
$scope.editUser = function () {
var user = $scope.selectedUser;
UserService.editUser(user).success(function (data) {
console.log('Updated', data)
}).
error(function () {
$scope.error = console.log('Something went wrong')
});
}
A:
According to what we talked about in the comments, the fix was to send the ID from the client as well, that way you'll have it in the model and the null problem is fixed.
| {
"pile_set_name": "StackExchange"
} |
Q:
DevExpress GridView throwing exception when asigning to FocusedRowHandle
I'm using DevExpress.XtraGrid GridView for WinForms, and I don't know why the code bellow is throwing this exception:
An exception of type 'DevExpress.Utils.HideException' occurred in
DevExpress.XtraEditors.v13.1.dll but was not handled in user code
Stack Trace:
at DevExpress.XtraEditors.Container.ContainerHelper.OnInvalidValueException(IWin32Window owner, Exception sourceException, Object fValue)
at DevExpress.XtraGrid.Views.Base.ColumnView.SetRowCellValueCore(Int32 rowHandle, GridColumn column, Object _value, Boolean fromEditor)
at DevExpress.XtraGrid.Views.Grid.GridView.SetRowCellValueCore(Int32 rowHandle, GridColumn column, Object _value, Boolean fromEditor)
at DevExpress.XtraGrid.Views.Grid.GridView.PostEditor(Boolean causeValidation)
at DevExpress.XtraGrid.Views.Base.BaseView.CloseEditor(Boolean causeValidation)
at DevExpress.XtraGrid.Views.Base.ColumnView.CheckCanLeaveRow(Int32 currentRowHandle, Boolean raiseUpdateCurrentRow)
at DevExpress.XtraGrid.Views.Grid.GridView.DoChangeFocusedRow(Int32 currentRowHandle, Int32 newRowHandle, Boolean raiseUpdateCurrentRow)
at DevExpress.XtraGrid.Views.Base.ColumnView.DoChangeFocusedRowInternal(Int32 newRowHandle, Boolean updateCurrentRow)
at DevExpress.XtraGrid.Views.Base.ColumnView.set_FocusedRowHandle(Int32 value)
at xyzForm.gridView_MouseDown(Object sender, MouseEventArgs e) in c:...xyzForm.cs:line 1218
at DevExpress.XtraGrid.Views.Base.BaseView.RaiseMouseDown(MouseEventArgs e)
at DevExpress.XtraGrid.Views.Base.Handler.BaseViewHandler.OnMouseDown(MouseEventArgs e)
at DevExpress.XtraGrid.Views.Grid.Handler.GridHandler.OnMouseDown(MouseEventArgs ev)
at DevExpress.Utils.Controls.BaseHandler.ProcessEvent(EventType etype, Object args)
at DevExpress.XtraGrid.Views.Base.Handler.BaseViewHandler.ProcessEvent(EventType etype, Object args)
at DevExpress.XtraGrid.GridControl.OnMouseDown(MouseEventArgs ev)
Code (simplified):
private void gridView_MouseDown(object sender, MouseEventArgs e)
{
GridHitInfo info = gridView.CalcHitInfo(e.Location);
if (info.Column == null) return;
gridView.FocusedRowHandle = info.RowHandle; // this line throws
gridView.FocusedColumn = info.Column;
}
Here gridView.FocusedRowHandle is an int (currently with value 4), and info.RowHandle is an int also (with value 5). The GridView has 20 rows.
A:
As far as I know, GridControl throws this exception when you are trying to change a focused row while editor validation is not complete, because GridControl does not allow any actions until a correct value is entered in the validating editor. And it is not needed to do something with this exception in user code because this exception should be processed by GridControl itself and not affect your application.
I believe you should contact the DevExpress Support team directly to clarify the situation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did the Buddha ever talk about his family?
When Siddhārtha Gautama left his home to become an ascetic, he left a wife, son, father and step mother. His achievement of enlightenment and subsequent teachings of the 4 Noble Truths and 8 Fold Noble Path has brought obvious benefit to the world for the potential of the cessation of suffering. But what is known about the suffering of the Buddha's personal family due to his leaving? As the Buddha, did he ever speak of this matter?
A:
The Buddha praised princess Yashodara's virtue by dispensing the Channakinnara Jataka when he visited her at Kapilavatthu. Yashodara has never been a wife to another man since the life when Bodhisatva received the confirmation from Deepankara Buddha to become a Buddha in the future. The Bodhisatva was always her husband.
So the Bodhisatva and his family have spent plenty of time together as family in many a previous life. If that didn't take away their suffering, what's the point of doing more of the same?
Lets take an analogy. If your family is suffering from a mortal illness and if you alone have the capability to go find the cure, wouldn't you leave them behind to get the cure instead of lingering there to give them false comfort?
A:
Are you familiar with the Vessantara-jātaka? As the last tale in the Jataka series, it is basically the story of the Buddha’s incarnation immediately preceding his life as Shakyamuni (so you could say it’s rather significant!) Be that as it may, what happens to the Buddha-figure's immediate family is rather shocking.
The Vessantara-jātaka is supposed to illustrate the virtue of dāna, or generosity. The main character is a prince who goes into the forest (in effect becomes a renunciant) in order to save his father’s kingdom. His wife and two children go with him. At one point an old Brahmin whose wife needs a personal slave comes to Vessantara and asks him to give up his children, and he does. Later he also gives away his wife, but luckily it is the god Sakka who receives her. Later everything is reversed, Vessantara becomes king and riches rain down on his palace from the sky, so he is able to practice the dana virtue in an unlimited way.
This Jataka has a prominent place in Thai Buddhism – everyone knows the story, it was used for teaching and is often recited at temples as an exercise in merit-making. Charles Keyes wrote that it was historically one of three core texts in Thai popular Buddhist practice, along with the Traiphum, a work of cosmology, and the story of Phra Malai, which contains a lesson about the future Buddha Maitreya. (By the way, neither of the latter texts appears in the Tripitaka at all.)
Many Thais are disturbed about the seemingly anti-family message of the Vessantara-jātaka. (Other, less well-known jatakas can be disturbing too. There is one where a male hermit lets his female companion, also a renunciant, starve to death – she is just too weak to follow the path.)
It’s all about ridding oneself of attachments, of course. One of the most difficult things about becoming a monk must be to do this, although in practice the severing of ties is not absolute – family members may continue to feed the monk by donating food on his morning rounds, for instance. The Vessantara-jātaka has a message for both laypeople (how virtuous it is to give) and for monks (a model for renouncing worldly ties.) That may account for its popularity - who knows really?
Here’s a good summary of the Vessantara story – the full version is very long.
The tale of Prince Vessantara
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript Access Property From Object
I want to set value of "text" property to "value" property.
Example.html:
<script>
var obj = {
text: "Hello",
value: this.text
/*
value: function() {
return this.text;
}
*/
};
console.log(obj.text); // Output: Hello
console.log(obj.value); // Output: undefined
// console.log(obj.value()); // Output: Hello
</script>
Why?
A:
bcoz this refers to global object in your code. this is available inside functions otherwise it will refer to the global object (current execution context)
var obj = {
text: "Hello",
value: this
};
console.log(obj.text); // Hello
console.log(obj.value); // window
but in this case
var obj = {
text: "Hello",
value: function() {
return this.text;
}
};
console.log(obj.text); // Hello
console.log(obj.value()); //Hello
now this in value() refers to your object
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating Thumbnails in Build Phase of iPhone App Xcode project?
I have a group of png files in my bundle; but I also want smaller versions of them to be used at my app as well. Right now I am just resizing them all manually and putting them in the bundle as well: so i might have Graphic_1.png and Graphic_1-thumbnail.png.
Instead, is there anyway to do something like: at build time, take all my png assets and create 1/4 scale versions of them, and save them into the bundle as well, with the -thumbnail in the filename as above? Thanks!
A:
You can create a bash script for a custom build phase of your project. (Haven't tried to see if automator would work) This would require you to have something like Image Magick installed.
Right click on your target and click "Add > New Build Phase > New Run Script Build Phase"
Set the shell to /bin/bash. For the script:
FILES="*.png"
for f in "$FILES"
do
`convert $f -resize 25% thumb-$f`
done
Any other command line image processing tool would work in place of Image Magick. You likely need to adjust the FILES variable to the real location of your images.
| {
"pile_set_name": "StackExchange"
} |
Q:
I can't use where clause in stored procedure shows error whenever I put where clause
Can you tell me what wrong syntax I am having?
I can't use where clause in stored procedure shows error whenever I put where clause.
A:
Like the Abra says, your syntax is not in the correct order.
The logical processing order of the SELECT statement is,
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
However, even though the preceding sequence is usually true, there are uncommon cases where the sequence may differ.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use a transaction log to restore to a date before my last full backup was made?
I have a massive transaction log backup, and I have a full database backup for the past few days. I can use the transaction log backup to restore forward if I restore an earlier date from the full backup, but I'm wondering if it's possible to actually restore before the date I choose to backup from the full date.
To be more specific, let's assume the transaction log contains 12/01 -> 12/12 (today), and the oldest full backup is 12/07, and I want to restore to a point at 12/02.. Is this possible?
A:
It seems like it should be (technologically). But the product does not offer that choice.
Maybe a 3rd party product can help. There are some who can read and interpret logs. They can restore data from logs. Not sure if they need a base full backup, though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an easier way to search for an pattern in a list of strings in python?
I have a list of string and need a better wayt to search for patterns in that list. An exemple of list:
['red','green','red','red','red','red','green','red','red','green','green','red','green','green','red','red','green','green','green','green','green','green','green','red','red','red','red','red','red','green','red','red','red','red','red','red','red','green','green','red','red','green','red','green','green','green','green','green','red','red','green','green','green','red','green','red','green','red','red','green','green','red','green','green','red','red','green','green','red','red','green','green','green','green','red','red','red','red','red','green','green','green','green','red','green','red','green','red','green','red','red','green','red','green','red','green','red','red','red','red','green','red','red','red','green','green','green','red','red','green','green','red','green','red','green','red','green','green','green']
and patterns:
BLUE PATTERN:
['red','green','green','green']
['green','red','red','red']
PINK PATTERN:
['red','green','green','red']
['green','red','red','green']
The method needs to scan my list for patterns and generate another list with the names of the patterns in order that the patterns appeared for exemple:
['blue','pink','blue','blue',..]
That is what i have:
catalogacao = []
if len(self._items) < 4:
return
for i, _ in enumerate(self._items):
if i + 4 > len(self._items):
break
if self._items[i] == "red" and self._items[i+1] == "green" and self._items[i+2] == "green" and self._items[i+3] == "green":
catalogacao.append("blue")
if self._items[i] == "green" and self._items[i+1] == "red" and self._items[i+2] == "red" and self._items[i+3] == "red":
catalogacao.append("blue")
if self._items[i] == "red" and self._items[i+1] == "green" and self._items[i+2] == "green" and self._items[i+3] == "red":
catalogacao.append("pink")
if self._items[i] == "green" and self._items[i+1] == "red" and self._items[i+2] == "red" and self._items[i+3] == "green":
catalogacao.append("pink")
A:
You can iterate through your items, and for every sublist of 4 elements, check if the sublist equals a blue or a pink pattern
items = ['red','green','red','red','red','red','green','red','red','green','green','red','green','green','red','red','green','green','green','green','green','green','green','red','red','red','red','red','red','green','red','red','red','red','red','red','red','green','green','red','red','green','red','green','green','green','green','green','red','red','green','green','green','red','green','red','green','red','red','green','green','red','green','green','red','red','green','green','red','red','green','green','green','green','red','red','red','red','red','green','green','green','green','red','green','red','green','red','green','red','red','green','red','green','red','green','red','red','red','red','green','red','red','red','green','green','green','red','red','green','green','red','green','red','green','red','green','green','green']
blue_patterns = [['red','green','green','green'], ['green','red','red','red']]
pink_patterns = [['red','green','green','red'], ['green','red','red','green']]
catalogacao = []
#Iterate over the list
for idx in range(len(items)):
#Check if the 4 element sublist match blue or pink pattern
if any(item == items[idx:idx+4] for item in blue_patterns):
catalogacao.append("blue")
elif any(item == items[idx:idx+4] for item in pink_patterns):
catalogacao.append('pink')
print(catalogacao)
The output will be
['blue', 'pink', 'pink', 'pink', 'pink', 'blue', 'blue', 'blue', 'pink',
'pink', 'blue', 'pink', 'blue', 'pink', 'pink', 'pink', 'pink', 'pink',
'pink', 'blue', 'blue', 'blue', 'pink', 'blue', 'blue', 'blue', 'pink',
'pink', 'blue']
| {
"pile_set_name": "StackExchange"
} |
Q:
× react TypeError: Cannot read property 'then' of undefined
I think I just need another pair of eyes on this, because I can't get what I'm missing here.
in server,the code is:
function getByCategory (token, category) { return new Promise((res)
=> {
let posts = getData(token)
let keys = Object.keys(posts)
let filtered_keys = keys.filter(key => posts[key].category === category &&
!posts[key].deleted)
res(filtered_keys.map(key => posts[key])) }) }
in postAPI,the code is:
export const getByCategory=(category)=>{
fetch(`${api}/${category}/posts`,{headers})
.then(res=>res.json())
.then(data=>data)
};
in categiries:
PostsAPI.getByCategory(category).then((posts) =>{
posts.map((post)=>{
return addPosts(post)
});
});
my code was pushed at https://github.com/tulipjie/redux-readable
I hope someone can help me.thank you very much.
A:
Your method doesnt return anything.
Try putting "return" in front of fetch like so:
export const getByCategory=(category)=>{
return fetch(`${api}/${category}/posts`,{headers})
.then(res=>res.json())
.then(data=>data)
};
Or remove curly braces like so:
export const getByCategory=(category)=>
fetch(`${api}/${category}/posts`,{headers})
.then(res=>res.json())
.then(data=>data);
| {
"pile_set_name": "StackExchange"
} |
Q:
extjs4 store addes get params in the url
i'm using extjs4 store
In xhtpp calls it shows the http://localhost/home_dir/index.php/questions/content_pie?_dc=1312366604831&hi=&page=1&start=0&limit=25
This is the store code
var content_type_store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: BASE_URL+'questions/content_pie',
method:'POST',
params :{hi:''}
}),
reader: new Ext.data.JsonReader({
root: 'results'
}, [
'qtype',
'qval'
])
});
Even though i set the method as POST its get params appears in url
I'm using codeigniter as my framework. I disabled GET params in CI. Iwnat to send params in post. with ext2 and 3 this code worked fine..
Help me
Thanks
A:
method:'POST' in proxy's config won't work. There is no such config option. However there are two ways to make store use POST. The simplier one - just override getMethod function:
var content_type_store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: BASE_URL+'questions/content_pie',
extraParams :{hi:''},
// Here Magic comes
getMethod: function(request){ return 'POST'; }
},
reader: {
type: 'json',
root: 'results'
}
});
The second way: override proxy's actionMethods property. If you choose this way your proxy should look like this:
// ...
proxy: {
type: 'ajax',
url: BASE_URL+'questions/content_pie',
extraParams :{hi:''},
// Here Magic comes
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
}
},
// ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while executing: Segmentation fault
I'm a beginner in C language. After reading the initial chapters of Ritchie's book, I wrote a program to generate random numbers and alphabets.
The program compiles fine with gcc. However on running it, it gives an error "Segmentation fault", which is incomprehensible to my limited knowledge. I'd be glad to understand what I've written wrong.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
long int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
long int genrandom(int mino,int maxo) {
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
return val;
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%s ,",text);
}
char letterize(int num) {
char letter='A'+num;
return letter;
}
A:
printf("%s ,",text); is wrong - it says that text is a nul-terminated array of chars. Use
printf("%c ,", text);
instead to print your single char.
| {
"pile_set_name": "StackExchange"
} |
Q:
android ListView mListView.getChildAt(i) is null, how to solve it?
I create the below code:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
for (int i = 0; i < mListView.getCount(); i++) {
View callLogView = mListView.getChildAt(i);
mRelativeLayout = (LinearLayout)callLogView.findViewById(R.id.myShow);
if(i == position){
if(mRelativeLayout.getVisibility() == View.GONE){
mRelativeLayout.setVisibility(View.VISIBLE);
}
else{
mRelativeLayout.setVisibility(View.GONE);
}
}else{
mRelativeLayout.setVisibility(View.GONE);
}
}
}
});
I want to realize a function like when i click one item of Listview, it will show a view, and the other items of Listview will be hidden. But mListView.getChildAt(i) will have the null pointer after exceed mListView.getChildCount().
How to solve this? Thanks in advance!
A:
AdapterView.getCount() returns the number of data items, which may be larger than the number of visible views, that's why you are getting null pointer exception, because you are trying to find views which do not exist in the current visible ListView items.
To solve this issue you will first need to find the first visible item in the ListView using getFirstVisiblePosition() and the last visible item using getLastVisiblePosition(). Change the for loop condition as:
int num_of_visible_view=mListView.getLastVisiblePosition() -
mListView.getFirstVisiblePosition();
for (int i = 0; i < num_of_visible_view; i++) {
// do your code here
}
| {
"pile_set_name": "StackExchange"
} |
Q:
BufferedWriter java problems
i try to print something to file. so i create a array of BufferedWriters (there is reason why array) . and when i run the program, nothing happend. the files are empty.
here is my code:
BW = new BufferedWriter[8];
for(int i = 0; i < 8; i++){
BW[i] = new BufferedWriter(new FileWriter(TablePath + i + ".txt"));
BW[i].write("asdfgh");
}
this code create the txt files. but not write then anything.
what is the problem?
A:
Add this line inside loop
BW[i].Close();
It will work fine after that, you have to flush and close the BW.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I correctly calculate fuel for a Cessna 152?
I'm learning to fly in a C152 and I've found the fuel calculation to be a little ambiguous. Based on information from my instructor, Internet and the Cessna 152 Information Manual (1980), I've home cooked the following formula and wanted to run it by the community for some verification.
I hope this is an appropriate use of this forum and please excuse my newb-ness. Here's my formula:
Fuel Required =
5.6L unusable +
5L run-up and taxi +
24L/hour flight (rich) +
18L (45 minute) reserve
Based on this formula, a one hour lesson conducted in the training area and below 3,000 feet AMSL requires a minimum of 52.6 litres in the tanks, calculated as follows:
5.6L unusable + 5L run-up & taxi + 24L flight + 18L reserve = 52.6L total
Or 26.3L in each tank. Since we're measuring fuel by the surprising method of dipping a stick in the tank, I'm realistically looking for around 25L per tank, and maybe topping it up to 30 per tank to be on the safe side.
Is this correct and reasonable?
A:
The short answer is: Yes, your calculation is reasonable.
Fuel consumption values are not an exact science, they are average values and rounded in many cases or based on pilot experience. Using 24L/hr in your example for traffic patterns is the right assumption, as you will most likely remain in rich configuration. Even if you lean a bit within the pattern, you would not gain enough fuel efficiency to offset these 24L/hr.
Your 5L run-up and taxi obviously depends on the airport you are based at or use the formula at. If this value was your calculation for a smaller airfield, you might need to adapt your formula when flying to larger regional airports or airports with high-traffic, where your taxi time could be significantly longer.
Be reasonable however with topping up your values. Going from 52.6L to 60L is the equivalent of 5.3KG, which you will need to consider in your weight and balance calculation.
| {
"pile_set_name": "StackExchange"
} |
Q:
PDO search query
PDO, I want to use a search query. I tried to use like query, using % on both front and end of search variable. but it search in between the words.
like if in database there is name Jhon Anderson and if i use search variable using LIKE %erson%, The query will get me the row which contains the above name.
But what i want is query should only search with starting alphabets so i tried the LIKE query with Jhon%, i got the desired result, but using this % in the end only works if search variable matches the starting of first word, but what about the word after the space?
I mean if i try Anderson% or Ander%, The query will not get me the result of this row as Anderson is the second word in the field Jhon Anderson after space.
So my question is how to search in the words after spaces, that if there starting alphabets match the search query.
I don't know if such kind of query exist or not, but i think it might be possible with some looping after using like query with wildcard '%'.$variable.'%' and after getting all the results unset the arrays or rows where search variable do not match with the first alphabet of the result.
Any ideas how to implement such kind of search.
Query right now i am using,
$stmt = $conn->prepare("SELECT ROOM, GUEST_NAME, GUEST_FIRST_NAME, CONFIRMATION_NO, DEPARTURE, PWD FROM RESERVATION_GENERAL_2 WHERE LOWER(GUEST_FIRST_NAME) LIKE ? OR LOWER(GUEST_NAME) LIKE ?");
$stmt->execute(array('%'.strtolower($searchFilter).'%','%'.strtolower($searchFilter).'%' ));
A:
A bit dirty, but simple solution is to include the space in the search:
WHERE ' ' || Name LIKE '% Anderson%'
You see I added a space in front of Name, so it will also find the word if it is at the beginning of the string.
Alternatively, you can use REGEXP_LIKE, but then it is still a bit awkward, since Oracle doesn't have a word boundary expression in its regex engine. For a solution, see this answer
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get image from assets by folder ios
I heve Assets catalog like this
Assets
ComponentA - folder
Background - image
ComponentB - folder
Background - image
how i can get image depend of component (folder) ?
I like to use something what it is
let image = UIImage(named:"ComponentA/Background")
but this doesn't work
A:
you can get image depending on folder by "Providing Namespace" to folder.
Select folder in .xcassets
Check "Providing Namespace" in last tab (see attached image)
Access image using var image : UIImage = UIImage(named:"New Folder/bgimg")
| {
"pile_set_name": "StackExchange"
} |
Q:
ASIFormDataRequest with setPostValue and Method DELETE
I am trying to use ASIFormDataRequest with setPostValues and Method DELETE, Following are the codes lines
NSString *urlstring = [NSString stringWithFormat:@"%@%@",notificationsURL, typeId];
NSLog(@"Notification URL == %@",urlstring);
NSURL *urlR = [NSURL URLWithString:urlstring];
notificationAPNRequest = [ASIFormDataRequest requestWithURL:urlR];
notificationAPNRequest.timeOutSeconds = 30;
notificationAPNRequest.useSessionPersistence = NO;
[notificationAPNRequest setPostValue:deviceId forKey:@"deviceId"];
[notificationAPNRequest setPostValue:apnToken forKey:@"apnToken"];
if ([methodStr isEqualToString:@"OFF"]) {
[notificationAPNRequest setRequestMethod:@"DELETE"];
}
else if ([methodStr isEqualToString:@"ON"]) {
[notificationAPNRequest setRequestMethod:@"PUT"];
}
[notificationAPNRequest setDelegate:self];
[notificationAPNRequest setDidFinishSelector:@selector(notificationAPNSuccess:)];
[notificationAPNRequest setDidFailSelector:@selector(notificationAPNFailure:)];
[notificationAPNRequest startAsynchronous];
In Success method i get the Code 405
NSLog(@"%d",[request responseStatusCode]);
While when i hit from postman client then its works. Please let me know where i did mistake.
A:
When you are using DELETE method with some post parameters you need to call "buildPostBody" function before setting Http DELETE method like below
[notificationAPNRequest setPostValue:deviceId forKey:@"deviceId"];
[notificationAPNRequest setPostValue:apnToken forKey:@"apnToken"];
[notificationAPNRequest buildPostBody]; /// Call this before setting request method
[notificationAPNRequest setRequestMethod:@"DELETE"];
Hope it works now
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ return type for function producing polymorphic object?
As I understand it, to pass/return polymorphic objects you need to use a pointer or reference type to prevent slicing problems. However, to return objects from functions you cannot create on stack and return reference because the local object won't exist anymore. If you create on the heap and return reference/pointer- the caller has to manage the memory- not good.
With the above in mind, how would I write a function which returns a polymorphic type? What return mechanism/type would I use?
A:
You would return a smart pointer that takes care of the memory management and makes the ownership clear:
#include <memory>
struct IFoo
{
virtual ~IFoo() {}
};
struct Foo1 : IFoo {};
struct Foo2 : IFoo {};
std::unique_ptr<IFoo> make_foo()
{
return std::unique_ptr<IFoo>{new Foo1()};
}
Note that C++14 has std::make_unique, which allows you to do the above without having to call new directly. See related question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Word for graph that counts backwards vs graph that counts forwards
Sorry if the title was confusing. I am having difficulty putting this simply, so let
Let's say we're graphing sales per week as a line graph.
You can count forwards, in which case, if viewing on a Sunday, it would appear as though sales are down this week, and through the week, it would move up until the end of the week.
Or you can count backwards. In this case, the last data point (this week) is exactly 7 days of data, and so forth all the way to the start.
What is the name for these two types of graphs?
A:
Your first graph is a running total that resets weekly.
Your second graph is a rolling sum, also called a moving sum. From the linked page on Wikipedia:
In financial applications a simple moving average (SMA) is the unweighted mean of the previous n data.
This can clearly be extended to other operations, such as a "moving sum" from your example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rmarkdown Beamer 16:9 aspect ratio
How to set the aspect ratio of beamer slides created using Rmarkdown in Rstudio to 16:9? It does not seem to be a standard option. I tried changing the \documentclass{} options using a header.tex insert but this was not successful.
A:
Put the option in double quotes:
output:
beamer_presentation:
classoption: "aspectratio=169"
Notice that classoption keyword is at the same level with output.
pandoc 1.19
texlive 2015
knitr 1.17
rmarkdown 1.6
| {
"pile_set_name": "StackExchange"
} |
Q:
Integration of twitter posting in Blackberry+IllegalArguementException
i am trying to embed twitter posting feature in my application.
i am using twitter api_me-1.8
i am able to reach the login screen(though most of the text is displayed as boxes- i am guessing that the text is in hindi/tamil as i am in india...), but as soon as i enter my credentials,i get taken to another page with some text in the top in boxes...
and more text in english below that(you can revoke access to any application...) ...then i get an illeagalArguementException after a minute...
i tried to debug the application,
public TwitterUiScreen(String wallMsg) {
System.out.println("Twitter UI BEGINS!");
setTitle("Twitter");
this.wallMsg = wallMsg;
BrowserContentManager browserMngr = new BrowserContentManager(0);
RenderingOptions rendOptions = browserMngr.getRenderingSession()
.getRenderingOptions();
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.SHOW_IMAGES_IN_HTML, false);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.ENABLE_EMBEDDED_RICH_CONTENT, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_FONT_FACE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_CHARSET_VALUE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.JAVASCRIPT_ENABLED, true);
/*
* browserMngr.getRenderingSession().getRenderingOptions().setProperty(
* RenderingOptions.CORE_OPTIONS_GUID,
* RenderingOptions.DEFAULT_FONT_FACE, Font.getDefaultFont());
*/
add(browserMngr);
OAuthDialogWrapper pageWrapper = new BrowserContentManagerOAuthDialogWrapper(browserMngr);
pageWrapper.setConsumerKey(CONSUMER_KEY);
pageWrapper.setConsumerSecret(CONSUMER_SECRET);
pageWrapper.setCallbackUrl(CALLBACK_URL);
pageWrapper.setOAuthListener(this);
pageWrapper.login();
}
i had breakpoints upto the last line, and all of them were hit, with no problems...
but as soon as i logged in, i hit the exception.( i think it was in this page:-
BrowserContentManagerOAuthDialogWrapper.java (version 1.1 : 45.3, super bit)
after which i get to a third screen.
the comment was barely legible- so i thought i might as well add the code over here:
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME+ "://" + OAUTH_CALLBACK_HOST;
private final String CALLBACK_URL = OAUTH_CALLBACK_URL;
i managed to get the source and attach it to the jar file. the exception that the BrowserContentManagerOAuthDialogWrapper.java throws is:: Protocol not found: net.rim.device.cldc.io.x-oauthflow-twitter.Protocol
in this method::
protected void loadUrl(final String url, final byte[] postData,
final Event event) {
new Thread() {
public void run() {
try {
HttpConnection conn = getConnection(url);
//
if (postData != null) {
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty(
"Content-Length", String.valueOf(postData.length));
//
OutputStream out = conn.openOutputStream();
out.write(postData);
out.close();
}
//
browserManager.setContent(
conn, renderingListenerOAuth, event);
} catch (IOException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}.start();
}
A:
feel like hitting myself.
my clients had told us that the twitter posting was not working...
so i assumed that it did not work.
for some reason, it does not work in the simulator- but seems to work fine on the device.
the clients have assumed that it does not work, as after we try logging in, it takes too long to post, and displays the third screen for about 20 seconds, and they seem to have clicked back early, deciding that posting did not work.
now i need to figure out a way to post a message on the third screen asking the user to wait for the post to be successful.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to invoke click:prepend event or click:append event in the vuetify input fields
I want to trigger the input field click:prepend function by clicking other element.
As far now I am able to access the element using refs but in order to achieve some functionality I need to trigger the click:prepend. How can I trigger
<v-file-input accept="image/*" ref="fileInputSelector"></v-file-input>
this.$refs.fileInputSelector.$el.click()
A:
You can click the vuetify input element programatically in jaavascript, but you need to traverse to input from refs pointer
this.$refs.fileInputSelector.$el
just points to the div wrapper of vuetify component , you have to traverse to the input by
var id = this.$refs.fileInput.$el.lastChild.firstChild.firstChild.lastChild.id;
document.querySelector(`input#${id}`).click();
Working codepen here: https://codepen.io/chansv/pen/PoozMYY?editors=1010
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript Floating Point Number Regex Expression
I am looking for a regular expression to match floating point numbers with at most 4 digits before the '.' and at most 4 digits after.
Examples of valid inputs:
1234.5678
123.567
12.34
1.2
1.23
12.3
etc...
A:
There are many places where you get the answer for it. Here is your required answer,
^\d{0,4}(\.\d{0,4})?$
Test the answer in this Link
| {
"pile_set_name": "StackExchange"
} |
Q:
How to clean whitespaces in jComboBox
I´m trying to make a jComboBox that contains books titles and when i hit a button that "loan a book", that book no longer appear.
I was able to make all that work, but when I "lend a book", there is a blank space where it was located.
This is the code that i tryied:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()]; //librosDisponibles() returns the amount of books available
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo(); //get the titles
}
}
jComboBox3.removeAll();
DefaultComboBoxModel modelo = new DefaultComboBoxModel(libros);
this.jComboBox3.setModel(modelo);
}
And also tryied this:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()];
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo();
}
}
DefaultComboBoxModel modelo = (DefaultComboBoxModel)jComboBox3.getModel();
modelo.removeAllElements();
for(String libro : libros)
{
modelo.addElement(libro);
}
jComboBox3.setModel(modelo);
}
With both of them i obtain this results:
Picking a book
Borrowed book
A:
and when i hit a button that "loan a book", that book no longer appear.
You need to remove the selected item from the model of the combo box.
So the code in your ActionListener of the combo box would be something like:
JComboBox comboBox = (JComboBox)e.getSource();
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
Object item = comboBox.getSelectedItem();
model.removeElement( item );
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom UIView doesnt show
I have very simple UIView that creating the box, but what is happen is the UIView does not show at all, here is my code on sharingButtons.m
-(void)createContainer{
winWidth = [UIScreen mainScreen].bounds.size.width;
buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, winWidth, 20)];
buttonContainer.backgroundColor = [UIColor redColor];
[self.view addSubview:buttonContainer];
}
-(void)createButton{
[self createContainer];
}
and here is my sharingButtons.h
@interface SocialSharing : UIViewController {
int winWidth;
}
- (void)createButton;
- (void)createContainer;
#pragma mark - Properties
@property(nonatomic, strong) UIView* buttonContainer;
@end
And createButton method is called from MyViewControler.m on viewDidLoad
Is any wrong with my code??
EDITED
Here is my code on MyViewControler.m
- (void)loadSocialSharingButton {
socialButtons = [[SocialSharing alloc] init];
[socialButtons createButton];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadSocialSharingButton];
}
Sorry I just learn about obj c :)
Thanks a lot
A:
The reason your buttonContainer is not visible is, it is not loaded in your view hierarchy.
To make it visible you should add it as subview. In MyViewController.m in viewDidLoad add the following line after [self loadSocialSharingButton];
[self.view addSubview:socialButtons.buttonContainer];
Hope this Helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
error geocoding API
I am trying to use google geocoding. If i just type
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
it gives me right output. I am trying to use this with a amazon proxy server and it gives
{ "error_message" : "The 'sensor' parameter specified in the request must be set to either 'true' or 'false'.", "results" : [], "status" : "REQUEST_DENIED" }
This the code
http://ec2-00-000-000-000.compute-1.amazonaws.com/OsProxy/getpage.aspx?p=https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
Can someone help me?
Thanks
Rashmi
A:
You need to URL-encode your parameters. Consider the URL you're using:
http://ec2-00-000-000-000.compute-1.amazonaws.com/OsProxy/getpage.aspx?p=https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
This is parsed as:
http://ec2-00-000-000-000.compute-1.amazonaws.com/OsProxy/getpage.aspx?
p=https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&
sensor=true
That is, you're passing the sensor parameter to amazonws.com, not to googleapis.com.
Since the only parameter to amazonws.com should be the full URL, encode that URL so it reaches amazonws.com as a single parameter to be passed through to googleapis.com:
http://ec2-00-000-000-000.compute-1.amazonaws.com/OsProxy/getpage.aspx?p=https%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fgeocode%2Fjson%3Faddress%3D1600%2BAmphitheatre%2BParkway%2C%2BMountain%2BView%2C%2BCA%26sensor%3Dtrue
| {
"pile_set_name": "StackExchange"
} |
Q:
c# resize datagridview columns to fit control
I have a datagridview that is docked and anchored with a panel on a Winform. When I resize the form, the datagridview resizes as expected, but the columns do not resize to fit the datagridview. Instead, I am left with the background colour of the Datagridview.
How can I get the columns to grow with the control?
Thanks.
A:
You could always use the AutoSizeColumnsMode property
This property lets you configure the control so that column widths are automatically adjusted either to fill the control or to fit cell contents. Size adjustments occur in fill mode whenever the width of the control changes.
There's a lot more information on the MSDN page for this.
A:
You can set AutoSizeMode property of one of the columns to be Fill. Then this column will always resize itself to fill all the available space not used by other columns.
A:
private void dataGrid_SizeChanged(object sender, EventArgs e)
{
ResizeGridColumns();
}
private void ResizeGridColumns()
{
//get sum of non-resizable columns width
int diffWidth = 0;
foreach (DataGridViewColumn col in this.dataGrid.Columns)
{
if (col.Resizable == DataGridViewTriState.False && col.Visible) diffWidth += col.Width;
}
//calculate available width
int totalResizableWith = this.dataGrid.Width - diffWidth;
//resize column width based on previous proportions
this.dataGrid.ColumnWidthChanged -= new DataGridViewColumnEventHandler(dataGrid_ColumnWidthChanged);
for (int i = 0; i < this.colWidthRaport.Count; i++)
{
try
{
if (this.dataGrid.Columns[i].Resizable != DataGridViewTriState.False && this.dataGrid.Columns[i].Visible)
{
this.dataGrid.Columns[i].Width = (int)Math.Floor((decimal)totalResizableWith / this.colWidthRaport[i]);
}
}
catch { }
}
this.dataGrid.ColumnWidthChanged += new DataGridViewColumnEventHandler(dataGrid_ColumnWidthChanged);
}
private void dataGrid_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
CalculateGridColWidthsRaport();
}
/// <summary>Calculates the proportions between grid width and column width</summary>
private void CalculateGridColWidthsRaport()
{
//get sum of non-resizable columns width
int diffWidth = 0;
int colWidthsSum = 0;
foreach (DataGridViewColumn col in this.dataGrid.Columns)
{
if (col.Visible)
{
colWidthsSum += col.Width;
if (col.Resizable == DataGridViewTriState.False) diffWidth += col.Width;
}
}
colWidthsSum += 24;
//calculate available with
int totalResizableWith = colWidthsSum - diffWidth;// this.dataGrid.Width - diffWidth;
if (this.ParentForm.WindowState == FormWindowState.Maximized)
{
totalResizableWith = this.dataGrid.Width - diffWidth;
}
//calculate proportions of each column relative to the available width
this.colWidthRaport = new List<decimal>();
foreach (DataGridViewColumn col in this.dataGrid.Columns)
{
this.colWidthRaport.Add((decimal)totalResizableWith / (decimal)col.Width);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Stuck in recurrence relation
$T(n) = 2 T\left(\dfrac{n}{2}\right) + n (\log_{2}n)^{2}, n > 1$
$T(1) = 1$
Note : $(\log_{2}n)^{2} = \log_2 n \times \log_2 n$
I have solve the above equation till the step
$T(n) = 2^{k} T\left(\dfrac{n}{2^k}\right) + n \sum_{i = 0}^{k-1} \left(\log_{2} \dfrac{n}{2^{i}}\right)^2$
However I am unable to solve
$\sum_{i = 0}^{k-1} \left(\log_{2} \dfrac{n}{2^{i}}\right)^2$
A:
Making $n=2^z$ we have
$$
\mathbb T(z)=2\mathbb T(z-1)+2^z z^2
$$
with solution
$$
\mathbb T (z) = \frac 13 2^{z-1}\left(z+3z^2+2z^3+3C_0\right)
$$
and finally $\mathbb T (z)\to T(n)$
$$
T(n) = \frac n2C_0 + \frac n6 \log_2 n+\frac n2 (\log_2 n)^2+\frac n3(\log_2 n)^3
$$
NOTE
$$
\mathbb T (u) = T(2^u)
$$
$$
T(n) = T\left(2^{\log_2 n}\right) = T\left(2^z\right) = \mathbb T(z)
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Get first parent key of value from Multidimensional Array in PHP
How to get the first parent key of value from Multidimensional Array in PHP
Sample Code :
$arr = array(
"a" => array("1"=>"!","2"=>"@","3"=>"#"),
"b" => array("4"=>"$","5"=>"%","6"=>"^"),
"c" => array("7"=>"&","8"=>"*","9"=>"(")
);
echo array_search("%",$arr);
Require Output:
b
A:
You can filter the array returning only the array(s) that contain what you are searching for and get the key:
echo key(array_filter($arr, function($v) { return array_search("%", $v); }));
Obviously if it is found in more than one array you will have to decide which key you want. The above will give you the first key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't browserify use my module?
I made a library, bundled it with browserify, put it here: https://github.com/cfv1984/two-ways and published a module from it.
The library as compiled works just fine in the browser, the package I made from it is unusable as you can see by installing it and having a test file like this:
var two = require('two-ways');
console.log("Two", two);
And running it through
browserify test.file.js > test.compiled.js
What am I doing wrong? The error message I get, Error: Cannot find module './../../util/makeGetter' from 'D:\o\puto\node_modules\two-ways'makes 0 sense in this context, because I don't actually have a file in there any more, but a bundle, which as far as I can tell browserify was OK with generating.
Any pointers?
A:
Browserify was mis-packing the file after transmogrifying it through Babel, so I simply used Webpack to package with which made it self-consistent again and I can use it with browserify and/or webpack or any other bundling software without much issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hourly points add to users php and mysql solution?
In the website im working on i need to add user points. Every user will have it's own points and maximum amount of points will be 200. And upon registration user gets 100 points. With various tasks user points will be deducted.
But main problem im struggling is how to add points to the user, since every user need to gets 1 point every hour unless he have 200 or more points.
My first thought was to do a cronjob where it will run every hour a script which will check if user is verified and if user have less than 200 points and add 1 point to every user.
But after some reading im thinking of different approach which i don't understand quite exactly. The better approach, less server resource consuming would be to run a function which will check every time when user login how many points he have and add appropriate number of points to him. Problem is i don't know how to set it, how to calculate how many points to add to user if he was offline like 8 hours and how to time it? Or even maybe use ajax with timer?
What would be your suggestion and approach to this ?
Edit: Just to add since you ask, users doesn't see each other points.
A:
When a user does something, check the last time you gave them points. If it was 5 hours ago, give them 5 points. If it was 10 hours ago, give them 10 points. Etc. Implement caching so if a user visits your site 50 times in one hour, you don't have to check against the DB every time.
Anyway, short answer is, do the check when loading the user data, rather than automatically every hour for all users whether they are active or not.
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF&MVVM: access to Controls from RelayCommand()
I need both operating by mouse clicking and operating by hotkeys in my WPF application. User's actions affects on both data and appearance of application controls.
For example, the following app will send data to tea machine. You can select the tea brand, type (hot or cold) and optional ingredients: milk, lemon and syrup.
Not good from the point of view of UI design, but just example:
If to click the dropdown menu or input Ctrl+B, the list of select options will appear.
If to click the "Hot" button on input Ctrl+T, button becomes blue and text becomes "Cold". If to click or input Ctrl+T again, button becomes orange and text becomes to "Hot" again.
If to click optional ingredient button or input respective shortcut, button's background and text becomes gray (it means "unselected"). Same action will return the respective button to active state.
If don't use MVVM and don't define shortcuts, the logic will be relatively simple:
Tea tea = new Tea(); // Assume that default settings avalible
private void ToggleTeaType(object sender, EventArgs e){
// Change Data
if(tea.getType().Equals("Hot")){
tea.setType("Cold");
}
else{
tea.setType("Hot");
}
// Change Button Appearence
ChangeTeaTypeButtonAppearence(sender, e);
}
private void ChangeTeaTypeButtonAppearence(object sender, EventArgs e){
Button clickedButton = sender as Button;
Style hotTeaButtonStyle = this.FindResource("TeaTypeButtonHot") as Style;
Style coldTeaButtonStyle = this.FindResource("TeaTypeButtonCold") as Style;
if (clickedButton.Tag.Equals("Hot")) {
clickedButton.Style = coldTeaButtonStyle; // includes Tag declaration
clickedButton.Content = "Cold";
}
else (clickedButton.Tag.Equals("Cold")) {
clickedButton.Style = hotTeaButtonStyle; // includes Tag declaration
clickedButton.Content = "Hot";
}
}
// similarly for ingredients toggles
XAML:
<Button Content="Hot"
Tag="Hot"
Click="ToggleTeaType"
Style="{StaticResource TeaTypeButtonHot}"/>
<Button Content="Milk"
Tag="True"
Click="ToggleMilk"
Style="{StaticResource IngredientButtonTrue}"/>
<Button Content="Lemon"
Tag="True"
Click="ToggleLemon"
Style="{StaticResource IngredientButtonTrue}"/>
<Button Content="Syrup"
Tag="True"
Click="ToggleSyrup"
Style="{StaticResource IngredientButtonTrue}"/>
I changed my similar WPF project to MVVM because thanks to commands it's simple to assign the shortcuts:
<Window.InputBindings>
<KeyBinding Gesture="Ctrl+T" Command="{Binding ToggleTeaType}" />
</Window.InputBindings>
However, now it's a problem how to set the control's appearance. The following code is invalid:
private RelayCommand toggleTeaType;
public RelayCommand ToggleTeaType {
// change data by MVVM methods...
// change appearence:
ChangeTeaTypeButtonAppearence(object sender, EventArgs e);
}
I need the Relay Commands because I can bind it to both buttons and shortcuts, but how I can access to View controls from RelayCommand?
A:
You should keep the viewmodel clean of view specific behavior. The viewmodel should just provide an interface for all relevant settings, it could look similar to the following (BaseViewModel would contain some helper methods to implement INotifyPropertyChanged etc.):
public class TeaConfigurationViewModel : BaseViewModel
{
public TeaConfigurationViewModel()
{
_TeaNames = new string[]
{
"Lipton",
"Generic",
"Misc",
};
}
private IEnumerable<string> _TeaNames;
public IEnumerable<string> TeaNames
{
get { return _TeaNames; }
}
private string _SelectedTea;
public string SelectedTea
{
get { return _SelectedTea; }
set { SetProperty(ref _SelectedTea, value); }
}
private bool _IsHotTea;
public bool IsHotTea
{
get { return _IsHotTea; }
set { SetProperty(ref _IsHotTea, value); }
}
private bool _WithMilk;
public bool WithMilk
{
get { return _WithMilk; }
set { SetProperty(ref _WithMilk, value); }
}
private bool _WithLemon;
public bool WithLemon
{
get { return _WithLemon; }
set { SetProperty(ref _WithLemon, value); }
}
private bool _WithSyrup;
public bool WithSyrup
{
get { return _WithSyrup; }
set { SetProperty(ref _WithSyrup, value); }
}
}
As you see, there is a property for each setting, but the viewmodel doesn't care about how the property is assigned.
So lets build some UI. For the following example, generally suppose xmlns:local points to your project namespace.
I suggest utilizing a customized ToggleButton for your purpose:
public class MyToggleButton : ToggleButton
{
static MyToggleButton()
{
MyToggleButton.DefaultStyleKeyProperty.OverrideMetadata(typeof(MyToggleButton), new FrameworkPropertyMetadata(typeof(MyToggleButton)));
}
public Brush ToggledBackground
{
get { return (Brush)GetValue(ToggledBackgroundProperty); }
set { SetValue(ToggledBackgroundProperty, value); }
}
// Using a DependencyProperty as the backing store for ToggledBackground. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ToggledBackgroundProperty =
DependencyProperty.Register("ToggledBackground", typeof(Brush), typeof(MyToggleButton), new FrameworkPropertyMetadata());
}
And in Themes/Generic.xaml:
<Style TargetType="{x:Type local:MyToggleButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyToggleButton}">
<Border x:Name="border1" BorderBrush="Gray" BorderThickness="1" Background="{TemplateBinding Background}" Padding="5">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="border1" Property="Background" Value="{Binding ToggledBackground,RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Now, build the actual window content using this toggle button. This is just a rough sketch of your desired UI, containing only the functional controls without labels and explanation:
<Grid x:Name="grid1">
<StackPanel>
<StackPanel Orientation="Horizontal">
<ComboBox
x:Name="cb1"
VerticalAlignment="Center"
IsEditable="True"
Margin="20"
MinWidth="200"
ItemsSource="{Binding TeaNames}"
SelectedItem="{Binding SelectedTea}">
</ComboBox>
<local:MyToggleButton
x:Name="hotToggle"
IsChecked="{Binding IsHotTea}"
VerticalAlignment="Center"
Margin="20" MinWidth="60"
Background="AliceBlue" ToggledBackground="Orange">
<local:MyToggleButton.Style>
<Style TargetType="{x:Type local:MyToggleButton}">
<Setter Property="Content" Value="Cold"/>
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value="Hot"/>
</Trigger>
</Style.Triggers>
</Style>
</local:MyToggleButton.Style>
</local:MyToggleButton>
</StackPanel>
<StackPanel Orientation="Horizontal">
<local:MyToggleButton
x:Name="milkToggle"
Content="Milk"
IsChecked="{Binding WithMilk}"
VerticalAlignment="Center"
Margin="20" MinWidth="60"
Background="WhiteSmoke" ToggledBackground="LightGreen"/>
<local:MyToggleButton
x:Name="lemonToggle"
Content="Lemon"
IsChecked="{Binding WithLemon}"
VerticalAlignment="Center"
Margin="20" MinWidth="60"
Background="WhiteSmoke" ToggledBackground="LightGreen"/>
<local:MyToggleButton
x:Name="syrupToggle"
Content="Syrup"
IsChecked="{Binding WithSyrup}"
VerticalAlignment="Center"
Margin="20" MinWidth="60"
Background="WhiteSmoke" ToggledBackground="LightGreen"/>
</StackPanel>
</StackPanel>
</Grid>
Notice the style trigger to change the button content between Hot and Cold.
Initialize the datacontext somewhere (eg. in the window constructor)
public MainWindow()
{
InitializeComponent();
grid1.DataContext = new TeaConfigurationViewModel();
}
At this point, you have a fully functional UI, it will work with the default mouse and keyboard input methods, but it won't yet support your shortcut keys.
So lets add the keyboard shortcuts without destroying the already-working UI. One approach is, to create and use some custom commands:
public static class AutomationCommands
{
public static RoutedCommand OpenList = new RoutedCommand("OpenList", typeof(AutomationCommands), new InputGestureCollection()
{
new KeyGesture(Key.B, ModifierKeys.Control)
});
public static RoutedCommand ToggleHot = new RoutedCommand("ToggleHot", typeof(AutomationCommands), new InputGestureCollection()
{
new KeyGesture(Key.T, ModifierKeys.Control)
});
public static RoutedCommand ToggleMilk = new RoutedCommand("ToggleMilk", typeof(AutomationCommands), new InputGestureCollection()
{
new KeyGesture(Key.M, ModifierKeys.Control)
});
public static RoutedCommand ToggleLemon = new RoutedCommand("ToggleLemon", typeof(AutomationCommands), new InputGestureCollection()
{
new KeyGesture(Key.L, ModifierKeys.Control)
});
public static RoutedCommand ToggleSyrup = new RoutedCommand("ToggleSyrup", typeof(AutomationCommands), new InputGestureCollection()
{
new KeyGesture(Key.S, ModifierKeys.Control)
});
}
You can then bind those commands to appropriate actions in your main window:
<Window.CommandBindings>
<CommandBinding Command="local:AutomationCommands.OpenList" Executed="OpenList_Executed"/>
<CommandBinding Command="local:AutomationCommands.ToggleHot" Executed="ToggleHot_Executed"/>
<CommandBinding Command="local:AutomationCommands.ToggleMilk" Executed="ToggleMilk_Executed"/>
<CommandBinding Command="local:AutomationCommands.ToggleLemon" Executed="ToggleLemon_Executed"/>
<CommandBinding Command="local:AutomationCommands.ToggleSyrup" Executed="ToggleSyrup_Executed"/>
</Window.CommandBindings>
and implement the appropriate handler method for each shortcut in the window code behind:
private void OpenList_Executed(object sender, ExecutedRoutedEventArgs e)
{
FocusManager.SetFocusedElement(cb1, cb1);
cb1.IsDropDownOpen = true;
}
private void ToggleHot_Executed(object sender, ExecutedRoutedEventArgs e)
{
hotToggle.IsChecked = !hotToggle.IsChecked;
}
private void ToggleMilk_Executed(object sender, ExecutedRoutedEventArgs e)
{
milkToggle.IsChecked = !milkToggle.IsChecked;
}
private void ToggleLemon_Executed(object sender, ExecutedRoutedEventArgs e)
{
lemonToggle.IsChecked = !lemonToggle.IsChecked;
}
private void ToggleSyrup_Executed(object sender, ExecutedRoutedEventArgs e)
{
syrupToggle.IsChecked = !syrupToggle.IsChecked;
}
Again, remember this whole input binding thing is purely UI related, it is just an alternative way to change the displayed properties and the changes will be transferred to the viewmodel with the same binding as if the user clicks the button by mouse. There is no reason to carry such things into the viewmodel.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make dynamic namespace or scopes route in rails
I am trying to make admin route with namespace but it doest trigger to the route
I run rails g controller admin
it created the file app/controllers/admin_controller.rb , app/views/admin/index.html.haml
my namespace look like this
namespace :admin do
controller :admin do
get '/', :index
end
end
it doesn't trigger to localhost:3000/admin it said not found for that route
any idea ??
A:
namespace not only adds a path prefix but it also adds a module nesting to the expected controller. For example:
namespace :blog do
resources :posts
end
Will create the route /blog/posts => Blog::PostsController#index.
In your example Rails expects the controller to be defined as:
# app/controllers/admin/admin_controller.rb
module Admin
class AdminController
# GET /admin
def index
end
end
end
If you just want to add a path prefix or other options to the routes without module nesting use scope instead:
scope :admin, controller: :admin do
get '/', action: :index
end
This will route /admin to AdminController#index
But if this just a one off route you could just write:
get :admin, to: 'admin#index'
| {
"pile_set_name": "StackExchange"
} |
Q:
Functions being executed at definition? -JS
I'm going through the Google maps API guides and noticed that the demo on this page: https://developers.google.com/maps/documentation/javascript/marker-clustering is using the functions defined inside of initMap() apparently without actually calling them. The only related info I can find is people mistakenly adding a () at the end of a function when defining or passing as a variable, but I don't see that happening here - How are these functions being executed?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
A:
The code creates new objects, passing along existing ones. For instance when map is declared, the code calls new google.maps.Map(...), passing along document.getElementById('map'). The constructor of the Map object creates the map and displays it inside the element. The variable isn't really needed, except later when the markers are added.
You could in fact remove var markerCluster = from the code above and it would still work fine.
If your question is how the Google Maps API knows how to call initMap, see Eric's answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP's exec() can't access network drive
In PHP, I list some file by calling exec("dir ..."). However, this strangely works only on local drives. On network drives it has non-zero result status code and no results are returned.
I run Apache on Windows XP Professional.
Is there any trick to fix this? Or to view an error message?
EDIT: apache is running under the same user as I am and I can do it from the command line
A:
I was going to say "you can't do it from the command line either", and I'm sure that used to be true, but I have just tried on WinXP Pro SP3 and it is working, just to spite me.
I had to get PHP to talk to a network drive some time ago (when I was decidedly greener in the world of PHP), and I had a nightmare getting it to work, however eventually I managed to get it to work by doing the following:
In the "Services" MMC snap-in, change the user account that Apache runs under to a local user. It will probably be set to SYSTEM at the moment and (AFAIK) that account does not have access to network drives. You will need to restart the service after you do this.
Add the following line before you try and access it: system('net use Z: "\\servername\sharename" PASSWORD /user:USERNAME /persistent:no');, where you change the drive letter, UNC path, username etc to match your requirements. Do this even if the drive is already mapped. I seem to remember that I had to use system() instead of exec() or shell_exec() or it didn't work - as a result, you need to output-buffer to stop the output being passed to STDOUT.
I have no idea why this worked, but it did. Note, though, that I was trying to use the drive with native PHP functions like opendir() and fopen(), rather than trying to exec() an external program against it.
If you want to view the error messages from your call to dir, append 2>&1 to the end of the command. This will redirect STDERR to STDOUT, so you should get the error messages in the result of exec().
So your line would look like:
exec("dir Z:\\some\\path 2>&1")
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure Active Directory not Working (After deletion of Cookies)
I've created a MVC Application and hosted in Azure App along with Active Directory.
The problem here is when clicking the Submit Button (login module) with Active Directory ,it works for sometimes and not after sometimes
It not working in the sense=> It took too much time for loading to get the replay URL Like this
And result with the Bad Request !
Steps to re-pro my Issue:
When i tried to delete the cookies in my browser.This will not be work.(Long time Loading and result into Bad Request)m
When i tried to open in multiple browser
What will be the Cause for my Problem here ?
(P.s : I used Azure Sql Server for the Database Connection string)
Thanks in Advance,
Jayendran
UPDATED 1
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Server = tcp:myazuresql.database.windows.net,1433; Initial Catalog = database; Persist Security Info = False; User ID = username; Password = mypassW@Azure; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:ClientId" value="to be filled" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:ClientSecret" value="to be filled" />
<add key="ida:Domain" value="domain.com" />
<add key="ida:TenantId" value="to be filled" />
<add key="ida:PostLogoutRedirectUri" value="https://ww.mydomain.com/" />
</appSettings>
<system.web>
<customErrors mode="Off" />
<compilation targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpRuntime maxRequestLength="10000"/>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Services.Client" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.8.1.0" newVersion="5.8.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.8.1.0" newVersion="5.8.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.8.1.0" newVersion="5.8.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
Now the response header length is 75
UPDATED 2
I just found why the Page loading so much time with the help of developer tool in chrome
During the login Page : The Request Header says Provisional headers are shown
This URL makes collapse my Login Page to run Continuously. I also checked copy this URL and paste it in separate tab.It takes too much time and ended with Req header too long
A:
It's a known bug in Katana where the Katana cookie manager and the ASP .NET cookie manager clash and overwrite each other's cookies
I've just fixed using the below Answer
Second sign-in causes infinite redirect loop after the first successful login MVC .NET 5 OWIN ADAL OpenIDConnect
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a line chart with a factor variable and a continuous variable in ggplot r
I have the following data:
cefr_hours <- data.frame(cefr = as.factor(c("A2", "B1", "B2", "C1", "C2")),
hours = c(200, 400, 600, 800, 1200))
And I have created the following plot:
ggplot(cefr_hours, aes(x = cefr, y = hours)) +
geom_point() +
geom_line() +
theme_minimal() +
labs(title = "Hours of Guided Learning Per Level", subtitle = "Source: Cambridge English Assessment") +
xlab("CEFR Level") +
ylab("Number of Hours")
What I want to do is draw an arrow through each of the points and then shade the area under the line and between the points similar to this meaning the colors between each of the levels would be different.
Thank you in advance for your assistance.
A:
This is pretty hacky, but it works. I had to play with the data a bit to create "groups" of the data from A2 to B1, then B1 to B2 and so on. I'm sure there's a better way of doing this.
library(tidyverse)
cefr_hours <- data_frame(cefr = as.factor(c("A2", "B1", "B2", "C1", "C2")),
hours = c(200, 400, 600, 800, 1200))
#duplicate the data and create an indicator for group
cefr_hours <- cefr_hours %>%
bind_rows(cefr_hours) %>%
arrange(cefr) %>%
#create a group for A2 to B1, then B1 to B2, etc.
mutate(group = ceiling((row_number() - 1) / 2)) %>%
#exclude the first and last points
filter(group != min(group), group != max(group)) %>%
#convert from numeric to character
mutate(group = letters[group])
ggplot(cefr_hours, aes(x= cefr, y=hours, group = group, fill = group)) +
geom_ribbon(aes(ymin = 0, ymax = hours))+
geom_point() +
geom_line(arrow = arrow(angle = 15, ends = "last", type = "closed")) +
theme_minimal() +
labs(title = "Hours of Guided Learning Per Level",
subtitle = "Source: Cambridge English Assessment",
x = "CEFR Level",
y = "Number of Hours") +
scale_fill_brewer(palette = "Dark2") +
theme(legend.position = "none")
| {
"pile_set_name": "StackExchange"
} |
Q:
How to skip static(hardcoded entry) entry in PostgreSQL if value is NULL?
I have written following query for data retrieval in Jasper report.
select d.description as description,d.upload_count as count
from
(select a.doc_type,b.description,count(*) as upload_count
from case_uploads a,doc_type b
where a.doc_type = b.doc_type
and a.upload_dt >= $P{START_DATE}
and a.upload_dt <= $P{END_DATE}
group by a.doc_type,b.description) d
where d.doc_type not in ('215','F35')
union all
select 'Applications' as description,SUM(d.upload_count) as count
from
(select a.doc_type,b.description,count(*) as upload_count
from case_uploads a,doc_type b
where a.doc_type = b.doc_type
and a.upload_dt >= $P{START_DATE}
and a.upload_dt <= $P{END_DATE}
group by a.doc_type,b.description) d
where d.doc_type in ('215','F35')
Here, in my database I have data for June 2015 only. If my start_date and end_date are from any month other than June.
So in this case I don't want to display any data in my result set. But as my query contains 'Applications' as hard coded value, its adding an entry in result set with NULL value.
description count
------------------------
Applications null
Because of this null value, jasper report throwing "Null pointer exception" after execution.
I want to skip this entry if data is not retrieved. Is there any way to achieve this?
A:
based on the comments, you can use this:
select d.description as description,d.upload_count as count
from
(select a.doc_type,b.description,count(*) as upload_count
from case_uploads a,doc_type b
where a.doc_type = b.doc_type
and a.upload_dt >= $P{START_DATE}
and a.upload_dt <= $P{END_DATE}
group by a.doc_type,b.description) d
where d.doc_type not in ('215','F35')
and d.upload_count IS NOT NULL
union all
select 'Applications' as description,SUM(d.upload_count) as count
from
(select a.doc_type,b.description,count(*) as upload_count
from case_uploads a,doc_type b
where a.doc_type = b.doc_type
and a.upload_dt >= $P{START_DATE}
and a.upload_dt <= $P{END_DATE}
group by a.doc_type,b.description) d
where d.doc_type in ('215','F35')
having SUM(d.upload_count) IS NOT NULL
| {
"pile_set_name": "StackExchange"
} |
Q:
"[Edit]" shortlink is changed to lowercase at the begining of a sentence
The comment below this post contains a sentence starting with "[Edit]".
The system changes it to a lower case 'edit'.
A:
This is an issue. While "please [edit]" might sound nicer than "[edit]", i usually write it in the form of "[Edit]ing this question for xyz would improve it", and find it annoying to have to rephrase.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML Encoding alpha, beta, gamma
I am trying to HTML encode a string that contains alpha, beta, and gamma characters (α, β, γ
). Unfortunately, using the System.Web.HttpUtility.HtmlEncode is not encoding these characters. Is there some other function in the .NET library that would encode these to HTML?
A:
Not aware of any built in tool for this, but you can use this handy function:
public string ForceHtmlEncode(string input)
{
return string.Concat(input.Select(c => "&#" + (int)c + ";"));
}
This will simply convert all characters in the string to HTML entities.
| {
"pile_set_name": "StackExchange"
} |
Q:
how can i calculate the one number is power of another number or not?
def is_power_of(number, base):
# Base case: when number is smaller than base.
Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.
def is_power_of(number, base):
# Base case: when number is smaller than base.
if number < base:
# If number is equal to 1, it's a power (base**0).
return __
# Recursive case: keep dividing number by base.
return is_power_of(__, ___)
print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False```
A:
def is_power_of(number, base):
# Base case: when number is smaller than base.
if number < base:
# If number is equal to 1, it's a power (base**0).
return number == 1
result = number//base
# Recursive case: keep dividing number by base.
return is_power_of(result, base)
| {
"pile_set_name": "StackExchange"
} |
Q:
Group a multidimensional array by a Key value?
I have an multi dimensional array i am trying to group the array based on the key value.
So, I'm trying to group them by key but i am not getting to group the
array based on the key values.
Below is the original array
Array
(
[0] => Array
(
[User] => Array
(
[id] => 2
[feature] => AddUser
[feature_level] => 1
[parent_feature] => 1
)
)
[1] => Array
(
[User] => Array
(
[id] => 3
[feature] => EditUser
[feature_level] => 1
[parent_feature] => 1
)
)
[2] => Array
(
[Candidate] => Array
(
[id] => 5
[feature] => AddCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
[3] => Array
(
[Candidate] => Array
(
[id] => 6
[feature] => EditCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
)
What i need is
Array (
[User] => Array (
[0] => Array (
[id] => 2
[feature] => AddUser
[feature_level] => 1
[parent_feature] => 1
)
[1] => Array (
[id] => 3
[feature] => EditUser
[feature_level] => 1
[parent_feature] => 1
)
)
[Candidate] => Array (
[0] => Array (
[id] => 5
[feature] => AddCandidate
[feature_level] => 1
[parent_feature] => 4
)
[1] => Array (
[id] => 5
[feature] => EditCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
)
A:
Here is a solution with demo. Might help you:
// $myArr is your origional array.
$result_arr = [];
array_walk($myArr,function($v,$k) use (&$result_arr){
$result_arr[key($v)][] = $v[key($v)];
});
print_r($result_arr);
Click Here for Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
curl up navigation on view based application in ios apps
i have faced some problem while navigating from one class to another with the curl-up animation style
i have did 2 test projects one with View based application & another navigation based application & also created 2 classes in each and a button on the first screen
following is my event handler for that button
-(IBAction)OnclickButton
{
SecondViewController * viewController = [[[SecondViewController alloc] initWithNibName:nil bundle:nil] autorelease];
[UIView transitionWithView:self.view.window
duration:1.0f
options:UIViewAnimationOptionTransitionCurlUp
animations:^{
[self.navigationController pushViewController:viewController animated:NO];
}
completion:NULL];
}
my problem is
project with navigation based template is working fine its navigating to second page with curl up animation ,,
but
in the project with navigation based template ,its not navigating to the second page on click of the button instead it will give curl up effect n reload the same page
why its happening so,, i am planing to apply this curl up animation to my existing project which is created in view based template
can any one tell where i gone wrong,,, how can i navigate with curl up animation(but not using the partial animation API)
thanx in advance
A:
B'coz you set self.view
transitionWithView:self.view.window
you need to change view which you call..
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare variables in Django Templates
I have two variables in my Django template file
like
{{orderitem.value.id}}
and `
{{ orderitem.order.id }}
I need to show some data if they are equal but i don’t know how to compare variables in html files .
please suggest.
A:
use ifequal tag to compare variables in templates:
sample:
{% ifequal orderitem.value.id orderitem.order.id %}
<p>are equals!<p/>
{% endifequal %}
| {
"pile_set_name": "StackExchange"
} |
Q:
Withholding data before save in Android
I'm not very sure of how to go about doing this, so I'm asking for some suggestions.
For starters, I have a activity that contains ClassA.java and ClassB.java.
ClassA has a button that, when tapped, goes into ClassB. ClassB then asks for input (1 Integer and 1 String), and then reverts back to ClassA, which displays what the user did on screen. I also want the user to be able to hit 'Save' when everything is done, back in ClassA.
Problem is, how do I go about storing that data temporarily and permanently? ClassB does not return anything, so I'm thinking the temporary storage of data should be done in ClassB, brought over to ClassA, then saved in a database if the user hits 'Save'.
Am I doing this the right way?
Also, am I right to call Android Bundles 'temporary storage'? They save the user's input temporarily, and if the application closes the Bundle is deleted (nothing is saved), right?
So would storing strings and integers in a Bundle and then transferring them to a database afterwards be theoretically correct and also be a possible way to tackle this problem?
Or does anyone have a better solution?
A:
If you want to withhold values permenantly, i.e.., Even after restarting the application, you want the data back to your application, then go for SharedPreferences
Shared Preferences
If you want to with hold temporarily and you want to pass the value from one Activity to another activity, You should pass intent and get the values from the bundle in the target activity.
Intent
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is my nav bar overlaying Fancybox and how can I fix it?
I've recently installed a photo gallery WordPress plugin on my school's website, and everything seems to be working except one thing: the navigation bar is overlaying images:
Everything seems to work in other themes.
Where and how can I fix this?
I'm running the latest version of Iceweasel that is in Debian's repos, but I've checked with other browsers too.
A:
try this one.
#fancybox-wrap {
position: absolute;
top: 0;
left: 0;
padding: 20px;
z-index: 9999;
outline: none;
display: none;}
| {
"pile_set_name": "StackExchange"
} |
Q:
display brightness problem with ubuntu 13.04
I have a Dell Inspiron 5520 with intel core i7 and AMD Graphics card. It used to work fine with Ubuntu 12.04 and Ubuntu 12.10. Now I tried to install Ubuntu 13.04 but i can't change display brightness: the FN keys don't change it, the indicator shows it always almost full, but won't change, won't increase or decrease. The same problem is there for both x86 and amd64 versions of Ubuntu.
What's the problem?
A:
I had the same problem, and solved after put this line:
GRUB_CMDLINE_LINUX="acpi_backlight=vendor"
in /etc/default/grub file, and after:
# update-grub && reboot
I have one Dell Vostro 3560 running Ubuntu 13.04 x86_64 kernel 3.8.0-19-generic
And I'm using generic X.Org video driver (opensource, tested)
A:
The following fixed the problem in my Acer laptop.
Open etc/default/grub with a root text editor
sudo -H gedit /etc/default/grub
Change
GRUB_CMDLINE_LINUX="acpi_backlight=vendor"
to
GRUB_CMDLINE_LINUX="quiet splash acpi_osi=Linux acpi_backlight=vendor"
After this run sudo update-grub and restart the system.
A:
Find video/graphics card in Ubuntu and Linux Mint
Run the command below in terminal to know what video card is used for the backlight/brightness:
ls /sys/class/backlight/
find graphics driver in Ubuntu
As you can see, the output for me is dell_backlight and intel_backlight. An indicator that the graphics card in use is Intel. Another way to find out the graphics card would be to go in System Settings->Details->Graphics. You can see the graphic card in use.
If your graphics card is Intel, you can proceed with the fix below.
Fix brightness control issue with Intel card in Ubuntu and Linux Mint:
Open a terminal and create the following configuration file, if it does not exist:
sudo touch /usr/share/X11/xorg.conf.d/20-intel.conf
Now we need to edit this file. You can use any editor be it a terminal one or graphical.
sudo gedit /usr/share/X11/xorg.conf.d/20-intel.conf
Add the following lines to this file:
Section "Device"
Identifier "card0"
Driver "intel"
Option "Backlight" "intel_backlight"
BusID "PCI:0:2:0"
EndSection
Save it. Log out and log in back. The brightness control should be working through function keys now:
Fix brightness control not working in Ubuntu 13.10
| {
"pile_set_name": "StackExchange"
} |
Q:
Drake Rigid_body_tree calculating the jacobian question
I am currently trying to calculate the jacobian of a kuka arm using the "rigid_body_tree.cc" file for the equation: Tau = J^T*F, where Tau is the 7 joint torques of the kuka arm, F is the cartesian forces and torques at the end-effector, and J^T is the jacobian transposed.
There exists a function in drake called transformPointsJacobian which takes in a cache, points, from_body_or_frame_ind, to_body_or_frame_ind, and in_terms_of_qdot.
The function first calculates the geometric Jacobian which outputs a 6x7 matrix (kuka has 7 joints)
Then, it takes that matrix and uses it to determine a 3x7 jacobian which is calculated below:
J.template block<kSpaceDimension, 1>(row_start, *it) = Jv.col(col);
J.template block<kSpaceDimension, 1>(row_start, *it).noalias() += Jomega.col(col).cross(points_base.col(i));
This shrinks down the 6x7 geometric jacobian into a 3x7 jacobian where the first 3 rows were calculated by Jv + Jw*Transformation.
This code definitely works, but I don't seem to understand why this step works. Also, since I will need the torques in the cartesian end-effector space, I will need the full 6x7 jacobian.
In order to get the last 3 rows of the jacobian, how can I use the output of the geometric jacobian so that it will be valid in the equation, Tau = J^T*F?
Thanks!
A:
Please consider switching to the supported class MultibodyPlant rather than the soon-to-be-deprecated RigidBodyTree in the Drake attic. The Jacobian documentation is much better there -- the group of methods is here. An example (with lots of documentation) is here; that one produces the 6x7.
Is there a reason you need to use the old code?
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this.getClass give it's own class name rather than Anonymous class name?
I have created anonymous class by implementing interface I inside public static void main() method. So, by java 8 for the abstract method test(), the implementation is provided from imple() method of class C.
So, inside public static void main() method, printing _interface.getClass(), I got
package_path.Main$$Lambda$1/310656974 which is absolutely fine. Bacause it print's the anonymous class name.
Also, _interface is pointing to an anonymous object in heap and hence I'm doing _interface.test();
So, the first statement that test() method has now is to print the class name,
But eventually what it print was,
package_path.C (telling me C is the class name). How is that possible? Shouldn't package_path.Main$$Lambda$1/310656974 be printed again? Because 'this' means anonymous inside the test method right?
@java.lang.FunctionalInterface
interface I {
void test();
}
class C {
void imple() {
System.out.println(this.getClass());
System.out.println("Inside Implementation");
}
}
class Main {
public static void main(String[] args) {
I _interface = new C()::imple;
System.out.println(_interface.getClass());
_interface.test();
}
}
A:
Hopefully, this might help you understand, that when you declare
I _interface = new C()::imple;
you've actually implemented the interface somewhat similar to (though not same as):
I _interface = new I() {
@Override
public void test() {
new C().imple(); // creating an instance of class `C` and calling its 'imple' method
}
};
Hence when the test method is called, it first creates an instance of C which prints
class x.y.z.C
as the class.
Because 'this' means anonymous inside the test method right?
Now as you can see above, there is no more anonymous class from which imple
is being called from, hence this is not representing the anonymous class anymore.
As Holger clarified in comments further, despite the representation as lambda or anonymous class at the calling site, the this.getClass() inside a method of class C will evaluate to C.class, regardless of how the caller looks like.
Recommend: Continue to read and follow on Is there any runtime benefit of using lambda expression in Java?
| {
"pile_set_name": "StackExchange"
} |
Q:
Return all words which have their reverse present in a string
Problem Statement:
Given a string of words return all words which have their reverse present in the string as ( (word1 , reverseword1 ) , (word2 ,reverseword2) )
Example Case:
Input:
Sachin tendulkar is the best tseb eht nihcaS
Output:
{ ( best , tseb ) , ( the , eht) , (Sachin , nihcaS) }
My approach is to use a map and return the words if a match to the reverse of the current word is found in the map.
#include<iostream>
#include<unordered_map>
#include<string>
using namespace std;
int main()
{
unordered_map <string, int> binMap;
string test="Sachin tendulkar is the best tseb eht nihcaS si";
int i=0,j=0;
string temp,rev;
string::iterator it;
cout<<"{";
for(i = 0, it = test.begin() ; it <= test.end(); ++it)
{
if(*it==' ' || it==test.end())
{
temp=test.substr(j,i-j);
rev=string(temp.rbegin(), temp.rend());
if(binMap[rev]==1)
cout<<"( "<<rev<<","<<temp<<" ), ";
else
binMap[temp]=1;
j=i+1;
}
i++;
}
cout<<"}";
return 0;
}
Is this the most optimal way to solve the problem or am I doing something wrong?
A:
I have observed a few things that may help you improve your code.
Use library functions
One of the things the code does is to separate words in the input. However, this could be done more easily by using a std::stringstream:
stringstream in(test);
string word;
while (in >> word) {
// test each word
}
Use more whitespace to enhance readability of the code
Instead of crowding things together like this:
cout<<"( "<<rev<<","<<temp<<" ), ";
most people find it more easily readable if you use more space:
cout << "( " << rev << ", " << word << " ) ";
Only print words once
Right now, with this input string:
string test="Sachin tendulkar is si is the best tseb eht nihcaS si";
The word "is" gets reported twice.
{( is,si ), ( best,tseb ), ( the,eht ), ( Sachin,nihcaS ), ( is,si ), }
One way to handle that is to note when each word is actually reported and to only do it once. Here's one way to do that:
stringstream in(test);
enum state { DETECTED=1, REPORTED };
unordered_map <string, state> binMap;
string word;
cout << "{";
while (in >> word) {
string rev{word.rbegin(), word.rend()};
if (binMap[rev] == DETECTED && binMap[word] != REPORTED) {
cout << "( " << rev << ", " << word << " ) ";
binMap[word] = REPORTED;
} else {
binMap[word] = DETECTED;
}
}
cout << "}\n";
| {
"pile_set_name": "StackExchange"
} |
Q:
I can't change TabBarViewController when I Have an assync request
I can't change my view until my request and to find and fill my object.
I tried to put my code assync with GCD. That don't work
override func viewDidLoad() {
getHeartStroke()
NotificationCenter.default.addObserver(forName:NSNotification.Name("HeartStrokeNotification"), object: nil, queue: nil, using: notificationFinish)
}
func getHeartStroke() {
AF.request("http://localhost:8080/heartstroke", method: .get, headers: nil).responseJSON(completionHandler: {response in
if (response.error == nil)
{
let json = JSON(response.result.value!)
DispatchQueue.global(qos: .userInitiated).async {
guard let hearstrokeArray = try? JSONDecoder().decode([HeartStroke].self, from: json.rawData()) else{
debugPrint("An error has occurred")
return
}
NotificationCenter.default.post(name:NSNotification.Name("HeartStrokeNotification"), object: hearstrokeArray, userInfo: nil)
}
}else{
NotificationCenter.default.post(name:NSNotification.Name("HeartStrokeErrorNotification"), object: nil, userInfo: nil)
}
})
}
func notificationFinish(notification:Notification) -> Void{
if (notification.name.rawValue == "HeartStrokeNotification"){
arrayHeartstroke = notification.object as! [HeartStroke]
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
With this code I stay block on my page until the end of getHeartStroke(), I expect to navigate in my app in same time of the fetch.
A:
What you need is a completion handler to handle this. Using the notification centre is just making your life difficult and complicated and could lead to unexpected behaviour. Here is some sample code:
func getHeartStroke(completionHandler: (_ heartStroke: [HeartStroke?], _ error: NSError?) -> ()) {
AF.request("http://localhost:8080/heartstroke", method: .get, headers: nil).responseJSON(completionHandler: {response in
if (response.error == nil)
{
let json = JSON(response.result.value!)
DispatchQueue.global(qos: .userInitiated).async {
guard let hearstrokeArray = try? JSONDecoder().decode([HeartStroke].self, from: json.rawData()) else{
debugPrint("An error has occurred")
return
}
completionHandler(hearstrokeArray, nil)
}
} else {
completionHandler(nil, response.error))
}
})
}
Then you can call it like so:
getHeartStroke { [weak self] (heartStrokeArray, error) in
guard let self = self else {return}
if error != nil {
self.processError(error)
} else {
self.processHeartStroke(heartStrokeArray)
}
}
processError and processHeartStroke will be functions that you should create to handle the heartStrokeArray and error objects.
These are standard callbacks or passing functions into functions. A lot of courses you find online seem to ignore callbacks but its definitely worth your time learning about them.
You can learn more about closures (completionHandler as one is named here) here: https://docs.swift.org/swift-book/LanguageGuide/Closures.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel v5.2 Pagination Display
I am using Laravel v5.2 and while displaying records I am using pagination. Pagination is working fine but I want to display it in an elegant format without using bootstrap, I am not able to figure out how to do the same. Presently, pagination links look as below(vertically):
I have tried to add some inline css along but the thing doesn't work except for positioning the same where I want.
<div style="position:absolute; top:300px; float:left;">{{$t->links()}}</div>
HTML that got rendered after page load:(for pagination)
<div style="position:absolute; top:300px; float:left;">
<ul class="pagination">
<li class="disabled"><span>«</span></li>
<li class="active"><span>1</span></li><li><a href="http://localhost/laravel-7/blog/public/t?page=2">2</a></li>
<li><a href="http://localhost/laravel-7/blog/public/t?page=3">3</a></li>
<li><a href="http://localhost/laravel-7/blog/public/t?page=2" rel="next">»</a></li>
</ul>
</div>
A:
Laravel puts a pagination class on the list, and that makes it easy to target the CSS. There are three important selectors you'll be using: .pagination, .pagination li, and .pagination a. These deal with the list itself, the items, and the links within the items.
Let's get started with some basic styling.
.pagination {
list-style: none;
padding-left: 0;
}
This removes the bullet points from all the list items, and some padding that is usually there by default.
Next, we make all the parts be on one line:
.pagination li {
display: inline-block;
}
That's pretty good, but they're crowded together, so let's space them out:
.pagination li + li {
margin-left: 1rem;
}
That targets every list item that has a previous list item and puts space to the left.
Now, I'm assuming that there will be a decently wide horizontal space that this pagination is in. To make things centered, add text-align: center to the .pagination.
That's the basics of it. If you don't want the links to look like plain links, you can mess with .pagination a:
.pagination a {
text-decoration: none;
padding: 0.2rem 0.4rem;
color: red;
border: 1px solid red;
border-radius: 2px;
}
You'll probably want to do some :hover, :focus, and :active styling, but this should get you started.
Here it is all together:
.pagination {
list-style: none;
padding-left: 0;
text-align: center;
}
.pagination li {
display: inline-block;
}
.pagination li+li {
margin-left: 1rem;
}
.pagination a {
text-decoration: none;
padding: 0.2rem 0.4rem;
color: red;
border: 1px solid red;
border-radius: 2px;
}
<div style="position:absolute; width: 300px; top:300px; float:left;">
<ul class="pagination">
<li class="disabled"><span>«</span></li>
<li class="active"><span>1</span></li>
<li><a href="localhost/laravel-7/blog/public/t?page=2">2</a></li>
<li><a href="localhost/laravel-7/blog/public/t?page=3">3</a></li>
<li><a href="localhost/laravel-7/blog/public/t?page=2" ; rel="next">»</a></li>
</ul>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu 17.04 and AMD Radeon R5 340X and Intel HD Graphics 4600
I had problems after install Ubuntu 17.04 several times, I think the problem is related to my 4 monitors and two video-cards: AMD Radeon R5 340X and Intel HD Graphics 4600.
I don't know why; during the initialization, two of them try to initialize but I realize one driver (I don't know which of them) does not initialize correctly, in such a way that the monitor's led blinks orange, like when there is no signal. After trying turning on the computer several times, suddenly all my 4 monitors worked fine!.
Is there a way to "save permanently" my "working fine" configuration? Here is my logs.
Thanks in advance!
A:
Everything related to my Monitors is in ~/.config/monitors.xml. Backing up this file and Storing it in a secure location should do the trick. As mentioned in the comments though, if you have intermittent problems saving a incorrect config isn't going to fix anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
LaTeX CV template not working probably
Sadly, I wasn't able to copy more than just the first of two errors:
! Package unicode-math Error: Cannot be run with pdfLaTeX!
(unicode-math) Use XeLaTeX or LuaLaTeX instead..
See the unicode-math package documentation for explanation.
Type H <return> for immediate help.
Here the full error:
I use LaTeX, and as far as I can see, they want me to use XeTeX. I don't know how to improve the CV to LaTeX code.
If you could give me some tips, links etc. in a comment, I would like to try to find a solution and update my question, so that you don't have to do the work all on your own!
A:
Well, please read the documentation of this template (please follow your given link).
There you will find:
Usage
At a command prompt, run
$ xelatex {your-cv}.tex
This should result in the creation of {your-cv}.pdf
Conclusion:
This template has to be compiled with XeLaTeX, because it is designed for it ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Different file_get_contents() result on different hostings
Code:
<?php
$string = file_get_contents($url);
var_dump($string);
?>
There are different results from file_get_contents() for two different hosts.
Is there any server configuration that I have to change?
A:
Try this:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => implode("\r\n", array(
'Accept-Charset: ISO-8859-1',
'Accept-Encoding: ',
)),
)));
$string= file_get_contents($url, null, $context);
var_dump($string);
| {
"pile_set_name": "StackExchange"
} |
Q:
API GateWay to server in ec2
I wanted to know if it possible that API GateWay sends data to a specific EC2 instance (my server)?
And how my server (that run codes in java) should get the data from the gateway?
Thank you,
Nofar.
A:
As the name indicates API gateway is just a gateway to your actual business logic. API gateway cannot run business logic code on it's on. You have to integrate API gateway with an integration point. This integration point can be another HTTP endpoint (REST service), another AWS service or a Lambda function.
So to achieve your requirement what you can do is to host a REST service with the logic you want to execute in your EC2 instance. You can integrate the service you hosted in EC2 via API gateway. API gateway will generate an HTTP endpoint for you, which in turn call the service you hosted in EC2. The API endpoint you should share to the outside world would be the end point generated by API gateway only. Please note you should add enough security to the service you hosted in EC2 instance for not get called directly. Please see below the different integration API gateway has,
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add "context" to Elastic Search suggestions
I'm building a Enterprise social network.
I want to suggest people to add as friend, based on their title.
For example, the value can be: developer, blogger, singer, barber, bartender ...
My users are saved into ElasticSearch, their titles are saved in the field 'title'.
The current mapping is:
title: {
type: 'text',
analyzer: 'autocomplete_analyzer',
search_analyzer: 'autocomplete_analyzer_search'
}
and the query is:
should: [
{
match: {
title: {
query: user.title,
minimum_should_match: '90%',
boost: 2
}
}
}
]
and the analyzers definitions are:
indexConfig: {
settings: {
analysis: {
analyzer: {
autocomplete_analyzer: {
tokenizer: 'autocomplete_tokenizer',
filter: ['lowercase', 'asciifolding']
},
autocomplete_analyzer_search: {
tokenizer: 'lowercase',
filter: ['asciifolding']
},
phrase_analyzer: {
tokenizer: 'standard',
filter: ['lowercase', 'asciifolding', 'fr_stop', 'fr_stemmer', 'en_stop', 'en_stemmer']
},
derivative_analyzer: {
tokenizer: 'standard',
filter: ['lowercase', 'asciifolding', 'derivative_filter', 'fr_stop', 'fr_stemmer', 'en_stop', 'en_stemmer']
}
},
tokenizer: {
autocomplete_tokenizer: {
type: 'edge_ngram',
min_gram: 2,
max_gram: 20,
token_chars: ['letter', 'digit']
}
},
filter: {
derivative_filter: {
type: 'word_delimiter',
generate_word_parts: true,
catenate_words: true,
catenate_numbers: true,
catenate_all: true,
split_on_case_change: true,
preserve_original: true,
split_on_numerics: true,
stem_english_possessive: true
},
en_stop: {
type: 'stop',
stopwords: '_english_'
},
en_stemmer: {
type: 'stemmer',
language: 'light_english'
},
fr_stop: {
type: 'stop',
stopwords: '_french_'
},
fr_stemmer: {
type: 'stemmer',
language: 'light_french'
}
}
}
}
}
I tested it, the relevance is very good, but they are not enough users matched by this, because of the '90%' criteria.
A quick and dirty solution is to lower this criteria to 50% of course.
However, If I do that, I suppose that Elastic will search titles based on the concordance of the letters in the title, rather that the relevance of the proximity between titles.
For example, If my user is a 'barber', ElasticSearch might suggest 'bartender', because they have in common: b,a,r,e,r
Hence, I have two questions:
1 - is my assumption correct ?
2 - what can I do to add more relevance on my titles search ?
A:
The problem with your search is following - it uses autocomplete_analyzer, which is basically creates a huge index with a lot of n-grams.
Example for bartender would be something like ba, bar, bart, etc.
As you could see, for barber you will have a bit similar n-grams, which would make a match.
Regarding your questions, if you would lower the minimum_should_match you will get more results, but that's just because the following matching procedure will lead to partial matches.
To increase the relevancy - I would recommend to use another analyzer, since this n-gram analyzer is usually suitable only for autosuggest functionality, which isn't the case. There could be several choices from keeping it simple to keyword analyzer, or whitespace one.
What would be more important is to properly construct the query. For example if user searches for partial title, e.g bar, you may use prefix query. However, if you're searching just by full match (e.g. developer or bartender) it would be more important to just normalize title field properly. E.g. to use lowercase analyzer with some stemming.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple tenants in Sharepoint Online- PRO and DEV
We have one tenant for the company in Sharepoint Online, and we're working in integrating new services.
We have got the following piece of advice:
Why not use a DEV tenant to make your changes, and test and avoid problems.
As far as i know, it shoud be:
company.sharepoint.com
company-dev.sharepoint.com
Ok, it seems a good idea, but we aren't sure how to acomplish it.
How can i get this scenario?
It would great to have the same accounts in both tenants, but i'm not so sure that it could be possible.
What would be best practices for this scenario?
A:
You will have to pay for the separate tenant, but you can try and create a developer tenancy which will be free for a year:
https://dev.office.com/devprogram
https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment
You will need to use AAD Connect to integrate on-premises users.
https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt: Best control for displaying chat messages
I have been trying to use a textBrowser in order to display chat messages in my application. I've set the textBrowser with HTML enabled. I'm then appending each message to the textBrowser like so:
ui->textBrowser->append(QString().sprintf("<div style=\"border-bottom:1px solid #eeeeee; background-color:#ffffff;display:block;\"><font color=\"red\"> %s</font></div>",msg.toStdString().c_str()));
However, I am limited in what CSS i can apply to each appended element. For example;
- Border does not work
- Display block does not work
- etc.
I'm now fairly certain that the textBrowser just does not have the power that i need, I'm aiming in creating a chat message much like Skype is doing it.
What would be the best control to use for this purpose?
Some ideas I have so far:
- Use a scrollArea and append widgets inside of them
- Use a listView (not sure if its possible to style it the way i want)
Key elements i want to include in each chat message are:
- Time
- Avatar picture
- Name
- Text message
Any ideas what the best approach would be here?
Edit
Unfortunately i cant attach an image yet since I'm still new here.
A:
I think you could simply use the WebKit (WebView) component. That will allow you to do anything you need and more. Styling and layout is done like a regular HTML/CSS page, then you can integrate it to the application backend via JavaScript.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does spark-shell --master yarn-client fail (yet pyspark --master yarn seems to work)?
I'm trying to run the spark shell on my Hadoop cluster via Yarn.
I use
Hadoop 2.4.1
Spark 1.0.0
My Hadoop cluster already works. In order to use Spark, I built Spark as described here :
mvn -Pyarn -Phadoop-2.4 -Dhadoop.version=2.4.1 -DskipTests clean package
The compilation works fine, and I can run spark-shell without troubles. However, running it on yarn :
spark-shell --master yarn-client
gets me the following error :
14/07/07 11:30:32 INFO cluster.YarnClientSchedulerBackend: Application report from ASM:
appMasterRpcPort: -1
appStartTime: 1404725422955
yarnAppState: ACCEPTED
14/07/07 11:30:33 INFO cluster.YarnClientSchedulerBackend: Application report from ASM:
appMasterRpcPort: -1
appStartTime: 1404725422955
yarnAppState: FAILED
org.apache.spark.SparkException: Yarn application already ended,might be killed or not able to launch application master
.
at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApp(YarnClientSchedulerBackend.scala:105
)
at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:82)
at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:136)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:318)
at org.apache.spark.repl.SparkILoop.createSparkContext(SparkILoop.scala:957)
at $iwC$$iwC.<init>(<console>:8)
at $iwC.<init>(<console>:14)
at <init>(<console>:16)
at .<init>(<console>:20)
at .<clinit>(<console>)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
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.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:788)
at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1056)
at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:614)
at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:645)
at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:609)
at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:796)
at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:841)
at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:753)
at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:121)
at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:120)
at org.apache.spark.repl.SparkIMain.beQuietDuring(SparkIMain.scala:263)
at org.apache.spark.repl.SparkILoopInit$class.initializeSpark(SparkILoopInit.scala:120)
at org.apache.spark.repl.SparkILoop.initializeSpark(SparkILoop.scala:56)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1$$anonfun$apply$mcZ$sp$5.apply$mcV$sp(SparkILoop.scala:913)
at org.apache.spark.repl.SparkILoopInit$class.runThunks(SparkILoopInit.scala:142)
at org.apache.spark.repl.SparkILoop.runThunks(SparkILoop.scala:56)
at org.apache.spark.repl.SparkILoopInit$class.postInitialization(SparkILoopInit.scala:104)
at org.apache.spark.repl.SparkILoop.postInitialization(SparkILoop.scala:56)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply$mcZ$sp(SparkILoop.scala:930)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:884)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:884)
at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:884)
at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:982)
at org.apache.spark.repl.Main$.main(Main.scala:31)
at org.apache.spark.repl.Main.main(Main.scala)
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.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:292)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:55)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Spark manages to communicate with my cluster, but it doesn't work out.
Another interesting thing is that I can access my cluster using pyspark --master yarn. However, I get the following warning
14/07/07 14:10:11 WARN cluster.YarnClientClusterScheduler: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient memory
and an infinite computation time when doing something as simple as
sc.wholeTextFiles('hdfs://vm7x64.fr/').collect()
What may be causing this problem ?
A:
Please check does your Hadoop cluster is running correctly.
On the master node next YARN process must be running:
$ jps
24970 ResourceManager
On slave nodes/executors:
$ jps
14389 NodeManager
Also make sure that you created a reference (or copied those files) to Hadoop configuration in Spark config directory :
$ ll /spark/conf/ | grep site
lrwxrwxrwx 1 hadoop hadoop 33 Jun 8 18:13 core-site.xml -> /hadoop/etc/hadoop/core-site.xml
lrwxrwxrwx 1 hadoop hadoop 33 Jun 8 18:13 hdfs-site.xml -> /hadoop/etc/hadoop/hdfs-site.xml
You also can check ResourceManager Web UI on port 8088 - http://master:8088/cluster/nodes. There must be a list of available nodes and resources.
You must take a look at your log files using next command (application ID you can find in Web UI):
$ yarn logs -applicationId <yourApplicationId>
Or you can look directly to entire log files on Master/ResourceManager host:
$ ll /hadoop/logs/ | grep resourcemanager
-rw-rw-r-- 1 hadoop hadoop 368414 Jun 12 18:12 yarn-hadoop-resourcemanager-master.log
-rw-rw-r-- 1 hadoop hadoop 2632 Jun 12 17:52 yarn-hadoop-resourcemanager-master.out
And on Slave/NodeManager hosts:
$ ll /hadoop/logs/ | grep nodemanager
-rw-rw-r-- 1 hadoop hadoop 284134 Jun 12 18:12 yarn-hadoop-nodemanager-slave.log
-rw-rw-r-- 1 hadoop hadoop 702 Jun 9 14:47 yarn-hadoop-nodemanager-slave.out
Also check if all environment variables are correct:
HADOOP_CONF_LIB_NATIVE_DIR=/hadoop/lib/native
HADOOP_MAPRED_HOME=/hadoop
HADOOP_COMMON_HOME=/hadoop
HADOOP_HDFS_HOME=/hadoop
YARN_HOME=/hadoop
HADOOP_INSTALL=/hadoop
HADOOP_CONF_DIR=/hadoop/etc/hadoop
YARN_CONF_DIR=/hadoop/etc/hadoop
SPARK_HOME=/spark
| {
"pile_set_name": "StackExchange"
} |
Q:
Get filename from current image
can anybody tell me how I can get the current image filename. I have to link the current image to open it in a lightbox.
My code:
15 = TEXT
15 {
field = image
split {
token = ,
cObjNum = 1 || 3 || 3
//ignore
1....
3 {
10 = IMAGE
10.file.import.current = 1
10.file.import = uploads/pics/
10.file.maxW = 270
10.params = class="hidden"
10.imageLinkWrap = 1
10.imageLinkWrap {
enable = 1
typolink.parameter = TEXT
typolink.parameter.field = image
typolink.parameter.listNum.splitChar = ,
typolink.parameter.listNum = // <- Need current image number
typolink.parameter.wrap = /uploads/pics/|
A:
You should have some special vars set during img mainpulation. From TYPO3 wiki
IMG_RESOURCE:
While rendering an img_resource TYPO3 sets TSFE:lastImgResourceInfo which is a numerical array of image information
TSFE:lastImgResourceInfo|0 contains the width (after scaling) of the image
TSFE:lastImgResourceInfo|1 contains the height (after scaling) of the image
TSFE:lastImgResourceInfo|2 contains the image file extension
TSFE:lastImgResourceInfo|3 contains the path to the (scaled) image file
TSFE:lastImgResourceInfo|origFile contains the name (path?) of the original file
TSFE:lastImgResourceInfo|origFile_mtime contains the the last modification time of the original file
So you can use them for example with data
10 = TEXT
10.data = TSFE:lastImgResourceInfo|3
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a unique array of json objects with sort on a field?
How can I filler the below array on common id and output should have unique and latest history number
const input = [{
"id": 134116,
"user": "admin",
"historyno": "134116-0"
}, {
"id": 134132,
"user": "admin",
"historyno": "134132-0"
}, {
"id": 134132,
"user": "admin",
"historyno": "134132-1"
}, {
"id": 134133,
"user": "admin",
"historyno": "134133-0"
}, {
"id": 134133,
"user": "admin",
"historyno": "134133-1"
}];
let output = [];
let tempId;
for (let i = 0; i < input.length; i++) {
if (input[i].id === tempId) {
//do nothing
} else {
output.push(input[i]);
tempId = input[i].id;
}
}
console.log(output);
Expected Output
[
{
"id": 134116,
"user": "admin",
"historyno": "134116-0"
},
{
"id": 134132,
"user": "admin",
"historyno": "134132-1"
},
{
"id": 134133,
"user": "admin",
"historyno": "134133-1"
}
]
A:
Reduce the array to a Map, using the id as key, and then convert back by spreading the Map.values() iterator to an array.
This solution assumes that the array is presorted by history numbers:
const input = [{"id":134116,"user":"admin","historyno":"134116-0"},{"id":134132,"user":"admin","historyno":"134132-0"},{"id":134132,"user":"admin","historyno":"134132-1"},{"id":134133,"user":"admin","historyno":"134133-0"},{"id":134133,"user":"admin","historyno":"134133-1"}];
const output = [...input.reduce((r, o) => r.set(o.id, o), new Map).values()];
console.log(output);
This solution handles unsorted arrays by only replacing the current item in the map if historyno is greater:
const input = [{"id":134116,"user":"admin","historyno":"134116-0"},{"id":134132,"user":"admin","historyno":"134132-0"},{"id":134132,"user":"admin","historyno":"134132-1"},{"id":134133,"user":"admin","historyno":"134133-0"},{"id":134133,"user":"admin","historyno":"134133-1"}];
const getHistoryNo = ({ historyno }) => +historyno.split('-')[1];
const output = [...input.reduce((r, o) => {
const prev = r.get(o.id);
if(!prev || getHistoryNo(o) > getHistoryNo(prev)) r.set(o.id, o);
return r;
}, new Map).values()];
console.log(output);
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the Percentage of a Group of Items / Total Items
This may sound very stupid, but my brain stuck and I can't get it Right.
What I have:
10 Categories in which a number of Items (Item1, Item2, Item3) are stored.
In a Category there can be 0 or 100000 Items.
What I want:
Based on the item's in the Category, I want to find the Percentage every Category takes up.
These are the variables i have:
$category1_items <- All items of an Individual Category
$all_items <- All Items (#)
$all_categories <- All Categories (#)
I need to calculate $category1_percentage (and of every other category) so that i can display the Percentage of each individual Category.
I can add any other variable i need.
Can someone help me ?
A:
$category1_items / $all_items $\cdot 100$
| {
"pile_set_name": "StackExchange"
} |
Q:
Ending a song with a dominant chord
As far as i know, almost all songs end in the tonic chord, because this is the most "stable" condition. On the other hand, a dominant chord at the end of a progression (or song) sounds "incomplete".
However, i have found several songs that end with a V chord, and it sounds fine. (A Chinese folk song titled Mo Li Hua is one notable example). In my observation on these songs, i found a common thread: the last V chord is preceded by a II maj chord (i.e the secondary dominant V/V chord). Is this really a common characteristic of this group of songs (or is it a coincidence)... and what else would make "ending at a V chord" more "stable"?
A:
The making the ii chord major turns it into a secondary dominant of V (V/V) which makes V a temporary tonic. If you are ending on V in this case you would technically end on a tonic although it is not the tonic present though the rest of the piece.
I wouldn't go as far as calling ending on V unstable as it is a very typical cadence that can be seen in many pieces. The effect I would describe instead is that ending on V (or a half cadence) makes a piece seem like it's going to continue or there's more to the piece then there is. This isn't necessarily a bad thing and can even be used to create a type of "musical cliffhanger". I know I've used it that way in my own songwriting especially if I wanted the end of a song to be kind of ambiguous.
It should be noted however that the chord chosen to end a piece is only one of the things that constitutes the ending of a piece and how it overall feels. I guarantee that the same ending progression (cadence) can feel complete (stable) or incomplete (unstable) depending on how it is approached.
A:
Preceding the V chord with a II chord is actually a perfect way to make it more stable. When using a secondary dominant chord, the song's key is momentarily substituted by the key of the fifth, which means that the II chord functions as a dominant chord for a moment. Hence the V/V notation, and the "secondary dominant" name. A logical consequence is that the following V chord sounds much more stable than it usually would (when preceded by a IV, for instance). In many cases, the V chord resolves to I, which results in two consecutive chords relieving tension.
That last part is not necessary though. It's perfectly alright to end a song with II followed by V, which is relatively stable.
A:
Ending a tune on the dominant chord is a common technique for performers to keep the suspense and interest going in a given set. Usually that dominant chord will have some relationship to the key of the succeeding tune. (You are in C, end on G, then take off on a tune in G or D or G minor, etc.) It can be over-used, of course.
I have also used this device on the final song of the show, making for a neurologically disturbing conclusion to the performance that can reverberate for the audience "until next time."
That is different than when a series of changes at the end of a piece scrambles or changes the key feel so that the ostensible dominant chord really functions as a particularly thrilling concluding chord that somehow sounds right.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convergence of a geometric sequence
I am not sure if there is such thing as testing for convergence a geometric sequence, but I have a problem in my book that asks to test for the convergence or divergence of a sequence:
$\lim\limits_{n \to \infty} \frac{2^n}{3^{n-1}}$
Can I use the same method used to test a geometric series for this sequence?
So rearranging:
$\lim\limits_{n \to \infty} 2(\frac{2}{3})^{n-1}$
So in this case a=2 and r=$\frac{2}{3}$ so my sequence would converge as my r is within -1 and 1?
Is this thinking wrong? If so what method should I be applying to solve this?
Thank you!
A:
For any geometric series, if $|r|<1$, then your series will converge. Your reasoning is perfectly sound. If a series converges, then the limit of its corresponding sequence is zero.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the value of onclick in jquery
There are many topics on this and I have tried the solutions, but nothing is working. I am not a javascript developer, so might be not able to figure out.
I have a onclick function in my html (php template file)
<a href="javascript:;" onclick="AddFav({$id});" title="Add to Favs">Fav</a>
On click, jquery ajax function is being called and on success, I want to change the value of onclick to RemoveFav({$id}. I am changine the value of title with .attr.
$('div#fav-'+ id +' a').unbind('click').removeAttr('onclick').click(RemoveFav(id););
Please do help me with the same.
A:
.click need a callback function.
$('div#fav-'+ id +' a').unbind('click').removeAttr('onclick').click(function(e) {
e.preventDefault();
RemoveFav(id);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
MPDF undefined index error
I am using MPDF library to convert HTML to PDF.
Here is my code.
$HTML = '{HTML CONTENT GOES HERE}'; //HTML STRING
$MPDF->WriteHTML($html); // Converting
$MPDF->Output('preview.pdf','F'); //Saving to a File
It works , but generating too much errors in error log ,
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: BODY C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: BODY>>ID>> C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined offset: -1 C:\wamp\www\crm\application\libraries\mpdf.php 14421
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined variable: cstr C:\wamp\www\crm\application\libraries\mpdf.php 31951
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14280
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: DIV>>CLASS>>PRINTWRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14284
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: DIV>>ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242
anybody have some working experience with this library ? (If it only outputs some errors then we can fix it by changing on the library , but here it gives too much error) , i think that i am missing something.
Please help me.
Thanks.
A:
Add following at top of mpdf.php
error_reporting(0);
This will resolved the issue.
A:
Is the HTML well formed, and also are all the tags and attributes either all lowercase or all uppercase? Here are the requirements for the HTML as per MPDF documentation:
Example of an HTML attribute: <div align="center">
mPDF supports attribute values in single or double quotes e.g. <div align="center"> or <div align='center'>
Minimised attributes are not supported e.g. <input type="checkbox" disabled />
XHTML specification is recommended for best compliance with mPDF.
Also per https://mpdf.github.io/html-support/html-tags.html
you seem to be using tags that are not supported. BODY for instance is not.
I would try to limit my HTML to the ones on the documented list and and follow their well formed guidelines and see if the errors get fixed that way. They are only 'notices' so nothing severe, but it would be best to fix them just in case future versions are not as forgiving.
| {
"pile_set_name": "StackExchange"
} |
Q:
python: outfile to another text file if exceed certain file size
I using scapy with python in ubuntu. I would like to ask if anyone would know how to code the example:
let say I have two text files which are writing while the script is running then I would like to check the file is exceed example 500bytes, if does then it will store whatever in the file and create a new text file to write. (output1.txt, output2.txt,etc..)
Would be appreciated if any expertise will help. Thanks
part of my code is:
file = open("output.txt","w")
def example(p):
if p.haslayer(Dot11Beacon):
if p.addr2 not in uniqueAP:
file.writelines(p.addr2 + "\n")
so while the script is running in the terminal, it will write it into the file called output.txt but i would want to improve the script to check file size of the text file and if exceed it would stop writing in the current and create a new output2.txt for example and continue.
A:
A simple example if you don't want to use RotatingFileHandler.
You should use os.stat('filename').st_size to check file sizes.
import os
import sys
class RotatingFile(object):
def __init__(self, directory='', filename='foo', max_files=sys.maxint,
max_file_size=50000):
self.ii = 1
self.directory, self.filename = directory, filename
self.max_file_size, self.max_files = max_file_size, max_files
self.finished, self.fh = False, None
self.open()
def rotate(self):
"""Rotate the file, if necessary"""
if (os.stat(self.filename_template).st_size>self.max_file_size):
self.close()
self.ii += 1
if (self.ii<=self.max_files):
self.open()
else:
self.close()
self.finished = True
def open(self):
self.fh = open(self.filename_template, 'w')
def write(self, text=""):
self.fh.write(text)
self.fh.flush()
self.rotate()
def close(self):
self.fh.close()
@property
def filename_template(self):
return self.directory + self.filename + "_%0.2d" % self.ii
if __name__=='__main__':
myfile = RotatingFile(max_files=9)
while not myfile.finished:
myfile.write('this is a test')
After running this...
[mpenning@Bucksnort ~]$ ls -la | grep foo_
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_01
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_02
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_03
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_04
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_05
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_06
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_07
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_08
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_09
[mpenning@Bucksnort ~]$
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP $-SESSION variables disappear on new page and return empty
I'm having an issue with the Sessions Variables. Ever since i switched from mysqli to PDO. It worked fine with mysqli, but ever since i switched to PDO, this issue has now come forward.
I'm trying to login and i have an area, where i want to make sure that the user can only see, if the user is logged in. The login works fine, but as soon as i get referred to my index file, i don't see anything, because of the logged in function. I can see the $_SESSION Variable gets filled, but as soon as i redirect to another file, the $_SESSION Variables disappear and i get an empty Array:
Array
(
)
process_login.php
require_once('../inc/user.inc.php'); // here i have all my functions
$user = new User(); // New Instance of my User Class
$user -> sec_session(); // selfmade session function. I use start_session() in this function
if (isset($_POST['email'], $_POST['p'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$password = filter_var ($_POST['p'], FILTER_SANITIZE_STRING);
$login = $user -> login_user($email, $password);
if ($login) {
// Login sucessful
//print("<pre>".print_r($_SESSION,true)."</pre>"); //Here i get my $_SESSION variable printed out and it works. I see it is filled.
header('Location: ../index.php');
exit();
}
index.php
<?php
$title = 'Index';
$currentPage = 'Dashboard';
include('php/head.php');
require_once('../inc/user.inc.php');
$user = new User();
$user -> sec_session(); // here i call my session function again. Note: session_start() is included in this function
print("<pre>".print_r($_SESSION,true)."</pre>"); //Now The Array is empty?!?
?>
user.inc.php - sec_session function
protected function sec_session() {
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
Whilst logging in, i set the Session to the following in my login function:
if ($db_password == $password) {
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
return true;
}
This above works all fine, but only disappears, when i land in my index.php and i know there is something worng, but i have no idea what it is.
A:
Are you using http or https to access your local site? If you are using secure cookies PHP won't read them under http instead it starts a new session with a new cookie, switching to https solves this problem.
It looks from your sec_session function that you are using secure cookies ($secure = SECURE;) so is your browser session using HTTPS? If you are using HTTP with secure cookies you will start a new session on each page and won't have access to existing session variables.
The best solution is to access your local site with https just like you would for your live site but if you switch off the secure cookie setting for your local site that will work too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Combinación de números y letras en JComboBox
En un JFrame tengo el diseño para imprimir el formato con la información de la base de datos. Tengo un ComboBox con el que se selecciona la "operación" y conforme a esa selección se llenan todos los campos correspondientes, me muestra bien cuando selecciono en el ComboBox un ítem numérico, el problema surge cuando tiene una letra, por ejemplo:
No. operación: 27.2
La muestra de forma correcta.
No. operación: 27.A
Marca error que es el siguiente:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'A' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
...
En un método lleno el ComboBox que es el siguiente:
public void combo() {
try {
stat1 = cn.prepareCall("SELECT DISTINCT noOperacion FROM dibujos");
resultado = stat1.executeQuery();
if (resultado != null) {
DefaultComboBoxModel modeloNoOperacion = new DefaultComboBoxModel();
while (resultado.next()) {
modeloNoOperacion.addElement(resultado.getString("noOperacion"));
}
comboOperaciones.setModel(modeloNoOperacion);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
... y en el método mostrar lleno todos los componentes con lo seleccionado en el ComboBox.
Mis sentencias para los componentes son:
String sql = "SELECT referencia, noParte, cantidad, nombreNoParte, sufijo1, sufijo2, sufijo3, sufijo4, sufijo5 FROM dibujos WHERE noOperacion=" + comboOperaciones.getSelectedItem();
String sql1 = "SELECT noOperacion, notas, añoModelo, descripcionOperacion, departamento, nota FROM dibujos WHERE noOperacion=" + comboOperaciones.getSelectedItem();
String sql2 = "SELECT dibujos1, dibujos2 FROM dibujos WHERE noOperacion=" + comboOperaciones.getSelectedItem();
¿Me podrían dar una idea de cómo solucionar este problema? y que me muestre ¿Cuándo se tiene una letra en el campo de noOperacion?
A:
La sintaxis es incorrecta porque noOperación se trata de un varchar por lo tanto el valor va entre comillas simples.
Deberias construir tu consulta de esta manera:
String sql1 = "SELECT noOperacion, notas, añoModelo, descripcionOperacion, departamento, nota FROM dibujos WHERE noOperacion= '" + comboOperaciones.getSelectedItem(); + "'"
| {
"pile_set_name": "StackExchange"
} |
Q:
Design pattern to integrate Rails with a Comet server
I have a Ruby on Rails (2.3.5) application and an APE (Ajax Push Engine) server. When records are created within the Rails application, i need to push the new record out on applicable channels to the APE server. Records can be created in the rails app by the traditional path through the controller's create action, or it can be created by several event machines that are constantly monitoring various inputstream and creating records when they see data that meets a certain criteria.
It seems to me that the best/right place to put the code that pushes the data out to the APE server (which in turn pushes it out to the clients) is in the Model's after_create hook (since not all record creations will flow through the controller's create action).
The final caveat is I want to push a piece of formatted HTML out to the APE server (rather than a JSON representation of the data). The reason I want to do this is 1) I already have logic to produce the desired layout in existing partials 2) I don't want to create a javascript implementation of the partials (javascript that takes a JSON object and creates all the HTML around it for presentation). This would quickly become a maintenance nightmare.
The problem with this is it would require "rendering" partials from within the Model (which im having trouble doing anyhow because they don't seem to have access to Helpers when they're rendered in this manner).
Anyhow - Just wondering what the right way to go about organizing all of this is.
Thanks
A:
After talking w some folks in #rails and #ape this is appears to be the best approach to this issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Type mismatch using Yesod and Persistent
I'm trying to make a Persistent query in a Yesod app:
userDetails :: UserId -> HandlerT app IO (Maybe UserDetail)
userDetails uid = do
profile <- getBy $ UniqueUser uid
return $ undefined -- the rest of this type checks
and I am getting a type error on the getBy line:
Couldn't match type `PersistMonadBackend (HandlerT App IO)'
with `persistent-1.3.0.6:Database.Persist.Sql.Types.SqlBackend'
Expected type: PersistMonadBackend (HandlerT App IO)
Actual type: PersistEntityBackend Profile
So, checking the type in ghci:
:t getBy (UniqueUser undefined)
getBy (UniqueUser undefined)
:: ( PersistUnique m,
, PersistMonadBackend m ~ persistent-1.3.0.6:Database.Persist.Sql.Types.SqlBackend
) => m (Data.Maybe.Maybe (Entity Profile))
But, the thing is, I defined Profile as:
Profile
name Text
email Text
user UserId
UniqueUser user
UniqueEmail email
in my 'config/model' file. What's going on and how do I fix it?
A:
You need to use runDB around your persistent call.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.