text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to style specific a tag
I have a lot of links look something like this:
<a href="http://www.youtube.com/user/nigahiga">Youtube</a>
<a href="http://pinterest.com/pin/41236152807615600/">Pinterest</a>
<a href="https://www.facebook.com/manchesterunited">Facebook</a>
<a href="http://www.youtube.com/user/RayWilliamJohnson">Youtube</a>
<a href="http://pinterest.com/pin/24910604158520050/">Pinterest</a>
How can I style only the hyperlinks that will be linked to pinterest. I tried this:
$('a').attr('href').contains('pinterest').css('Styling here');
But it does not work. How to achieve it?
A:
You can use attribute contains selector:
$('a[href*="pinterest"]').css('color','DeepSkyBlue');
or better just need pure css:
a[href*="pinterest"] {
color: DeepSkyBlue;
}
Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Needed environment for building gstreamer plugins in Windows
I've been strugling for two weeks to create an environment for building a gstreamer plugin on windows (needed for a songbird addon).
I've installed MSYS, MinGW and Cygwin, then installed GStreamer OSSBuild, and I also downloaded the sources for Songbird, which come with their own precompiled version of gstreamer.
I was unable to run gst-inspect (or any other gstreamer applications) from the songbird sources and I figured I will settle for OSSBuild (as I was able to run gst-inspect from the compiled OSSBuild).
When following the instructions for building a GST plugin (found here) through, cygwin will not recognize the OSSBuild and the build fails when running autogen, with the following error:
checking for GST... no
configure: error:
You need to install or upgrade the GStreamer development
packages on your system. On debian-based systems these are
libgstreamer0.10-dev and libgstreamer-plugins-base0.10-dev.
on RPM-based systems gstreamer0.10-devel, libgstreamer0.10-devel
or similar. The minimum version required is 0.10.16.
configure failed
I could also not use MSYS or MinGW as they are unable to run autogen at all.
I understand that cygwin should have it's own gstreamer development packages but I couldn't find how to install them.
My question: How do I install the gstreamer packages in cygwin or how do I build using cygwin with the OSSBuild dependencies?
In short, how do I get an environment where I can build a gstreamer plugin under windows?
A:
you can install precompiled gstreamer packages for cygwin at cygwinports. there you will find installation instructions and a list of available packages. you should not need to build them from source.
| {
"pile_set_name": "StackExchange"
} |
Q:
NServiceBus Endpoint Routing Injection
I am trying to inject my own IRouteMessagesToEndpoints in NServiceBus with structure map as I need to redirect various messages to different endpoints depending on some business logic (not via namespace/assembly/type). This would allow it to fire using bus.Send(); and be configured to our requirements. I thought this was possible, but I can't seem to get it to work. I have tried using the Configure.Component() and ObjectFactory.Configure() for the injection, and both run without any exception, but when I debug my implementation of the interface the breakpoint does not hit.
My question is, can it be done this way (there's nothing on the internet that covers this)? I notice that the EndPointRouter in the GatewayReceiver has a setter, but I cannot work out how to access the property.
A:
Unfortunately, even though IRouteMessagesToEndpoints is a public interface at the moment is not possible to replace the default implementation, sorry!
Please raise an issue about it in https://github.com/Particular/NServiceBus.Gateway/issues/new so we can discuss it better.
| {
"pile_set_name": "StackExchange"
} |
Q:
Applying the Lagrangian function to find critical points
So I have the following function
$$ f(x,y) = x^2+y^2 $$
subject to
$$ g(x,y) = x+y-1 = 0. $$
And I have to use the Lagrangian to find the critical points, and determine wether they are constrained minima, constrained maxima or neither.
I am starting on this guy right now. I have no clue, and any hints would be great (not necessarily an answer). Im on wikipedia, which is making me more confused right now!
A:
For your better reading, I'll follow the notation used on wikipedia.
Let $(x,y)\in \Bbb R^2$.
Start of by defining $\Lambda(x,y,\lambda):=f(x,y)+\lambda g(x,y)$.
Then find $\dfrac{\partial\Lambda }{\partial x}(x,y,\lambda), \dfrac{\partial\Lambda }{\partial y}(x,y,\lambda)$ and $\dfrac{\partial\Lambda }{\partial \lambda}(x,y,\lambda)$:
$$\begin{align} \dfrac{\partial\Lambda }{\partial x}(x,y,\lambda)&=2x+\lambda\\
\dfrac{\partial\Lambda }{\partial y}(x,y,\lambda)&=2y+\lambda\\
\dfrac{\partial\Lambda }{\partial \lambda}(x,y,\lambda)&=x+y-1 .\end{align}$$
Next solve the system:
$$\begin{align} \begin{cases}\dfrac{\partial\Lambda }{\partial x}(x,y,\lambda)&=0\\
\dfrac{\partial\Lambda }{\partial y}(x,y,\lambda)&=0\\
\dfrac{\partial\Lambda }{\partial \lambda}(x,y,\lambda)&=0 \end{cases}&\iff \begin{cases}\\2x+\lambda=0\\
2y+\lambda=0\\
x+y-1=0 \end{cases}\\
&\iff \begin{cases}\\2x=-\lambda\\
2y-2x=0\\
x+y-1=0 \end{cases}\\
&\iff \begin{cases}\\2x=-\lambda\\
x=y\\
2x=1 \end{cases}\\
&\iff x=\dfrac 1 2=y \land \lambda =-1.\end{align}$$
Thus finding the set of critical points: $\left\{(x,y)\in \Bbb R^2\colon x=\dfrac 1 2 = y\right\}=\left\{\left(\dfrac 1 2, \dfrac 1 2\right)\right\}$.
From here I'll let you make the final conclusions.
In order to verify the conclusions you find, note that $x+y-1=0\iff y=1-x$, so you can just replace $y$ with $1-x$ in $f$ and you have reduced the problem to a single variable which you should know how to solve.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can JavaScript be expressly used to develop Unity games?
I would like an authoritative answer on a point that has been a question mark for me for a little while. There seems to be a frequent use of the term JavaScript to mean or describe UnityScript.
I have been told time and again that you can use actual JavaScript to develop games in Unity, however from what I understand UnityScript could, at best, be described as a superset of JavaScript, but there really are some items that perhaps aren't completely compatible and you can't simply use JS as you normally would to develop Unity games as you would have to follow their conventions.
Am I wrong about this? Can you actually use pure JS and its conventions directly to make Unity games outside of following the parameters that UnityScript has set?
A:
Short answer: No you cannot use PURE JavaScript. As far an I am aware - Unity uses it's own JS-like syntax (some people refer to it as Unity JS) but it is most commonly known as UnityScript.
Your question arises from the fact that the Unity community refers to JavaScript and UnityScript as if they are equivalent and interchangeable.
Whilst these look and feel extremely similar - there are some fundamental differences such as UnityScript being class-based whilst JavaScript doesn't support classes.
You can definitely use prior JavaScripting conventions you have picked up within UnityScript as a LOT of it applies. The semantics used are a little different - but I've found it doesn't take long to pick up on the small changes.
Read more about it here: UnityScript versus JavaScript
Happy coding!
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it a good idea to show a warning to users who are typing tags incorrectly?
On our site, we have a tag field that looks like the following:
Today, while looking at some of our users interacting with the site, I noticed that one of them had used only spaces to separate their tags, instead of using commas as the input field advises (he probably did not see the advice and applied his idea of how tags should be typed in).
This raised a concern: are we going to get many users that fail to read the advice and end up typing in tags by only separating them with spaces (which would lead to having a huge single tag) and if so, should we try to do something about it by educating the user about the problem?
I thought that we could make the field detect if the user has entered no commas in the field and check for the presence of more than one space, and if the condition is met display a warning that would say something along the lines of "You might be typing in your tags incorrectly. Are you using commas to separate them?".
If we didn't tell our user about this issue they would probably have a hard time noticing and correcting the issue after submitting their entry, because the only difference between well-formed tags and "huge chunk" tags is the amount of space that goes between them, a thing which a novice and uneducated user might miss.
Is it a good idea to try to prevent this behavior and try to educate the user a priori? Are we taking the right approach?
A:
One way to guide the user would be to style the tags as soon as the users finish typing a tag, thus indicating that the application/system has recognized their tag.
For example, when the user types in the tags that you have entered for this question i.e. "user-behavior", "tags", "warnings", this is what people typically do.
Instead, try the following. As soon as they type a comma, change the styles of the text to indicate that the word(s) has been added/recognized as a tag.
And most importantly, provide clear instructions above the textbox on the accepted delimiter for the tags. It makes it more readable. When people see textboxes, they start typing right away. It's natural behavior since the user feels invited to respond when there's a call to attention especially with a cursor blinking at them.
And if you have watermark/placeholder text in that box that disappears as soon as the user starts typing something, then the user can't remember what the instructions were.
Finally, highlighting the instructions about the delimiter in the guidelines can play an important role too as it grabs the user's attention by providing contrast to the surrounding content.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability that particle hits shaded region on random walk?
Consider the following grid in the image, where the squares are equally spaced. Assume that the area of the entire image is $1$ and the black squares take up exactly $0 < k < 1$ of the region. Now suppose some point located in the white region begins a random walk at some constant speed in the image. (Further assume that the image is on a torus, so if the point travels right on the right edge it will appear on the left edge.) How do I determine the probability that the point enters one of the black regions?
I have no idea how to proceed since I am not familiar with the notation behind random walks. I only have general knowledge in elementary probability theory. How do I go about solving this problem?
A:
There is an answer for the discrete time solution provided by Tomi. In the continuous time case, a random walk is a solution to the diffusion equation : $$ \frac{\partial}{\partial t}P(\vec{r}, t) = D \nabla^2 P(\vec{r},t) $$
where $D$ is the diffusion constant (provided it does not depend on time or space) and $P(\vec{r}, t)$ is the probability of finding your particle in the region $\vec{r}$ at time $t$. In the usual cartesian space, solving this equation with $P(\vec{r}, 0) = \delta(\vec{0})$ and $P(\vec{r} \rightarrow \infty, t) = 0$ yields the gaussian solution. In your case, you will want to solve it for 2D toroidal coordinates with $P(\vec{r}, 0) = \delta(\vec{r_0})$. For a given time, the probability of finding the particle on a black square would be given by $$\int_{B} P(\vec{r}, t) d\vec{r}$$ where $B$ is the black region.
EDIT : I'm not sure what you mean by use the assumptions. The solution $P$ does not have to follow the symmetry of your squares (the initial condition $P(\vec{r}, t=0) = \delta(\vec{r_0})$ does not). I would guess you're interested in getting the probability at some time $t$ of finding the particle in a black region given that the initial condition is some point in the white space. Since you can calculate $P(\vec{r} = B, t; \vec{r_0})$, the probability of finding the particle in the black region at time $t$ for some initial condition $\vec{r_0}$, you just have to sample all the possible initial points in the white region :
$$ P_B(t) = A^{-1}\int_{\vec{r_0} \in W} P(\vec{r}=B, t; \vec{r_0}) d\vec{r_0}$$
Where A is the white space area that you consider. Given your symmetry you only have to perform integration in the irreducible region, which should be one quarter of a single black/white square.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Java, can I specify any amount of generic type parameters?
I am looking to create a particular type of interface in Java (although this is just as applicable to regular classes). This interface would need to contain some method, say, invoke; it would be called with a varying amount of parameters depending on the generic type arguments supplied.
As an example:
public interface Foo<T...> {
public void invoke(T... args);
}
// In some other class
public static Foo<Float, String, Integer> bar = new Foo<Float, String, Integer>() {
@Override
public void invoke(Float arg1, String arg2, Integer arg3) {
// Do whatever
}
};
To explain, briefly, how this could be used (and provide some context), consider a class Delegator: the class takes a varying number of generic types, and has a single method - invoke, with these parameter types. The method passes on its parameters to an object in a list: an instance of IDelegate, which takes the same generic types. This allows Delegator to choose between several delegate methods (defined inside IDelegate) without having to create a new class for each specific list of parameter types.
Is anything like this available? I have read about variadic templates in C++, but cannot find anything similar in Java. Is any such thing available? If not, what would be the cleanest way to emulate the same data model?
A:
Is anything like this available? I have read about variadic templates
in C++, but cannot find anything similar in Java. Is any such thing
available?
No, this feature is not available in Java.
| {
"pile_set_name": "StackExchange"
} |
Q:
Format Cart Totals HTML from JSON Response
My Controller File
public function myAction() {
$response = array();
$response['myresponse'] = $this->myAjax();
$this->getResponse()->clearHeaders()->setHeader('Content-type','application/json',true);
return $this->getResponse()->setBody(json_encode($response));
}
protected function myAjax()
{
$layout = $this->getLayout();
$totalsBlock = $layout->createBlock('checkout/cart_totals')->setTemplate('checkout/cart/totals.phtml');
return $totalsBlock->toHtml();
}
My JSON Response
{"myresponse":" <table id=\"shopping-cart-totals-table\">\n <col \/>\n <col width=\"1\" \/>\n <tfoot>\n <tr>\n <td style=\"\" class=\"a-right\" colspan=\"1\">\n <strong>Grand Total<\/strong>\n <\/td>\n <td style=\"\" class=\"a-right\">\n <strong><span class=\"price\">$90.56<\/span><\/strong>\n <\/td>\n<\/tr>\n <\/tfoot>\n <tbody>\n <tr>\n <td style=\"\" class=\"a-right\" colspan=\"1\">\n Subtotal <\/td>\n <td style=\"\" class=\"a-right\">\n <span class=\"price\">$820.56<\/span> <\/td>\n<\/tr>\n<tr>\n <td style=\"\" class=\"a-right\" colspan=\"1\">\n Shipping & Handling (Flat Rate - Fixed) <\/td>\n <td style=\"\" class=\"a-right\">\n <span class=\"price\">$90.00<\/span> <\/td>\n<\/tr>\n<tr>\n <\/tr>\n <\/tbody>\n <\/table>\n"}
My Oncomplete function
new Ajax.Request("<?php echo $formAction;?>", {
method: 'post',
postBody: "mypostdata="+$('my_value').value,
onComplete: function(data) {
var mydata = data.responseText.evalJSON(true);
$('shopping-cart-totals-table').update(mydata);
}
});
The cart totals block is being updated but with incorrect HTML format. How could I make it in formatted data and show proper HTML in cart totals block ?
Please Help.
Thanks.
A:
Instead of using
$('shopping-cart-totals-table').update(mydata);
Try using
$('shopping-cart-totals-table').update(mydata.myresponse);
You are sending JSON with the key myresponse and your cart block html as the value for that key. So mydata will be an Object after json is converted into a JS object and this object should have a property myresponse with the HTML for the cart block.
| {
"pile_set_name": "StackExchange"
} |
Q:
FTP - How to transfer a directory with multiple sub-directories?
I need to transfer a few gigs of files from server A to B. I own SSH access to server A, but I have only FTP access to B.
Since I can not send one .tar file from A to B, for the reason that I can not untar it later, I need to perform an FTP transfer.
How can I transfer (via FTP) all files including the directories and all sub directories?
I tried using mput * and mput *.*, but they did not work.
About solutions like LFTP or others
The lftp is a great solution, but I can not install it on the server, because it is not a dedicated server or a VPS. It is a common shared webhosting with SSH access.
A:
You need a client that can handle this. lftp (mirror -R , see http://www.russbrooks.com/2010/11/19/lftp-cheetsheet ) and ncftp (put -R) are two.
| {
"pile_set_name": "StackExchange"
} |
Q:
Valgrind legitimate "possibly lost" bytes example
I saw that valgrind classifies memory leaks into:
definitely lost
indirectly lost
possibly lost
still reachable
suppressed
I just fixed a leak where the "possibly lost" was the main problem.
The documentation says: "possibly lost means your program is leaking memory, unless you're doing unusual things with pointers that could cause them to point into the middle of an allocated block; see the user manual for some possible causes"
May I please know an example of "doing unusual things with pointers that could cause them to point into the middle of an allocated block" ?
I mean an example where "possibly lost" can be ignored although it is reported by valgrind. An example in which the use of pointers makes valgrind complain but at the same time the use of the pointers in that way is somehow legitimate
Thank you
A:
Some examples of what the documentation are different libraries that have their own allocators and for which the memory returned is not directly the pointer returned by the underlying OS allocator (malloc/sbrk), but a pointer after an offset. Consider for example, an allocator that obtained some extra memory and stored meta information (maybe type information for a garbage collector...). The process of allocation and deallocation would be similar to:
void* allocate( size_t size ) {
metainfo_t *m = (metainfo_t*) malloc( size + sizeof(metainfo) );
m->data = some_value;
return (void*)(m+1); // [1]
}
void deallocate( void* p ) {
metainfo_t *m = ((metainfo_t*)p) - 1;
// use data
}
void * memory = allocate(10);
When valgrind is tracking the memory, it remembers the original pointer that was returned by malloc, and that pointer is not stored anywhere in the program. But that does not mean that the memory has been leaked, it only means that the pointer is not directly available in the program. In particular memory still holds the returned pointer, and deallocate can be called to release it, but valgrind does not see the original returned pointer at location (char*)memory - sizeof(metadata_t) anywhere in the program and warns.
A:
char *p = malloc(100);
if (p != 0)
{
p += 50;
/* at this point, no pointer points to the start of the allocated memory */
/* however, it is still accessible */
for (int i = -50; i != 50; i++)
p[i] = 1;
free (p - 50);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Should we accept questions about moderation issues from users' points of view?
The current wave of questions seems to deal mainly with discussing how a moderator can/should act in situations requiring moderation, for example conflicts.
But of course, users are also involved in these situations. And they also need help and guidance from people who know how moderation works best.
For example, the question How do you deal with a back-seat moderator? has been asked and answered from the point of view of moderators: what can moderators do to subdue such a person.
I can imagine a twin question asking about the same problem from the perspective of a user: imagine that I am a user somewhere. A non-moderator starts policing me in what I believe to be inappropriate ways. The real moderators haven't solved the situation, for whatever reasons. What are my options?
Opening the site to this type of question will help to attract more users (because there are more users out there than moderators), and will enhance the communication between both groups, letting them clearly see the concerns of the other side.
There is also a potential for negative consequences: users who decide that this is the place to rant against what they perceive to be injustice inflicted on them by their moderators.
Do we want to accept these questions on the site? If yes, how do we minimize the chance of non-constructive questions?
A:
Yes, I believe a users perspective is important too. Confirmation bias sucks, and adding in other perspectives is a great way to prevent it.
To combat non-constructive questions, we do exactly what we do on other StackExchange sites. Flag off topic discussions. If the user is ranting, it's off topic. If the user is asking for advice on how to approach a moderator with evidence of problems within the community, that is on topic.
A:
I think we need to tread very carefully here. While good questions from any perspective that help better understand moderation should be encouraged and accepted, we need to very clearly define what types of questions those are (and
perhaps as importantly, what types of questions aren't).
I am tossing my ideas up as a community-wiki, so feel free to edit as needed to try to get a better list of what we do/don't want, and/or spin it off in to a separate post if merited.
Questions should:
Objectively lay out the situation with few or no leading statements or judgments on it
Should be about general concepts rather than incident-specific details
Inspire answers explaining why and how
Should have a single clear question about moderation rather than asking for general thoughts on a situation
Questions shouldn't:
Ask users to assign blame/determine right-wrong
Provide specific details of anyone involved (no witch hunting)
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift, Firebase. Checking if name already exist doesn't work
I'm trying to make an app, where you have to choose a team name, and when the user enter his/hers team name, I want to check if the name already is in use.
teamNameTextField is a UITextField and for some reason no matter what I type in the text field, it prints "Team name is not in use". I don't know what I'm doing wrong here, can somebody help me?
My code:
rootRef.child("teams").queryOrderedByChild("teamName").queryEqualToValue(teamNameTextField.text).observeSingleEventOfType(.Value, withBlock: { (snap) in
if (snap.value is NSNull) {
print("Team name is not in use")
} else {
print("Team name is already in use")
}
})
my JSON data tree:
{
"teams" : {
"pbXvXYOKmJQqwSQZ9IlBykG7x1P2" : {
"teamName" : "Test111"
},
"owidUDkEnbCOsmNSoSFu2o2iu4y38RKJNF" : {
"teamName" : "Test222"
},
"pdnJCDmcdjsiHDFb8349HGD8372bfdhb" : {
"teamName" : "Test123"
}
}
}
My database rules:
{
"rules": {
".read": true,
".write": true
}
}
A:
I realized the problem!
I tried to type print(teamNameTextField.text), and it printed: "Optional("Test111")"
So you have to put a ! after teamNameTextField.text, then it will only print "Test111"
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS: Localizable.strings doesn't work
This has been bothering for days now.
I've set up Arabic localisation in my project and I've set my device Language to Arabic.
When I run my app from Xcode with the run scheme option set to use Arabic Localization, localisation works fine.
When I run the app without Xcode, the app uses English.
I've read the answers to similar questions but none of them have worked for me thus far.
I am using NSLocalizableString(@"login",@""); to load the strings from the Localizable.strings file. This works fine as long as I set the Run scheme localization option to Arabic.
I've tried uninstalling the app, cleaning the project and then re-installing. Now the app uses the Localizabe.strings key names instead of their arabic values.
The Localizable.strings file is named correctly, and is listed under "Copy Bundle Resources".
The Localizable.strings is perfectly formatter. I've verified this using plutil.
What else could I be missing?
Example:
-(void) viewDidLoad
{
[super viewDidLoad];
// ...
[self setupLocalization];
}
-(void) setupLocalization
{
self.mailAddress.placeholder = NSLocalizedString(@"email_address", @"");
self.password.placeholder = NSLocalizedString(@"password", @"");
}
A:
I found out what the issue is:
AppDelegate's application:didFinishLoadingWithOptions: contained this snippet of code
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@[@"en"] forKey:@"AppleLanguages"];
[defaults synchronize];
which forces NSLocalizedString() to return English values.
The project was outsourced and I had no idea that the snippet was there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I include my admin page into the angular project or should i create a seperate one?
Hey i'm working on a frontend for my SpringBoot Application.
I'm just starting to learn Angular.
I'm not sure if there is a security issue if i create my admin-page in the same project.
Admin- and User-Page would share a lot of code but admin operations (or even data) shouldn't be accessable for anybody else.
What i've found so far:
Should I create Two Angular projects for Admin and Users?
So creating one Angular project with two modules should be the way to go right?
But how do i approach that?
Or can i just build a single one module project with authentification and admin/user roles?
What would be best practice?
Thank you
A:
I've recently developed a project that has a user facing set of pages and an admin set of pages.
The way I have structured my project is roughly like the following:
|- AppModule
|-- app components
|-- app services
|-- app routing
|
|- SharedModule
|-- components
|
|- AdminModule
|-- admin components
|-- admin services
|-- admin routing
Both AppModule and AdminModule import SharedModule. AdminModule is lazy loaded from my root admin path in AppRouting like this:
{
path: 'admin',
canLoad: [AdminGuardService],
loadChildren: () => import('../modules/admin/admin.module').then(m => m.AdminModule)
}
Where AdminGuardService is a route guard that checks if the current user has admin access.
The benefit of a lazy loaded module is that it is compiled separately from AppModule, and is only loaded by the browser when my admin path is hit. I keep all of my admin-specific http calls in my admin services, so they never make it into my main app bundle.
From a security perspective, there's nothing to stop non-admin users guessing your admin urls regardless of whether it's in the same project or a different project. All of my backend authorization is done by my API. So if a non-admin user guesses an admin url, they will get a 401 and I will redirect them back to the main app.
| {
"pile_set_name": "StackExchange"
} |
Q:
Asp.Net4 Javascript/jquery Minification Error
I realize this might be stupid, and its probably caused by my lack of javascript/jquery knowledge (in terms of re-factoring etc..)
I'm rendering a JQGrid component on my page like this.
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/JQGrid")" type="text/javascript"></script>
<script type="text/javascript">
var colNames = ['S ID', 'Shift Description'];
var colModel = [
{ name: 'S_ID', index: 'S_ID', key: true, width: 55, editable: false, hidden: true, search: false },
{ name: 'Shift_Description', index: 'Shift_Description', width: 100, align: "right", editable: true, editrules: { required: true }, formoptions: { rowpos: 1, colpos: 1}}];
RenderJQGrid("#theGrid", '#pager', '@ViewBag.Title', 600, colNames, colModel, 'S_ID', null, null, null, '@Url.Action("GridData")', '@Url.Action("Add")', '@Url.Action("Edit")', '@Url.Action("Delete")', '@Url.Action("ExportToExcel")');
</script>
Inside my .js file, I only have this. (it's also the only file in the bundle)
function RenderJQGrid(GridID, PagerID, Title, ModalWidth, ColNames, ColModel, InitSortCol, OnLoadComplete, EditBeforeShowOptions, AddBeforeShowOptions, URL_get, URL_add, URL_edit, URL_delete, URL_excel) {
... Logic
}
I'm receiving this error in fiddler though.
/* Minification failed. Returning unminified contents.
(1,10): run-time error CSS1031: Expected selector, found
'RenderJQGrid('
(1,10): run-time error CSS1025: Expected comma or open brace, found
'RenderJQGrid('
*/
what am i doing wrong/missing? the code seemed fine when it was embedded inside my html page?
A:
I ran into a similar problem. My issue was that I was using a StyleBundle to bundle *.js files
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining GC type via GarbageCollectorMXBean
I was reading this excellent answer on grabbing Java garbage collection activity info and noticed that the GarbageCollectorMXBean doesn't have any data about what type of collection it was (Minor, Major, Full, etc.).
I'm wondering: is it possible to figure out (from Java code) whether a particular GC was minor, major or full?
A:
Printing periodic GC stats from the GarbageCollectorMXBean's summary stats won't give you that type of information. If you are using Java 1.7+, you can subscribe to JMX notifications from each GarbageCollectorMXBean instance and you'll get a notification for every GC event which will give you a bit more detail on each individual event. The notification's UserData will contain an instance of the type GarbageCollectionNotificationInfo. The attribute GcAction will tell you if it was major or minor, and GcCause will tell you the GC event cause.
Note that this references com.sun packages and assumes a HotSpot JVM. You can avoid referencing the com.sun packages in your code using pure JMX and OpenType inference, but be cautious about assuming this will work across all Java 1.7 JVMs.
| {
"pile_set_name": "StackExchange"
} |
Q:
qml2 Non-existent attached object ImageParticle
When I try to build a particle system by using ImageParticle in qml2, the compiler gives this error:
Non-existent attached object
ImageParticle:{
^
Here is the part of my code:
import QtQuick 2.0
import QtQuick.Particles 2.0
Item {
id:particle
anchors.fill: parent
Rectangle{
anchors.fill: parent
ParticleSystem{
id:petalParticleSystem
}
ImageParticle:{
source:"image/Petal.png"
system:petalParticleSystem
}
A:
Why don't you have a colon in
ParticleSystem{
and
Rectangle{
but you do have one here?
ImageParticle:{
That's what the error message means, I think.
| {
"pile_set_name": "StackExchange"
} |
Q:
AVR - High speed interrupt driven UART code not working
I want to make a interrupt driven uart program, to send large amounts of data at high speeds with the absolute minimal amount of cpu overhead. I combined existing code and reading of the datasheet to make this code. It compiles without errors or warnings in Atmel Studio 7 on an atmega328p (Atmega328p Xplained Mini).
The problem that I'm having is that data is erratic, sometimes it sends 'ello!' sometimes nothing for a while. The 'H' is often skipped, I don't understand this since the ISR shouldn't execute before the 'H' has been copied from UDR0 to be sent.
Any help would be greatly appreciated!
Greetings,
Bert.
#define F_CPU 16000000
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
volatile uint8_t transmit_index = 0;
volatile char str[] = "Hello!\n";
volatile uint8_t len = 6;
int main(void){
UCSR0A = 0b00000010;
UCSR0B = 0b00111000;
UCSR0C = 0b00000110;
//9600 baud
UBRR0L = 207;
UBRR0H = 0;
DDRD |= 0x02;
sei();
//Flash led
DDRB |= 0b00100000;
PORTB |= 0b00100000;
_delay_ms(1000);
PORTB &= ~0b00100000;
_delay_ms(1000);
while (1){
transmit_index = 1;
//Enable udre interrupt
UCSR0B |= 0b00100000; //enable interrupt
//Send first byte in main()
while (!(UCSR0A & 0b00100000)) {} //Wait for register empty
UDR0 = str[0]; //send first byte
_delay_ms(1000);
}
}
ISR(USART_UDRE_vect) {
//Buffer empty, ready for new data
if (transmit_index < (len + 1)) {
UDR0 = str[transmit_index];
transmit_index++;
} else {
UCSR0B &= ~0b00100000; //disable interrupt
}
}
A:
per the datasheet:
"When the Data Register Empty Interrupt Enable (UDRIE) bit in UCSRnB
is written to '1', the USART data register empty interrupt will be
executed as long as UDRE is set"
As soon as you enable the interrupt, the ISR is triggered, thus skipping the "H". You have a couple of options.
1) Enable the interrupt after you send the H.
2) Just use the ISR to send the entire message, including the H (e.g. don't send anything in the main routine.
3) Use the Tramsmit Complete ((TXC) interrupt. If you use this, send the H in the main routine, and once it is transferred, the ISR will trigger and your ISR will send the rest of the message.
Lastly, change "transmit_index < (len + 1)" to transmit_index <= len. There is no need to waste instructions inside an ISR
| {
"pile_set_name": "StackExchange"
} |
Q:
Nombre de columna repetidos en diferentes tablas de sql server
tengo una base de datos que no está relacionada, es decir no existen foreign keys, y necesito encontrar en qué tablas aparece el campo codigocliente, que es primary key de la tabla CLIENTE, sé que este campo por ejemplo lo encuntro en la tabla FACTURA y VENTASERVICIO de la base de datos, pero quisiera saber en qué otras tablas adicionalmente está. Por favor su apoyo...
A:
Esto es útil, siempre que las columnas respeten el mismo nombre, cuando codigocliente en la tabla secundaria se llame numerocliente, obviamente esta solución no te serviría, de hecho es algo que no tampoco tiene solución.
SELECT o.name
FROM syscolumns c
inner join sysobjects o
on c.id = o.id
where c.name = 'codigocliente'
order by o.name
Esto, se ejecuta por base de datos, y te retornará, todas las tablas dónde exista una columna codigocliente. El código anterior es compatible con una gran variedad de versiones de sql server, aunque para ser estrictos, en versiones de 2008 o superiores, se recomienda:
SELECT o.name
FROM sys.columns c
inner join sys.objects o
on c.object_id = o.object_id
where c.name = 'codigocliente'
order by o.name
| {
"pile_set_name": "StackExchange"
} |
Q:
zabbix API json request with python urllib.request
I'm working on my python project and I migrated from python2.6 to python 3.6. So I had to replace urllib2 with urllib.request ( and .error and .parse ).
But I'm facing an issue I can't solve, here it is...
I want to send a request written in JSON like below :
import json
import urllib2
data= json.dumps({
"jsonrpc":"2.0",
"method":"user.login",
"params":{
"user":"guest",
"password":"password"
}
"id":1,
"auth":None
})
with urllib2 I faced no issue, I just had to create the request with :
req=urllib2.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})
send it with:
response=urllib2.urlopen(req)
and it was good but now with urllib.request, I have met many error raised by the library. check what I did ( the request is the same within 'data') :
import json
import urllib.request
data= json.dumps({
"jsonrpc":"2.0",
"method":"user.login",
"params":{
"user":"guest",
"password":"password"
}
"id":1,
"auth":None
})
req = urllib.request.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})
response = urllib.request.urlopen(req)
and I get this error :
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 524, in open
req = meth(req)
File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 1248, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
So I inquired about this and learned that I must use the function urllib.parse.urlencode() to convert my request into bytes, so I tried to use it on my request :
import urllib.parse
dataEnc=urllib.parse.urlencode(data)
another error occured :
Traceback (most recent call last):
File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 842, in urlencode
raise TypeError
TypeError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 850, in urlencode
"or mapping object").with_traceback(tb)
File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 842, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object
and I realized that json.dumps(data) just convert my array/dictionnary into a string, which is not valid for the urllib.parse.urlencode function, soooooo I retired the json.dumps from data and did this :
import json
import urllib.request
import urllib.parse
data= {
"jsonrpc":"2.0",
"method":"user.login",
"params":{
"user":"guest",
"password":"password"
}
"id":1,
"auth":None
}
dataEnc=urllib.parse.urlencode(data) #this one worked then
req=urllib.request.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})
response = urllib.request.urlopen(req) #and this one too, but it was too beautiful
then I took a look in the response and got this :
b'{"jsonrpc":"2.0",
"error":{
"code":-32700,
"message":"Parse error",
"data":"Invalid JSON. An error occurred on the server while parsing the JSON text."}
,"id":1}
And I guess it's because the JSON message is not json.dumped !
There is always one element blocking me from doing the request correctly,
so I'm totally stuck with it, if any of you guys have an idea or an alternative I would be so happy.
best Regards
Gozu09
A:
In fact you just need to pass your json data as a byte sequence like this:
data= {
"jsonrpc":"2.0",
"method":"user.login",
"params":{
"user":"guest",
"password":"password"
}
"id":1,
"auth":None
}
req = urllib.request.Request(
"http://myurl/zabbix/api_jsonrpc.php",
data=json.dumps(data).encode(), # Encode a string to a bytes sequence
headers={'Content-type':'application/json}
)
POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str
This error means that the data argument is expected to be an iterables of bytes.
st = "This is a string"
by = b"This is an iterable of bytes"
by2 = st.encode() # Convert my string to a bytes sequence
st2 = by.decode() # Convert my byte sequence into an UTF-8 string
json.dumps() returns a string, therefore you have to call json.dumps().encode() to convert it into a byte array.
By the way, urlencode is used when you want to convert a string that will be passed as an url argument (i.e: converting spaces characters to "%20"). The output of this method is a string, not a byte array
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP: Merge catches
Could I merge two catches in PHP?
try {
// some code
}
catch (App_Exception $e) {
// do sth.
}
catch (Exception $e) {
// do the same exception code again
}
A:
try {
try {
// some code
}
catch (App_Exception $e) {
// do sth.
throw $e;
}
}
catch (Exception $e) {
// do the same exception code again
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a word for a review of a review?
I need a word to describe a review that has been made on a review.
The review itself I will call a "review", but if someone reviews the reviews, what can I call this? I can't call it a review as well as that would be confusing.
I need a short understandable word for it. Any ideas?
A:
A review of a review is still just a review.
You might risk calling it a meta-review, but understand that you would thereby put yourself at some small risk of being misunderstood.
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing the alternating series $\sum_{n=1}^\infty (-1)^n \frac{n}{p_n}$ where $p_n$ is the $n$th prime converges
So what I want to prove is:
Proposition:
Let $p_n$ be the $n$th prime. Then the alternating series $$\sum_{n=1}^\infty (-1)^n \dfrac{n}{p_n}$$ converges.
Here's my (original) attempt. Could someone verify my proof is alright?
Lemma 1: If $a_n$ and $b_n$ are sequences and $\lim_{x\to \infty} \frac{a_n}{b_n} = 1$, then
$$\sum_{n=1}^\infty a_n \text{ converges} \iff \sum_{n=1}^\infty b_n \text{ converges},$$
$$\sum_{n=1}^\infty a_n \text{ diverges} \iff \sum_{n=1}^\infty b_n \text{ diverges}.$$
Proof: Follows directly from the limit comparison test.
Proof of Proposition: Note that by the Prime Number Theorem,
$$p_n \sim n \log(n),$$
that is, due to
$$\lim_{n\to \infty} \frac{p_n}{n \log(n)} =1.$$
Thus, by Lemma 1,
$$\sum_{n=1}^\infty (-1)^n \dfrac{1}{\log (n)} \text{ converges} \implies \sum_{n=1}^\infty (-1)^n \dfrac{n}{p_n} \text{ converges}.$$
Now, the series $\sum_{n=1}^\infty (-1)^n \dfrac{1}{\log (n)}$ converges (as made clear by the alternating series test). As a result, our proposition is proven.
Note (Clément C.): As mentioned in the comments, this particular argument is faulty, since the "Lemma" used does not hold. (Specifically, it only holds for positive sequences (or negative sequences), but not those whose sign alternate.) A proof of convergence (or divergence) of the original series would be quite interesting.
Observe also that the alternating series test does not seem to apply here, as even with the Prime Number Theorem it is not obvious (and may be false) that the sequence $\left(\frac{n}{p_n}\right)_n$ is non-increasing. Moreover, it is not clear that the "usual" remedy for this (i.e., performing a Taylor series expansion of $\lvert a_n\rvert$ to get a constant number of terms which constitute, each by itself, non-increasing sequences; until a last term is reached which is the term of an absolutely convergent series) can be applied here, as such a series development appears to only give very slowly decreasing terms. (That is, reaching a term whose seriess absolutely convergent does not seem to happen within a constant number of terms).
A:
It's an unsolved problem see Primes Sum Number 8
Because the gap between two consecutive primes $n^{0.53}\geq g_n\geq 2$ for large $n$ ,and by PNT the average gap is $\ln n$.
Now one can show that if most of the gaps are away from $\ln n$ then the sum diverges, but if most of the gaps are around $\ln n$ then the sum converge.
Even if used the bound given by the famous R.H. we still get that $ \sqrt{n} \ln n \geq g_n \geq 2$ which does not help.
May be it could have a chance of being solved using Cramér's conjecture for the gap $O(\ln^2 n) \geq g_n \geq 2$ (i am not sure since its not solved).
A:
The limit comparison test requires positive terms, as
explained by user466572.
Possibly of more use: For $n \geq 6$,
$$ \log n + \log\log n - 1 < \frac{p_n}{n} < \log n + \log \log n \text{.} $$
(See Wikipedia: Prime Number Theorem:Approximations for the $n^\text{th}$ prime.)
But this is clearly not sufficient to conclude, the sequence not being decreasing. There is a plot of the partial sums of the series, showing why it could converge, but at such a slow rate that we'd probably need super-strong versions of the Cramer conjecture on the prime gap to show it
| {
"pile_set_name": "StackExchange"
} |
Q:
CMake-Configure: Permission Denied
I am trying to compile my Project with CMake, on one of my Computers it works perfectly (a Linux box), but the other one (Windows 7 Ultimate 64) has really problems.
I have tried multpiple generators:
MinGW (standalone and from CodeBlocks):
Error message:
(Just the part that should lead to a solution)
f:/tools/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../../mingw32/bin/ld.exe:
cannot open output file cmTryCompileExec.exe: Permission denied
collect2: ld returned 1 exit status
Visual Studio 10 Professional
Error Message:
(Again only the Part that may be interesting, i have translated it from german)
CMake Error at C:/Program Files (x86)/CMake 2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
The C compiler "cl" is not able to compile a simple test program.
[...]
1>ClCompile:
1> testCCompiler.c
1>LINK : fatal error LNK1104: Datei
"H:\yps_2\VISUAL\CMakeFiles\CMakeTmp\Debug\cmTryCompileExec.exe" could not be opened.
I have Searched google and SO fpr days now and i think no one had some similar Problem like me...
I would be so glad if you could help me guys!
PS: There is another Issue on SO like mine, but it is unanswered:
https://stackoverflow.com/questions/7294011/permission-denied-errors-when-using-cmake
A:
First make sure you're computer is not infected with viruses: If any viruses modifying EXE files exist, they can be the main cause you can't write to your own EXE files. Scan your computer with an up-to-date antivirus.
Another problem can be your anti-virus trying to block EXE hijacks. If you're sure your computer is clean, try fully disabling your antivirus.
Another solutions that come to my mind are:
Try right-clicking on Code Blocks or Visual Studio and choosing Run as Administrator.
If you are executing from Command Prompt, make sure you do it in an administrative Command Prompt.
Try putting the CMake and other related tools and also the output folder in your C:\ drive. Maybe you don't have quota or rights to access other drives?
Try disabling all services you see are useless. Maybe some service has just locked the file without using it for no good reason.
Try to dismount your H: volume and mount it again. (Either use diskmgmt.msc or use fsutil volume dismount H: and explore to mount it again)
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel No database selected
I just can't connect with my database in laravel, it's give me an error
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected (SQL: select count(*) as aggregate from users where email = )
.env my database name is=empty
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=empty
DB_USERNAME=root
DB_PASSWORD=
database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'empty'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
Thank you in advanced.
A:
You shouldn't be using reserved keywords at all to names of tables, columns, functions, stored_procedures, views, database.
Please find below link for reserved keywords in MySQL.
https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-removed-in-current-series.
If still facing some problems. follow below commands.
composer update
composer dump-autoload
php artisan config:cache
php artisan view:clear
php artisan route:clear
| {
"pile_set_name": "StackExchange"
} |
Q:
Asp.Net Drop down menu not working correctly
Im make a 3 drop down menu 1) Country
2) City
3) Factory
Country and City Dropdownmenu working correctly(Country selected displayed country to included city's) but city selected not a display city to included factory's how can i fix it? can you please give the solution.
GodownCls godownCls = new GodownCls();
CityCls ctyCls = new CityCls();
FactoryCls facCls = new FactoryCls();
LoadCountries();
private void LoadCountries()
{
CountryCls objCountry = new CountryCls();
DataTable dtCountry = objCountry.Country_SelectAll();
ddlCountry.DataSource = dtCountry;
ddlCountry.DataTextField = "Name";
ddlCountry.DataValueField = "ID";
ddlCountry.DataBind();
}
private void LoadFactories(int CityId)
{
FactoryCls objFactory = new FactoryCls();
DataTable dtFactory = objFactory.FactoriesByCity(CityId);
ddlFactory.DataSource = dtFactory;
ddlFactory.DataTextField = "Name";
ddlFactory.DataValueField = "ID";
ddlFactory.DataBind();
ddlFactory.SelectedIndex = 0;
}
private void LoadCities(int CountryId)
{
CityCls objCity = new CityCls();
DataTable dtCity = objCity.CitiesByCountry(CountryId);
ddlCity.DataSource = dtCity;
ddlCity.DataTextField = "Name";
ddlCity.DataValueField = "ID";
ddlCity.DataBind();
ddlCity.SelectedIndex = 0;
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedCountryId = Convert.ToInt32(ddlCountry.SelectedValue);
LoadCities(selectedCountryId);
}
protected void ddlFactory_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedFactoryId = Convert.ToInt32(ddlFactory.SelectedValue);
LoadCities(selectedFactoryId);
}
actually now all of factory displayed for the drop down menu
full code
public partial class Godown : System.Web.UI.Page
{
#region "---- Variables & ViewStates ----"
clsCommonMethods clsComMethods = new clsCommonMethods();
public DataTable dtGodownHelp
{
get { return (DataTable)ViewState["dtGodownHelp"]; }
set { ViewState["dtGodownHelp"] = value; }
}
public String CurrentMode
{
get { return (String)ViewState["CurrentMode"]; }
set { ViewState["CurrentMode"] = value; }
}
public int SelectedGodownId
{
get { return (int)ViewState["SelectedGodownId"]; }
set { ViewState["SelectedGodownId"] = value; }
}
public int SelectedUserId
{
get { return (int)ViewState["SelectedUserId"]; }
set { ViewState["SelectedUserId"] = value; }
}
public bool ViewRight
{
get { return (bool)ViewState["ViewRight"]; }
set { ViewState["ViewRight"] = value; }
}
public bool CreateRight
{
get { return (bool)ViewState["CreateRight"]; }
set { ViewState["CreateRight"] = value; }
}
public bool UpdateRight
{
get { return (bool)ViewState["UpdateRight"]; }
set { ViewState["UpdateRight"] = value; }
}
#endregion
GodownCls godownCls = new GodownCls();
CityCls ctyCls = new CityCls();
FactoryCls facCls = new FactoryCls();
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
if ((Session["UserId"] == null))
{
FormsAuthentication.SignOut();
Response.Redirect("~/WebForms/Home/Login.aspx");
}
else
{
SelectedUserId = int.Parse(Session["UserId"].ToString());
string pageName = "godown";
DataTable dtUp = UserPermission(pageName);
if (dtUp.Rows.Count > 0)
{
ViewRight = Convert.ToBoolean(dtUp.Rows[0]["isViewable"]);
CreateRight = Convert.ToBoolean(dtUp.Rows[0]["isCreatable"]);
UpdateRight = Convert.ToBoolean(dtUp.Rows[0]["isEditable"]);
}
if (ViewRight != true)
{
Response.Redirect("~/WebForms/Home/AccessDenied.aspx");
}
else
{
SetSavePermission(CreateRight);
SetEditPermission(UpdateRight);
}
}
ClearControls();
EnableControls(false);
LoadCountries();
}
}
private void SetSavePermission(bool EnableStatus)
{
btnNew.Enabled = EnableStatus;
btnSave.Enabled = EnableStatus;
}
private void SetEditPermission(bool EnableStatus)
{
btnUpdate.Enabled = EnableStatus;
btnSave.Enabled = EnableStatus;
}
#endregion
private DataTable UserPermission(string mPageCode)
{
int UserId = int.Parse(Session["UserId"].ToString());
DataTable dtPermission = new DataTable();
dtPermission = clsComMethods.GetUserWisePermissions(UserId, mPageCode);
return dtPermission;
}
#region Enable Disable Controls
private void EnableControls(bool Status)
{
txtGodowncode.Enabled = Status;
txtGodownname.Enabled = Status;
ddlCountry.Enabled = Status;
//ddlCity.Enabled = Status;
//ddlFactory.Enabled = Status;
txtEmail.Enabled = Status;
txtFax.Enabled = Status;
txtGodown.Enabled = Status;
txtGodownAdd.Enabled = Status;
txtGodowncontact.Enabled = Status;
txtPhn1.Enabled = Status;
txtPhn2.Enabled = Status;
txtTelex.Enabled = Status;
txtWebSite.Enabled = Status;
txtTelex.Enabled = Status;
if (Status == true)
{
txtRemarks.Disabled = false;
}
else
{
txtRemarks.Disabled = true;
}
chkStatus.Enabled = Status;
btnGodownhelp.Enabled = Status;
}
#endregion
private void LoadCountries()
{
CountryCls objCountry = new CountryCls();
DataTable dtCountry = objCountry.Country_SelectAll();
ddlCountry.DataSource = dtCountry;
ddlCountry.DataTextField = "Name";
ddlCountry.DataValueField = "ID";
ddlCountry.DataBind();
}
private void LoadFactories(int CityId)
{
FactoryCls objFactory = new FactoryCls();
DataTable dtFactory = objFactory.FactoriesByCity(CityId);
ddlFactory.DataSource = dtFactory;
ddlFactory.DataTextField = "Name";
ddlFactory.DataValueField = "ID";
ddlFactory.DataBind();
ddlFactory.SelectedIndex = 0;
}
private void LoadCities(int CountryId)
{
CityCls objCity = new CityCls();
DataTable dtCity = objCity.CitiesByCountry(CountryId);
ddlCity.DataSource = dtCity;
ddlCity.DataTextField = "Name";
ddlCity.DataValueField = "ID";
ddlCity.DataBind();
ddlCity.SelectedIndex = 0;
}
#region Button Disable
private void DisableButtons()
{
btnSave.Enabled = false;
btnUpdate.Enabled = true;
btnInquiry.Enabled = true;
btnCancel.Enabled = false;
}
#endregion
#region Clear Controls
private void ClearControls()
{
txtGodowncode.Text = "";
txtGodownname.Text = "";
ddlCountry.SelectedIndex = 0;
//ddlCity.SelectedIndex = 0;
//ddlFactory.SelectedIndex = 0;
txtGodowncontact.Text = "";
txtWebSite.Text = "";
txtGodownAdd.Text = "";
txtPhn1.Text = "";
txtPhn2.Text = "";
txtEmail.Text = "";
txtFax.Text = "";
txtTelex.Text = "";
lblMsg.Text = "";
txtRemarks.Value = "";
chkStatus.Checked = false;
SelectedGodownId = -1;
if (CurrentMode == "Modify")
{
txtGodowncode.Enabled = true;
}
}
#endregion
#region New Button Click
protected void btnNew_Click(object sender, EventArgs e)
{
try
{
ClearControls();
CurrentMode = "Add";
lblMode.Text = "New Record";
lblMode.ForeColor = System.Drawing.Color.Yellow;
SelectedGodownId = -1;
btnUpdate.Enabled = false;
btnInquiry.Enabled = false;
btnCancel.Enabled = true;
EnableControls(true);
txtGodowncode.Enabled = false;
btnGodownhelp.Enabled = false;
btnSave.Enabled = true;
btnClear.Enabled = true;
chkStatus.Checked = true;
txtGodownname.Focus();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Update Button Click
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
CurrentMode = "Modify";
lblMode.Text = "Modify Record";
lblMode.ForeColor = System.Drawing.Color.Yellow;
btnNew.Enabled = false;
btnInquiry.Enabled = false;
btnCancel.Enabled = true;
txtGodowncode.Enabled = true;
txtGodownname.Enabled = false;
ddlCountry.Enabled = false;
ddlCity.Enabled = false;
txtGodowncontact.Enabled = false;
txtWebSite.Enabled = false;
txtGodownAdd.Enabled = false;
ddlFactory.Enabled = true;
txtPhn1.Enabled = false;
txtPhn2.Enabled = false;
txtEmail.Enabled = false;
txtFax.Enabled = false;
txtTelex.Enabled = false;
txtRemarks.Disabled = true;
chkStatus.Enabled = false;
btnGodownhelp.Enabled = true;
btnSave.Enabled = false;
btnClear.Enabled = true;
txtGodowncode.Focus();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Inquiry Button Click
protected void btnInquiry_Click(object sender, EventArgs e)
{
try
{
CurrentMode = "Inquiry";
lblMode.Text = "Inquiry Record";
lblMode.ForeColor = System.Drawing.Color.Yellow;
btnNew.Enabled = false;
btnUpdate.Enabled = false;
txtGodowncode.Enabled = true;
btnGodownhelp.Enabled = true;
btnSave.Enabled = false;
btnClear.Enabled = true;
btnCancel.Enabled = true;
txtGodownname.Focus();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Clear Button Click
protected void btnClear_Click(object sender, EventArgs e)
{
ClearControls();
}
#endregion
#region Cancel Button Click
protected void btnCancel_Click(object sender, EventArgs e)
{
try
{
CurrentMode = "Cancel";
btnNew.Enabled = true;
btnInquiry.Enabled = true;
btnUpdate.Enabled = true;
btnCancel.Enabled = false;
btnSave.Enabled = false;
btnClear.Enabled = false;
EnableControls(false);
ClearControls();
SetSavePermission(CreateRight);
SetEditPermission(UpdateRight);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Save Button Click
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string strGodownCode;
int statusId;
if (CurrentMode == "Add")
{
strGodownCode = "";
}
else
{
strGodownCode = txtGodowncode.Text.ToString();
}
if (chkStatus.Checked == true)
{
statusId = 8;
}
else
{
statusId = 9;
}
int output = godownCls.InsertGodown(SelectedGodownId, strGodownCode, txtGodownname.Text, int.Parse(ddlCountry.SelectedValue), int.Parse(ddlCity.SelectedValue), int.Parse(ddlFactory.SelectedValue), txtGodowncontact.Text, txtWebSite.Text, txtGodownAdd.Text, txtRemarks.Value.ToString(), txtPhn1.Text, txtPhn2.Text, txtEmail.Text, txtFax.Text, txtTelex.Text, statusId, SelectedUserId, CurrentMode.ToString());
if (output > 0)
{
if (CurrentMode == "Add")
{
txtGodowncode.Text = "GDN" + output.ToString("00000");
lblMsg.Text = "Successfully Saved!";
lblMsg.ForeColor = System.Drawing.Color.Green;
}
else if (CurrentMode == "Modify")
{
lblMsg.Text = "Successfully Updated!";
lblMsg.ForeColor = System.Drawing.Color.Green;
}
}
else if (output == -3)
{
lblMsg.Text = "Already Exists!";
lblMsg.ForeColor = System.Drawing.Color.Orange;
}
else if (output == -1)
{
lblMsg.Text = "Save Unsuccessful! Code Error!";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
else if (output == -2)
{
lblMsg.Text = "Save Unsuccessful! SP Error!";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region GDN Code help Button Click
protected void btnGodownhelp_Click(object sender, EventArgs e)
{
try
{
lblMsg.Text = "";
txtGodownname.Text = "";
txtRemarks.Value = "";
chkStatus.Checked = false;
DataTable dtGodown = godownCls.FGetGodown(txtGodowncode.Text.ToString());
if (dtGodown.Rows.Count > 0)
{
dtGodownHelp = dtGodown;
Session["Help"] = "Godown";
gvHelp.DataSource = dtGodown;
gvHelp.DataBind();
gvHelp.HeaderRow.Cells[3].Visible = false; //Godown Id
gvHelp.HeaderRow.Cells[4].Visible = false; //Status Id
gvHelp.HeaderRow.Cells[5].Visible = false; //Remarks
foreach (GridViewRow gvr in gvHelp.Rows)
{
gvr.Cells[3].Visible = false; //Godown Id
gvr.Cells[4].Visible = false; //Status Id
gvr.Cells[5].Visible = false; //Remarks
}
//rgData.DataSource = dtColour;
//rgData.DataBind();
mpConfirm.Show();
}
else
{
lblMsg.Text = "No Record Found";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Help Grid Row Command
protected void gvHelp_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = gvHelp.Rows[index];
if (Session["Help"].ToString() == "Godown")
{
SelectedGodownId = Convert.ToInt32(selectedRow.Cells[3].Text);
DataRow[] dr = dtGodownHelp.Select("[Godown Id] = " + SelectedGodownId);
if (CurrentMode == "Modify")
{
txtGodowncode.Enabled = false;
txtGodownname.Enabled = true;
ddlCountry.Enabled = true;
chkStatus.Enabled = true;
txtRemarks.Disabled = false;
btnSave.Enabled = true;
}
else if (CurrentMode == "Inquiry")
{
txtGodowncode.Enabled = true;
txtGodownname.Enabled = false;
ddlCountry.Enabled = false;
chkStatus.Enabled = false;
txtRemarks.Disabled = true;
btnSave.Enabled = false;
}
int countryId = Convert.ToInt32((dr[0]["Country Id"]).ToString());
LoadFactories(countryId);
int factoryId = Convert.ToInt32((dr[0]["Factory Id"]).ToString());
LoadFactories(factoryId);
txtGodowncode.Text = dr[0]["Godown Code"].ToString();
txtGodownname.Text = dr[0]["Godown Name"].ToString();
ddlCountry.SelectedValue = (dr[0]["Country Id"]).ToString();
ddlFactory.SelectedValue = (dr[0]["Factory Id"]).ToString();
ddlCity.SelectedValue = (dr[0]["City Id"]).ToString();
txtGodowncontact.Text = dr[0]["GodownContactPerson"].ToString();
txtWebSite.Text = dr[0]["GodownWebsite"].ToString();
txtGodownAdd.Text = dr[0]["GodownAddress"].ToString();
txtPhn1.Text = dr[0]["PhoneNumber"].ToString();
txtPhn2.Text = dr[0]["Mobile"].ToString();
txtEmail.Text = dr[0]["Email"].ToString();
txtFax.Text = dr[0]["Fax"].ToString();
txtTelex.Text = dr[0]["Telex"].ToString();
if (Convert.ToInt32(dr[0]["Status Id"]) == 8)
{
chkStatus.Checked = true;
}
else
{
chkStatus.Checked = false;
}
txtRemarks.Value = dr[0]["Remarks"].ToString();
}
}
}
#endregion
#region Help Grid Page Index Changing
protected void gvHelp_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// gvHelp.PageIndex = e.NewPageIndex;
// gvHelp.DataSource = dt;
// gvHelp.DataBind();
// mpConfirm.Show();
}
#endregion
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedCountryId = Convert.ToInt32(ddlCountry.SelectedValue);
LoadCities(selectedCountryId);
}
protected void ddlFactory_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedFactoryId = Convert.ToInt32(ddlFactory.SelectedValue);
LoadCities(selectedFactoryId);
}
}
}
FactoryCls
public class FactoryCls
{
DataManipulation clsDataMan = new DataManipulation();
public int InsertFactory
(
int FactoryId,
string FactoryCode,
string FactoryName,
int CountryId,
int CityId,
string FactoryContactPerson,
string FactoryWebsite,
string FactoryAddress,
string TQB_No,
string Remarks,
string PhoneNumber,
string Mobile,
string Email,
string Fax,
string DisplayNameForTQB,
string Declarant_SequenceNo,
string Telex,
int StatusId,
int UserId,
string sMode
)
{
int Output = 0;
SqlParameter[] sqlParam = new SqlParameter[21];
sqlParam[0] = new SqlParameter("@FactoryId", FactoryId);
sqlParam[1] = new SqlParameter("@FactoryCode", FactoryCode);
sqlParam[2] = new SqlParameter("@FactoryName", FactoryName);
sqlParam[3] = new SqlParameter("@CountryId", CountryId);
sqlParam[4] = new SqlParameter("@CityId", CityId);
sqlParam[5] = new SqlParameter("@FactoryContactPerson", FactoryContactPerson);
sqlParam[6] = new SqlParameter("@FactoryWebsite", FactoryWebsite);
sqlParam[7] = new SqlParameter("@FactoryAddress", FactoryAddress);
sqlParam[8] = new SqlParameter("@TQB_No", TQB_No);
sqlParam[9] = new SqlParameter("@Remarks", Remarks);
sqlParam[10] = new SqlParameter("@PhoneNumber", PhoneNumber);
sqlParam[11] = new SqlParameter("@Mobile", Mobile);
sqlParam[12] = new SqlParameter("@Email", Email);
sqlParam[13] = new SqlParameter("@Fax", Fax);
sqlParam[14] = new SqlParameter("@DisplayNameForTQB", DisplayNameForTQB);
sqlParam[15] = new SqlParameter("@Declarant_SequenceNo", Declarant_SequenceNo);
sqlParam[16] = new SqlParameter("@Telex", Telex);
sqlParam[17] = new SqlParameter("@StatusId", StatusId);
sqlParam[18] = new SqlParameter("@CreateId", UserId);
sqlParam[19] = new SqlParameter("@Mode", sMode);
sqlParam[20] = new SqlParameter("@iOutput", 0);
sqlParam[20].Direction = ParameterDirection.Output;
try
{
Output = clsDataMan.InsertData("Factory_InsertUpdate", sqlParam);
}
catch (Exception ex)
{
Output = -1;
}
return Output;
}
public DataTable Factory_SelectAll()
{
DataTable dtResults = new DataTable();
dtResults = clsDataMan.RetrieveToDataSet("Factory_SelectAll").Tables[0];
return dtResults;
}
#region Get Factory For Help
public DataTable FGetFactory(string strFactoryCode)
{
DataTable rsResult = new DataTable();
SqlParameter[] sqlParam = new SqlParameter[1];
sqlParam[0] = new SqlParameter("@inFactory", strFactoryCode);
rsResult = clsDataMan.RetrieveToDataSet("Factory_GetFactories", sqlParam).Tables[0];
return rsResult;
}
#endregion
//public DataTable LoadFactory()
//{
// DataTable dtResults = new DataTable();
// SqlParameter[] sqlParam = new SqlParameter[0];
// dtResults = clsDataMan.RetrieveToDataSet("Factory_Select", sqlParam).Tables[0];
// return dtResults;
//}
public DataTable FactoriesByCity(int FactoryId)
{
DataTable rsResult = new DataTable();
SqlParameter[] sqlParam = new SqlParameter[1];
sqlParam[0] = new SqlParameter("@FactoryId", FactoryId);
rsResult = clsDataMan.RetrieveToDataSet("Factory_FactoriesByCity", sqlParam).Tables[0];
return rsResult;
}
}
}
A:
You Need to add the ddlCity_SelectedIndexChanged to the asp markup and in your
CS code :
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedCityId = Convert.ToInt32(ddlCity.SelectedValue);
LoadFactories(selectedCityId);
}
I am assuming your Load Factory method is as below . You need to verify that Text and Value field names are correctly coming from the Dataset .
private void LoadFactories(int CityId)
{
FactoryCls objFactory = new FactoryCls();
DataTable dtFactory = objFactory.FactoriesByCity(CityId);
ddlFactory.DataSource = dtFactory;
ddlFactory.DataTextField = "Name";
ddlFactory.DataValueField = "ID";
ddlFactory.DataBind();
ddlFactory.SelectedIndex = 0;
}
lastly check your aspx Markup and see that
you haven't given any duplicate names for your Dropdown
Make sure you set "AutoPostBack=true" in ddlCity
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get data from 3 tables with same user id?
I have 3 tables like so
Table 1: UserInfo
user_id userName
123 userOne
Table 2: Post
user_id postContent
123 This is test message
Table 3: LikePost
user_id likesPostId
123 This is test message
I would like to run a query to get total number of post likes, posts, and user information from those 3 tables.
I can do this for each one such as in Post table:
SELECT COUNT(*) FROM Post WHERE Post.user_id = '123'
and SELECT * FROM UserInfo WHERE UserInfo.user_id = '123'
Is anyone have better solution in just 1 query? Thank you so much!
A:
Try This
SELECT ui.userName,Count(p.*),
Count(lp.*) as TotalPostLikes
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
INNER JOIN LikePost lp on lp.user_id=ui.user_id
WHERE ui.user_id = '123'
GROUP BY ui.userName
If you want to select Username, Post and Likes on post, try the following
SELECT ui.userName,p.postContent as PostContent,
(SELECT COUNT(lp.user_id) FROM LikePost lp
WHERE lp.user_id=ui.user_id) as Likes,
(SELECT COUNT(_p .user_id) FROM Post _p
WHERE _p .user_id=ui.user_id) as TotalPosts
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
WHERE ui.user_id = '123'
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo guardo y leo en php con el fin de hacer un chat?
Mis bienes son especiales con solemnidad. Aquí tienen mi código en html:
<meta charset="UTF-8">
<html>
<body>
<?php
$myfile=fopen("webdictionary.txt", "r") or die("Unable to open file!")
echo fread($myfile,filesize("webdictionary.txt"))
fclose($myfile)
?>
</body>
</html>
Y aquí lo que me aparece en la página:
Parse error: syntax error, unexpected 'echo' (T_ECHO) in /home/u447364596/public_html/no funciona.php on line 7
Intenté probar también la escritura:
<meta charset="UTF-8">
<html>
<body>
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
</body>
</html>
Sin embargo no me deja escoger el contenido del archivo.
Actualización.
Nuevo código:
<meta charset="UTF-8">
<style>body{background-color:black;color:white}</style>
<script>
<?
$myfile=fopen("chat10.txt","r") or die("Unable to open file!");
$writed=fread($myfile,filesize("chat10.txt"));
fclose($myfile);
$myfile=fopen("chat10.txt","w") or die("Unable to open file!");
fwrite($myfile,$writed."An user has connected. <br>");
fclose($myfile);
?>
setInterval(function(){
document.body.innerHTML="<?
$myfile=fopen("chat10.txt","r") or die("Unable to open file!");
echo fread($myfile,filesize("chat10.txt"));
fclose($myfile);
?>"
},1)
onkeydown=function(){}
</script>
Y el error es que cuando pongo un evento de escritura a la función "onkeydown", no se me escriben las cosas cuando presiono una tecla, sino cuando entro en html, y deja de escribirse lo que inicialmente puse.
Me gustaría poder hacer un archivo php que mandase un mensaje de entrada personalizado por el usuario a un archivo.htm, y que al entrar se actualizase todo el rato, mostrando así toda la información que se ha enviado al htm, y que al presionar cierta tecla se vuelva a enviar un mensaje al archivo htm.
A:
Como complemento a la respuesta de Javier Paz Sedano puedo poner el siguiente código, esta parte lee los mensajes:
<script>
document.write("Chat started. <br>")
setInterval(function(){
xhr=new XMLHttpRequest()
xhttp.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
document.body.innerHTML=this.responseText;
}}
xhr.open("GET","mensajes.txt",true);
xhr.send()
},500)
</script>
Y esta parte los escribe:
<?
$myfile=fopen("mensajes.txt","w")
fwrite($myfile,"Nuevo mensaje.<br>")
fclose($myfile)
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
What join to use in this case?
I have our yearly sales thus far for 2017 in the query marked as Yearly and our all time Inventory marked as AllTime. I need an advice on what join I could use or what additional code I could add to my already script which would get me to show the value marked as (null) in the result. The (null) values represents Robin from the Yearly table but since I do not have that value in the AllTime query it is displayed as null in the result. If I change the order of the resultant query to from yearly left outer join alltime, Red Arrow and Captain Marvel both lose their respected spots since both have zero values in the Yearly query. If I change to from alltime left outer join yearly, the null value (Robin) goes away. Please share your advice. And as always, if you require additional details, let me know please.
with AllTime as
(select dp.Builder,
count(*) "My Inventory" from alldatainput dp
where Project_ID = 'GAP'
group by rollup ((dp.Builder))
),
Yearly as
(
select Builder,(count
(Sale_Date) filter (where extract(year from Sale_Date) = 2017
and Project_ID = 'GAP'))
- (count(Cancelled) filter (where extract(year from Cancelled) = 2017
and Project_ID = 'GAP')) as "Net for 2017"
from allsalesdata sd
and Project_ID = 'GAP'
group by rollup((Builder))
having (count(Sale_Date) filter (where extract(year from Sale_Date) = 2017
and Project_ID = 'GAP' ))
- (count(Cancelled) filter (where extract(year from Cancelled) = 2017 and
sd.Project_ID = 'GAP')) > 0
)
select alltime.Builder,coalesce(yearly."Net for 2017",0)
as "YTD Home Sales", coalesce(alltime."My Inventory",0) as "My Inventory"
from allTime
full join yearly on allTime.Builder = yearly.Builder
group by rollup((allTime.Builder,yearly."Net for 2017",alltime."My Inventory",
yearly.Builder))
order by yearly.Builder;
Result:
Builder YTD Home Sales My Inventory
Batman 3 86
Superman 5 26
Aquaman 3 29
Martian 6 84
Green Lantern 2 21
Wonder Woman 1 3
Flash 2 74
****(null) 4 0 ************
Cyborg 2 54
Batwing 5 25
Captain Marvel 0 15
Red Arrow 0 1
33 0
0 418
A:
select Builder, sum(x."YTD Home Sales") as "YTD Home Sales",
sum(x."My Inventory") as "My Inventory"
from (
select Builder, yearly."Net for 2017" as "YTD Home Sales",
0 as "My Inventory"
from yearly
UNION
select Builder, 0 as "YTD Home Sales",
alltime."My Inventory"
from alltime
) x
group by Builder
order by Builder;
| {
"pile_set_name": "StackExchange"
} |
Q:
Android unable to install the application on emulator
I have an android application and am trying to test the installation by downloading from a URL. The app is developed by me and I can load the app into emulator using eclipse and run it properly.
I uploaded the apk to webserver and point the emulators android browser to the location http://localhost:9080/myapp.apk. Emulator downloads the app properly. When I try to click on the downloaded file to install, it throws an error saying Unfortunately the process android.process.media has stopped. I am not sure how to proceed further to resolve this issue
Emulator Configuration: Android avd running on API 14, ICS 4.0.0 with 1GB sdcard.iso
Appreciate any insights.
Logcat shows the following:
07-10 19:17:19.195: I/qtaguid(380): Untagging socket 65 failed errno=-2
07-10 19:17:19.195: W/NetworkManagementSocketTagger(380): untagSocket(65) failed with errno -2
07-10 19:17:19.624: D/dalvikvm(80): GC_CONCURRENT freed 398K, 10% free 12133K/13383K, paused 10ms+10ms
07-10 19:17:20.174: D/dalvikvm(147): GC_CONCURRENT freed 699K, 31% free 11440K/16455K, paused 4ms+8ms
07-10 19:17:20.734: D/dalvikvm(147): GC_CONCURRENT freed 535K, 32% free 11325K/16455K, paused 3ms+7ms
07-10 19:17:21.025: D/dalvikvm(80): GC_EXPLICIT freed 105K, 10% free 12084K/13383K, paused 5ms+11ms
07-10 19:17:21.484: D/dalvikvm(380): GC_CONCURRENT freed 373K, 5% free 10112K/10631K, paused 4ms+5ms
07-10 19:17:24.464: W/KeyguardViewMediator(80): verifyUnlock called when not externally disabled
07-10 19:17:24.594: W/dalvikvm(380): Exception Ljava/lang/UnsatisfiedLinkError; thrown while initializing Landroid/drm/DrmManagerClient;
07-10 19:17:24.604: D/AndroidRuntime(380): Shutting down VM
07-10 19:17:24.614: W/dalvikvm(380): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
07-10 19:17:24.654: E/AndroidRuntime(380): FATAL EXCEPTION: main
07-10 19:17:24.654: E/AndroidRuntime(380): java.lang.ExceptionInInitializerError
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.providers.downloads.DownloadDrmHelper.getOriginalMimeType(DownloadDrmHelper.java:97)
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.providers.downloads.DownloadReceiver.openDownload(DownloadReceiver.java:153)
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.providers.downloads.DownloadReceiver.handleNotificationBroadcast(DownloadReceiver.java:104)
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.providers.downloads.DownloadReceiver.onReceive(DownloadReceiver.java:74)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2118)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.os.Handler.dispatchMessage(Handler.java:99)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.os.Looper.loop(Looper.java:137)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.app.ActivityThread.main(ActivityThread.java:4340)
07-10 19:17:24.654: E/AndroidRuntime(380): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 19:17:24.654: E/AndroidRuntime(380): at java.lang.reflect.Method.invoke(Method.java:511)
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-10 19:17:24.654: E/AndroidRuntime(380): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-10 19:17:24.654: E/AndroidRuntime(380): at dalvik.system.NativeStart.main(Native Method)
07-10 19:17:24.654: E/AndroidRuntime(380): Caused by: java.lang.UnsatisfiedLinkError: Library drmframework_jni not found; tried [/vendor/lib/libdrmframework_jni.so, /system/lib/libdrmframework_jni.so]
07-10 19:17:24.654: E/AndroidRuntime(380): at java.lang.Runtime.loadLibrary(Runtime.java:393)
07-10 19:17:24.654: E/AndroidRuntime(380): at java.lang.System.loadLibrary(System.java:535)
07-10 19:17:24.654: E/AndroidRuntime(380): at android.drm.DrmManagerClient.<clinit>(DrmManagerClient.java:56)
07-10 19:17:24.654: E/AndroidRuntime(380): ... 15 more
07-10 19:17:24.804: W/InputManagerService(80): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@41647c30
07-10 19:17:25.044: I/WindowManager(80): createSurface Window{415ef168 paused=false}: DRAW NOW PENDING
A:
Apparently its a bug in Android as pointed by @SevaAlekseyev above
code.google.com/p/android/issues/detail?id=21173
I was able to install by clicking on the app from downloads
| {
"pile_set_name": "StackExchange"
} |
Q:
Unit test a class that has Imported values by MEF
I have a a class called "ViewFactory" and this class should deliver the right view
right now it has only one method (and it will grow) which I want to write a unit test against.
the class looks like this...
public class ViewFactory
{
[ImportMany(AllowRecomposition=true)]
IEnumerable<ExportFactory<DependencyObject, IViewMetaData>> Views { get; set; }
public DependencyObject GetViewByName(string name)
{
DependencyObject view = null;
try
{
view = Views.Where(v => v.Metadata.ViewName == name).FirstOrDefault().CreateExport().Value;
return view;
}
catch (Exception ex)
{
return view;
}
}
}
what I do want is to test my method but don't know how to do it because the List of Views is composed on runtime...
I want to test if I get a view for a valid name
and
I also want to test if I get null if I have an invalid name
What would be the right way?
A:
You would provide your ViewFactory with a set of ExportFactory<,> values suitable for the particular test. Different tests might have different sets, to allow you to test different things. Basically you're faking the injected dependency.
| {
"pile_set_name": "StackExchange"
} |
Q:
first value as a default in Drop Down List
i need to default the first value of the drop down list and pass it to my controller.
Below is my code. Please suggest what wrong i am doing.
Component:
<aura:attribute name="pltfrmGrpOptions" type="string[]"/>
<div class="container">
<form aura:id="frm1">
<fieldset>
<ui:inputSelect aura:id="ProductPlatform" class="form-control" label="Product Platform" change="{!c.onSelectChange}" required="true">
<aura:iteration items="{!v.pltfrmGrpOptions}" var="level">
<ui:inputSelectOption value="{!level}" label="{!level}" text="{!level}" />
</aura:iteration>
</ui:inputSelect>
....
</fieldset>
</form>
</div>
i need to mark the first value in the drop down list as the default value. Please suggest.
Currently, if i do not select any value from drop down, my controller receives an undefined value.
A:
As Tushar said you shouldn't pass any blank option value in the controller. Still if you want to set a dropdown value as default value in your Lightning component you can do this as below. <aura:iteration has a attribute indexVar which provides the position of the dropdown starting from 0. You can use this with <aura:if to set value="true" for any dropdown value to make it default. In your case it will be 0 as the first one is default. Hope this helps.
Example
<aura:iteration items="1,2,3,4,5" var="item" indexVar="index">
<aura:if isTrue="{!index ==0}" >
<ui:inputSelectOption text="{!item}" value="true"/>
<aura:set attribute="else">
<ui:inputSelectOption text="{!item}"/>
</aura:set>
</aura:if>
</aura:iteration>
Your code will be updated as below
<aura:attribute name="pltfrmGrpOptions" type="string[]"/>
<div class="container">
<form aura:id="frm1">
<fieldset>
<ui:inputSelect aura:id="ProductPlatform" class="form-control" label="Product Platform" change="{!c.onSelectChange}" required="true">
<aura:iteration items="{!v.pltfrmGrpOptions}" var="level" indexVar="index">
<aura:if isTrue="{!index ==0}" >
<ui:inputSelectOption value="{!level}" label="{!level}" text="{!level}" value="true" />
<aura:set attribute="else">
<ui:inputSelectOption value="{!level}" label="{!level}" text="{!level}" />
</aura:set>
</aura:if>
</aura:iteration>
</ui:inputSelect>
....
</fieldset>
</form>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
A power series is real analytic on its radius of convergence.
Currently stuck on the last part of 15.2.8(e) of this problem:
I don't know how to apply Fubini's theorem since one index relies on the other.
Having slept on it, I've almost got it figured out except for one thing.
Part of Fubini's theorem states (in my book) that if
$$\sum_{(n,m) \in \mathbb{N} \times \mathbb{N}} f(n,m)$$
converges absolutely to some limit $L$, then
$$\sum_{n=0}^{\infty} \left ( \sum_{m=0}^{\infty} f(n, m)\right )$$
also converges absolutely to $L$.
What I'm trying to figure out is if the converse of this statement is true.
Because it seems that in order to apply Fubini's theorem to this problem it needs to be.
A:
Note that if the terms are non-negative or the double series converges absolutely then
$$
\begin{align*}
\sum_{m\geqslant 0}d_m(x-b)^m&=\sum_{m\geqslant 0}\sum_{n\geqslant m}\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\\
&=\sum_{n\geqslant m\geqslant 0}\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\\
&=\sum_{n\geqslant 0}\sum_{m=0}^n\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\\
&=\sum_{n\geqslant 0}c_n(b-a+x-b)^n\\
&=\sum_{n\geqslant 0}(x-a)^nc_n
\end{align*}
$$
To "free" one variable of the other in the summation signs you also can use some indicator function as follows:
$$
\begin{align*}
\sum_{m\geqslant 0}d_m(x-b)^m&=\sum_{m\geqslant 0}\sum_{n\geqslant m}\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\\
&=\sum_{m\geqslant 0}\sum_{n\geqslant 0}\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\,\chi _{\Bbb N \cap [m,\infty )}(n)
\end{align*}
$$
and writing the last expression as a double integral with respect to the counting measure $\delta $ we have
$$
\int_{\Bbb N }\int_{\Bbb N }\binom{n}{m}(b-a)^{n-m}(x-b)^mc_n\,\chi _{\Bbb N \cap [m,\infty )}(n)\,\delta (n)\, \delta (m)
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I remove documents of mongodb using regex expression?
I have not find a method to do it yet.
If we can not remove documents using regex expression, what can we do to make it done? And why does not mongodb provide such a driver ?
A:
The .remove() method just takes a query object, so regular expressions are just a standard query for MongoDB:
db.collection.remove({ "field": /^string/ })
Removes anything that has "field" that starts with "string"
Look at the documentation for $regex as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
SVN splitting dilemma
I have a JavaEE project as follows:
hms2 (Maven parent pom)
hms2-ear
hms2-ejb
hms2-web
Should i use one SVN repository for all, or should i split up into 4 SVN repositories?
A:
I would say use one repository. I don't see what you will gain from having several, apart from some complexity. Also the projects are related to each other(at least thematically).
A:
If you use maven and your components follow different development lifecycles you can split the SVN repo too but in conjunction with an internal maven repo (such as Artifactory or Nexus) so you let the developers be able to build their component without sources.
If your application is a single application (even if layered for separation of responsibilities purpose) you should not split.
Seeing that you are using maven modules (with parent POM) I think you are in the second case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Right and Left align linear layouts placed inside a table row
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/homeTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:id="@+id/homeFirstRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<LinearLayout
android:id="@+id/navigationLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="10dp"
android:background="#669cb7"
android:orientation="horizontal" >
<Button
android:id="@+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_call_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnPicture"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_take_pictures_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnNavigate"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_navigate_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnedo"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_pod_text"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/distanceLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#FFC58F"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SOURCE TO DESTINATION COMES HERE" />
<TextView
android:id="@+id/txtFrom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/txtTo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/txtETA"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/txtDistance"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="@+id/expandingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginLeft="10dp"
android:background="#FFC58F"
android:orientation="horizontal" >
<Button
android:id="@+id/btnLanguage"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_language_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnImages"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_image_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnMessages"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_job_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnAlerts"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_alert_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnlogout"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="@string/btn_logout_text"
android:textSize="15sp" />
</LinearLayout>
</TableRow>
Hi Above is my implementation for a home screen and and I want to left align the first Linear layout , center align the second layout and right align the last lay out.Any one knows how to do it?
A:
try using weightsum and orientation to achieve what you want.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/homeTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="10"
android:orientation="horizontal"
>
<LinearLayout
android:id="@+id/navigationLayout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_gravity="left"
android:background="#669cb7"
android:orientation="vertical"
android:layout_weight="3.3"
>
<Button
android:id="@+id/btnCall"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="btn_call_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnPicture"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="btn_take_pictures_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnNavigate"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="btn_navigate_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnedo"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="btn_pod_text"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/distanceLayout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:background="#FFC58F"
android:gravity="center"
android:orientation="vertical"
android:layout_weight="3.3"
>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="SOURCE TO DESTINATION COMES HERE" />
<TextView
android:id="@+id/txtFrom"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="" />
<TextView
android:id="@+id/txtTo"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="" />
<TextView
android:id="@+id/txtETA"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="" />
<TextView
android:id="@+id/txtDistance"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="@+id/expandingLayout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:background="#FFC58F"
android:orientation="vertical"
android:layout_weight="3.4"
>
<Button
android:id="@+id/btnLanguage"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="btn_language_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnImages"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="btn_image_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnMessages"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="btn_job_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnAlerts"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="btn_alert_text"
android:textSize="15sp" />
<Button
android:id="@+id/btnlogout"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="btn_logout_text"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
the result will something like this:
| {
"pile_set_name": "StackExchange"
} |
Q:
How to maintain volatile state in a winforms DB application where validation is required?
I am just starting to develop a C# winforms application which is to have a SQL back-end. I have classes for the user interface which allow the user to enter data. However there will also be validation, some options are conditional on other options, and on the forms there will be some read-only fields implemented using labels. A good example of the latter is when the user enters a discount rate and a price and it displays the discounted price.
I have business logic classes for the data objects. Would you:
Instantiate these only at the point of saving and loading to/from
the database, and hold state in the properties of the controls OR
Keep the business logic objects constantly in memory and update them
whenever the user enters/edits information?
Option 2 sounds like hard work as you have to handle everything changing on your forms. However, since you have an object in existence you can use that object to do the validation/calculations. You can call the DiscountedPrice property, for example.
A:
An object in the business logic layer will exist all the time, I have chosen option 2. I will bind the object to the controls like this:
textBox1.DataBindings.Add("Text", example, "Datum");
Where Text is the Text property of a text box, and example.Datum is the property of the object in the business logic layer.
Those read-only fields on the form can then be implemented via properties of the object in the business logic layer. This means I can keep the logic out of the UI layer.
| {
"pile_set_name": "StackExchange"
} |
Q:
How big a set can we get from this construction?
Construct a set $X\subset (0,1)$ likewise:
Consider some irrational $x$ in $(0,1)$ which we represent in base $2$ e.g. $x=0.\,m_1m_2\,...$ where $m_i\in\{0,1\}$ for all $i$. Add it to $X$.
Consider another irrational $x'\in (0,1)$ and choose $S=\{s_1,\, s_2,\cdots\}\subset \mathbb{N}$ such that $x'=0.\,m_{s_1}m_{s_2}\,\ldots$ and add it to $X$.
Consider another irrational $x''\in (0,1)$ and choose $S'=\{s'_1,\, s'_2,\ldots\}\subset S$ such that $x''=0.\,m_{s'_1}m_{s'_2}\,\ldots$ and add it to $X$.
etc.
Am I correct in saying that the end set $X=\{x,x',\, ...\}$ will be countable? Is there any way to amend this construction so that we end up with an uncountable set?
The intial question was to find a chain $\mathbb{N}\supset S\supset S'\supset \cdots,$ if there is one, such that $\Sigma =\{\mathbb{N},S,S',\,\ldots\}$ is not countable.
A:
The initial question has a much simpler solution. The process that you suggest seem to end up with a countable set simply because you define this process by induction, but you don't say what happens after we exhausted all the finite indices.
For that purpose we have ordinals, which generalize the natural numbers to the transfinite. This allows us to use induction and recursion longer than just the natural numbers themselves, and indeed we can do induction with uncountably many steps. But for that you need to say what happens when you reach a limit point, i.e. when you exhausted all the available "immediate next step"'s.
Whether or not your idea can be carried over, I cannot say. I'm not fully sure that I understand what is it that you are trying to do. Note that you don't even describe the process right. It would be as if you were telling me something like this:
Consider the sequence $a_0=1, a_1=50, a_2=\pi,$ etc. Does it converge?
It's hard to say what should $a_3$ be, or if there is a general formula for the sequence. Instead you should say exactly what is the process. Something like this:
We begin with $x\in(0,1)$. We do [...]; suppose that we have defined a set $S$, if there is some $x'\in(0,1)$ such that [...] then we do [...].
Now we can claim that $S$ is uncountable, for example, by showing that no countably many elements exhaust the process of definition.
But let me give you a hint for the solution of the actual problem: the rational numbers are countable, and they are dense in $\Bbb R$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to port a JavaScript part of a MongoDB query to PyMongo
I have the the following MongoDB query thanks to https://stackoverflow.com/a/26436244/977828
var judge = function () {
var unexpect = "X";
var letter1 = unexpect, letter2 = unexpect;
for (var i in this.chr) {
var chr = this.chr[i];
if (chr.no == 5) {
letter1 = chr.letter;
} else if (chr.no == 6) {
letter2 = chr.letter;
}
}
if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
return true;
}
return false;
};
db.sss.find({
"pos": { "$gte": 200000, "$lt": 2000000 },
"$where": judge
}, {"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, _id:0});
I tried to port the above query to PyMongo, but I don't know where to put the JavaScript function.
from pymongo import MongoClient
db = MongoClient().test
sDB = db.sss
r = [["Test", "A", "B01", 828288, 1, 7, 'C', 4],
["Test", "A", "B01", 828288, 1, 7, 'C', 5],
["Test", "A", "B01", 828288, 1, 7, 'T', 6],
["Test", "A", "B01", 171878, 3, 8, 'C', 5],
["Test", "A", "B01", 171878, 3, 8, 'T', 6],
["Test", "A", "B01", 871963, 3, 9, 'A', 5],
["Test", "A", "B01", 871963, 3, 9, 'G', 6],
["Test", "A", "B01", 1932523, 1, 10, 'T', 4],
["Test", "A", "B01", 1932523, 1, 10, 'A', 5],
["Test", "A", "B01", 1932523, 1, 10, 'X', 6],
["Test", "A", "B01", 667214, 1, 14, 'T', 4],
["Test", "A", "B01", 667214, 1, 14, 'G', 5],
["Test", "A", "B01", 667214, 1, 14, 'G', 6]]
for i in r:
sDB.update({'type': i[0],
'name': i[1],
'sub_name': i[2],
'pos': i[3],
's_type': i[4],
'x_type': i[5]},
{"$push": {
"chr":{
"letter":i[6],
"no": i[7]} }},
True)
# var judge = function () {
# var unexpect = "X";
# var letter1 = unexpect, letter2 = unexpect;
# for (var i in this.chr) {
# var chr = this.chr[i];
# if (chr.no == 5) {
# letter1 = chr.letter;
# } else if (chr.no == 6) {
# letter2 = chr.letter;
# }
# }
# if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
# return true;
# }
# return false;
# };
results = sDB.find({
"pos": { "$gte": 200000, "$lt": 2000000},
"$where": judge
},
{"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, "_id":0})
for i in results:
print i
How is it possible to integrate the JavaScript function to PyMongo?
A:
With PyMongo you should be able to pass the JavaScript for $where as a string, e.g. like this:
# JavaScript as multiline string
judge = """
function () {
var unexpect = "X";
var letter1 = unexpect, letter2 = unexpect;
for (var i in this.chr) {
var chr = this.chr[i];
if (chr.no == 5) {
letter1 = chr.letter;
} else if (chr.no == 6) {
letter2 = chr.letter;
}
}
if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
return true;
}
return false;
};
"""
results = sDB.find({
"pos": { "$gte": 200000, "$lt": 2000000},
"$where": judge
},
{"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, "_id":0})
| {
"pile_set_name": "StackExchange"
} |
Q:
HMAC SHA256 hash computation in C#
I need to calculate the HMAC by using the SHA256 hash function. I have a secret key encoded in base64 format. Also there is an online tool that correctly calculate the HMAC (verified).
http://www.freeformatter.com/hmac-generator.html
I wrote the following code snippet:
var signatureHashHexExpected = "559bd871bfd21ab76ad44513ed5d65774f9954d3232ab68dab1806163f806447";
var signature = "123456:some-string:2016-04-12T12:44:16Z";
var key = "AgQGCAoMDhASFAIEBggKDA4QEhQCBAYICgwOEBIUAgQ=";
var shaKeyBytes = Convert.FromBase64String(key);
using (var shaAlgorithm = new System.Security.Cryptography.HMACSHA256(shaKeyBytes))
{
var signatureBytes = System.Text.Encoding.UTF8.GetBytes(signature);
var signatureHashBytes = shaAlgorithm.ComputeHash(signatureBytes);
var signatureHashHex = string.Concat(Array.ConvertAll(signatureHashBytes, b => b.ToString("X2"))).ToLower();
System.Diagnostics.Debug.Assert(signatureHashHex == signatureHashHexExpected);
}
PROBLEM:
My code does not generate the correct HMAC. I verified different steps by using different online tools and alternative C# implementations. Only the conversion from base64 is not confirmed. What am i missing?
UPDATE:
Calculated signatureHashHex by my code is "a40e0477a02de1d134a5c55e4befa55d6fca8e29e0aa0a0d8acf7a4370208efc"
ANSWER:
The issue was caused by a misleading documentation stating the key is provided in Base64 format. See the accepted answer:
var shaKeyBytes = System.Text.Encoding.UTF8.GetBytes(key);
A:
Your result is correct, the difference is because the tool you link to does not decode Base64 for the key value and treats it as a series of characters.
E.g. To duplicate its result treat your key as a string:
var shaKeyBytes = System.Text.Encoding.UTF8.GetBytes("AgQGCAoMDhASFAIEBggKDA4QEhQCBAYICgwOEBIUAgQ=");
Which yields
559bd871bfd21ab76ad44513ed5d65774f9954d3232ab68dab1806163f806447
(This is obviously not the right way to do it)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to apply notifications in OnItemClickListener?
I have 3 errors in the code of notification using OnItemClickListener
i need to apply that when an item is clicked it display notification
here is the code:
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Bundle programNum = getIntent().getExtras();
final String progNum = programNum.getString("ProgNum");
final String dayNum = programNum.getString("DayNum");
final List<TouringPrograms> startTime = datasource.getTouringProgramsStartTime(progNum, dayNum);
final List<TouringPrograms> endTime = datasource.getTouringProgramsEndTime(progNum, dayNum);
Intent intent = new Intent(this, ProgramsList2.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
String body = (String) ((TextView)parent.getChildAt(position)).getText();
String title = "Egypt On The Go";
String time = body + "\n start at:" + startTime.get(position)+ "\n end at:" + endTime.get(position);
Notification n = new Notification(R.drawable.egypt, time, System.currentTimeMillis());
n.setLatestEventInfo(this, title, time, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(uniqueID, n);
//String time1 = "" + System.currentTimeMillis();
//Toast.makeText(this, time1, Toast.LENGTH_SHORT).show();
//finish();
}});
the 3 error :
1.Intent intent = new Intent(this, ProgramsList2.class);
2.PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
3.n.setLatestEventInfo(this, title, time, pi);
any help please?
A:
Error 1
Intent intent = new Intent(this, ProgramsList2.class);
this is an item of type OnItemClickListener. You should pass it by declaring final Context intentContext = (Context) this; before calling setOnItemClickListener. Then, use:
Intent intent = new Intent(intentContext, ProgramsList2.class);
Always remember to keep track of your Context items; they're important for things like this (Intents, resources, assets, etc.).
Error 2
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Exactly the same problem as above. this is not of type Context. Use the same fix as above.
Error 3
n.setLatestEventInfo(this, title, time, pi);
And here, same issue as the above two. You're using this when you should be using a Context. Same fix as the above two.
Summary
Keep track of your thiss when using anonymous classes. And for the future, posting the compile errors (the line of code as well as the text of the error itself) is incredibly helpful to those who will provide answers.
| {
"pile_set_name": "StackExchange"
} |
Q:
what's the associated html to load images?
I'm trying to figure out how to load images from my images directory.
<script src="jquery-1.7.2.min.js"></script>
$("<img>", {
"src": "url.php...",
"load": function() {
alert("loaded!");
$("#foo").attr("src", "url.php...");
}
});
For the html, I'm not sure how to get started. I tried this: <img id="foo" src="$('#img').attr('src');">, but I'm thinking I'm not escaping html properly.
A:
You must set response data from server to image source like this
Js
$.ajax({
url: "url.php"
}).done(function( data ) {
$("#img").attr("src", data );
});
PHP (url.php)
echo '/images/1.jpg';
| {
"pile_set_name": "StackExchange"
} |
Q:
Twitter typeahead 0.1 w/ bloodhound -- can't get prefetch working with URL
I have this code in JS which works very well.
var values = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.num); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/url/that/returns/json'
});
But, since I only need to this once, I changed it to a prefetch, as below:
var values = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.num); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {url: '/url/that/returns/json'}
});
This causes an error ("TypeError: a is undefined") in typeahead.js. What do I need to change to get this functionality working?
EDIT: The json returned is if I visit the URL in my browser is:
[{"name":"MyName","id":"100","code":"CODE"}]
A:
This was caused by the fact that my datumTokenizer was looking for a field called num:
... return Bloodhound.tokenizers.whitespace(d.num)
But there was no such field in my JSON. I have no idea why this worked with remote, but it didn't work in prefetch. The fix was then to replace d.num with d.name.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove if $\{x^iy^jz^k \mid i \le2j\text{ or }j \le 3k\}$ is regular or not
$$L = \{x^iy^jz^k \mid i \le2j\text{ or }j \le 3k\}$$
To Prove: If given language is regular or not.
I know that it is not a regular language but I am not able to come up with the string which I can use in the pumping lemma to prove that it is not regular.
We can also divide $L$ into two parts:
$$\begin{align*}
L_1 &= \{x^iy^jz^k \mid i \le 2j\}\\
L_2 &= \{x^iy^jz^k \mid j \le 3k\}\,,
\end{align*}$$
so I just need the strings to be used in the pumping lemma for $L_1$ and $L_2$.
A:
It's not regular. Hint: Let $p$ be the integer of the pumping lemma and pump the string $x^{6p}y^{3p}z^{2p}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
"wcs" and "_w" and "_mbs" prefix in Visual Studio
I am a little confused with respect to the difference in the functions which are defined with/without the wcs/_w/_mbs prefix.
For Example:
fopen(),_wfopen()
On msdn it is given that:
The fopen function opens the file that is specified by filename.
_wfopen is a wide-character version of fopen; the arguments to _wfopen are wide-character strings. Otherwise, _wfopen and fopen behave
identically.
I just had a doubt whether there is any platform dependence to windows associated with the addition of the "_w" prefix.
strcpy(),wcscpy(),_mbscpy()
On msdn it is given that:
wcscpy and _mbscpy are, respectively, wide-character and multibyte-character versions of strcpy.
Again there is a doubt if the addition of "wcs" or "_mbs" is platform dependent.
EDIT:
Is WideCharToMultiByte function also platform dependent?
WideCharToMultiByte is not a C Runtime function, it's a Windows
API,hence it is platform dependent
Similarly is wcstombs_s function also platform dependent?
It was nonstandard but was standardized in C11 Annex K.
A:
The wcs* functions like wcscpy are part of the C Standard Library. The _wfopen function and other _w* functions are extensions, as are the multibyte string functions like _mbscpy.
For the most part, Visual C++ C Runtime (CRT) functions that have a leading underscore are extensions; functions that do not have a leading underscore are part of the C Standard Library.
There are two main exceptions, where extensions may not have leading underscores:
There are several extension functions, declared with an underscore prefix, that have prefixless aliases for backwards source compatibility. These aliases are deprecated, and if you try to use them you'll get a suppressable deprecation warning (C4996).
There are _s-suffixed secure alternative functions to some C Standard Library functions, e.g. scanf_s. These are declared by default, but their declarations may be suppressed by defining the macro __STDC_WANT_SECURE_LIB__ to have the value 0.
(These functions were actually added to C11 in the optional Annex K,
but note that there are a few differences between what is specified
in the C Standard and what is implemented by Visual C++. The
differences are due to a historical
accident.)
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql remove char in nth position
I need to remove 3rd hyphen(-) or the last hyphen from every records on my table.
this is the sample data
2009-12245-5432112310000-4
2009-12245-5431212320000-
2009-12245-H196812310000-
2009-12245-C026512310000-0
Output should be like this after UPDATE
2009-12245-54321123100004
2009-12245-5431212320000
2009-12245-H196812310000
2009-12245-C0265123100000
Is there any mysql function can I used together with UPDATE command? I know replace() command but I think it has no parameter for specific position of char to replace.
Thanks
A:
You have to use combination of CONCAT() and SUBSTRING_INDEX(). Try below query:
UPDATE tblName
SET column = CONCAT(SUBSTRING_INDEX(column,'-',3),SUBSTRING_INDEX(column,'-',-1));
It will concatenate first substring and last substring. Below is the output:
+---------------------------+
| 2009-12245-54321123100004 |
| 2009-12245-5431212320000 |
| 2009-12245-H196812310000 |
| 2009-12245-C0265123100000 |
+---------------------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set Build Action on a file - Advanced Properties Not Displayed in properties window
There is no advanced properties settings available for the files in my ASP NET 4.0 project in VS2010. I have looked through the options settings and I dont see how to turn them on.
I am looking for the Build Action setting so I can set to Embedded Resource.
Is this only available if the project is compiled to an assembly DLL?
Here's a screen shot from 4guysfromrolla sample. Note that their sample is a user control.
A:
The response marked as the answer is not correct. These properties are available for ASP.NET applications, but only if the project type is a web application.
Files on websites, in contrast, do not have these properties. The reason is that the Build Action, for example, is stored in the project file. Since websites lack project files, the Build Action cannot be set.
A:
After some more research I found that a file's Build Action is in fact only available on a project that compiles to an EXE or DLL such as a web control. It is not available for files within an ASP NET application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Basic Program acting odd
Before i start explaining my problem, i want to make clear that i'm no programming expert and nor do i claim to be great, i just made a VB program for fun
Now... the question... so i made this program where it converts text into Discord emoji text, the solution does seem to be functional and works as it should no problems until i go above two lines of code in the text conversion part because when i do that the program outputs incorrect and messed up text, sometimes it will convert 2 letters into thousands of letters and i can't figure out why, sometimes it freezes and then displays the OutofMemory exception
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
TextBox1.Text = TextBox1.Text.Replace("a", ":regional_indicator_a: ")
TextBox1.Text = TextBox1.Text.Replace("b", ":regional_indicator_b: ")
TextBox1.Text = TextBox1.Text.Replace("c", ":regional_indicator_c: ")
Form3.Refresh()
Form3.Show()
Form3.TextBox1.Text = TextBox1.Text
End Sub
A:
you are doing an unintentional nested loop on each replaces after the first one as each line tries to replace text that was already changed on previous lines.
try to change the text characters like this as it is a character replacement of a single entry.
Dim out = ""
For Each c As Char In TextBox1.Text
out += ":regional_indicator_" + c + ": "
Next
TextBox1.Text = out
the last line changes the TextBox1.Text itself, and if you want to put "out" to somewhere else, change that line.
by the way, I don't know why you try to Refresh() and Show() the form again, but if you have to, then put those 2 lines AFTER textbox assignment, not before.
| {
"pile_set_name": "StackExchange"
} |
Q:
Camera does not support setVideoSize()
i try to record video and play
I noticed that many devices crasheed when start to record video.
from logcat I realized the problem is the size of the video.
the camera view is small , a few pixels, is this the problem?
What do I need to fix? How?
private boolean prepareVideoRecorder() {
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO)
.toString());
outputFileName = getOutputMediaFile(MEDIA_TYPE_VIDEO).toString();
Log.d(TAG,"idan outputFileName" + outputFileName);
// Step 5: Set the preview output
// mMediaRecorder.setVideoSize(640, 480); //try
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG,
"IllegalStateException preparing MediaRecorder: "
+ e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
Log.d(TAG,"surfaceCreated camera id" + mCamera );
try {
CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight);
mCamera.setParameters(parameters);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
logcat error :
06-02 19:29:14.177: D/CameraSource(115): Camera does not support setVideoSize()
06-02 19:29:14.177: D/CameraSource(115): Requested video size (1920x1088) isSetVideoSizeSupportedByCamera 0
06-02 19:29:14.177: E/CameraSource(115): Video dimension (1920x1088) is unsupported
06-02 19:29:14.177: D/CameraService(115): unlock (pid 115)
06-02 19:29:14.177: D/QualcommCameraHardwareZSL(115): virtual bool android::QualcommCameraHardware::recordingEnabled() recordingState=0
06-02 19:29:14.177: D/CameraService(115): clear mCameraClient (pid 115)
06-02 19:29:14.177: E/MediaRecorder(30873): start failed: -19
06-02 19:29:14.177: V/MediaRecorderJNI(30873): process_media_recorder_call
06-02 19:29:14.177: E/MediaRecorder(30873): start failed.
06-02 19:29:14.177: E/MediaRecorder(30873): try to delete broken file: /mnt/sdcard/Movies/Your_voice/Your_voice020613_192914.mp4
06-02 19:29:14.187: D/AndroidRuntime(30873): Shutting down VM
06-02 19:29:14.187: W/dalvikvm(30873): threadid=1: thread exiting with uncaught exception (group=0x40ac3228)
06-02 19:29:14.187: E/AndroidRuntime(30873): FATAL EXCEPTION: main
06-02 19:29:14.187: E/AndroidRuntime(30873): java.lang.RuntimeException: start failed.
06-02 19:29:14.187: E/AndroidRuntime(30873): at android.media.MediaRecorder._start(Native Method)
06-02 19:29:14.187: E/AndroidRuntime(30873): at android.media.MediaRecorder.start(MediaRecorder.java:712)
06-02 19:29:14.187: E/AndroidRuntime(30873): at com.example.uploadvideo.MainActivity.onPlaying(MainActivity.java:165)
A:
CamcorderProfile.get(int) returns the profile for default (rear) camera. If your mCamera is the front camera, you should use CamcorderProfile.get(int, int) with the appropriate cameraId.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nginx El Capitan ERR_CONNECTION_REFUSED
I Have installed Nginx-full via homebrew to the latests stable 1.8.1 version. I have installed php7.0 via brew as well. I want to get php working but i can't first get nginx to serve a static file. I have this configuration on a server and works perfectly but on my mac I'm having trouble. I set up my sites directory as follows:
nginx.conf:
#user www-data www-data;
worker_processes 4;
events {
worker_connections 1024;
}
http {
include mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
/sites-available/default
server {
listen 80;
server_name localhost;
root /Users/londreblocker/Developer/Sites/bootstrap;
index index.php
error_log /Users/londreblocker/Logs/DMFA_erros.log;
access_log
/Users/londreblocker/Logs/DMFA_access.log;
}
there is a symbolic link to default in the sites-enabled folder. When i try to connect all i get is
This webpage is not available
ERR_CONNECTION_REFUSED
Any idea what could be going wrong. I am on a mac with El Capitan.
A:
Check if nginx configuration is correct:
sudo nginx -t
and your config symlinks not broken:
ls -al /etc/nginx/sites-enabled
Check if nginx running:
ps aux |grep nginx
Check if nginx listening port 80:
sudo lsof -i -P | grep -i "listen"
| {
"pile_set_name": "StackExchange"
} |
Q:
Best startup JSF 2.2 archetype
What is the best maven archetype to start a JSF 2.2 project in Eclipse EE with?
I am currently learning JSF and am looking for a clean maven archetype to start my JSF project with. I tried a few archetypes with jsf in the title, but they don't seem to create a "clean" (no problems found) in eclipse. I am looking for an answer from experience.
A:
I think there is no best one as every archetype comes with stuff one does not want. Since every one is different some modifications will always be required.
I would give the appfuse archetypes a try: http://appfuse.org/display/APF/AppFuse+QuickStart
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-light-jsf-archetype -DarchetypeVersion=2.2.1 -DgroupId=com.mycompany -DartifactId=myproject -DarchetypeRepository=http://oss.sonatype.org/content/repositories/appfuse
I think they use MyFaces 2.1.9 but that should be easy to change :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery dynamically generated content sibling issue
I'm getting close to the solution I'm looking for, but have one more issue that's giving me fits. Here is my fiddle: (http://jsfiddle.net/CjHAD/10)
I need to clean this up so that when red click div is open and I open black click div, the blue click thumb doesn't duplicate itself inside the .parent-box sibling.
Any tips in general on making this more graceful, fluid, and efficient are welcomed, and I'm happy to clarify if needed!
Here is the code:
Here is the code:
HTML:
<div class="parent-box">
<h3>2013</h3>
<div class="works-post">
<div class="x-image" style="color: red">click</div><!--open/close content-->
<div class="works-thumb">
<img width="150" height="112" />
</div><!--.works-thumb-->
<div class="toggle-content">
<h4>Content</h4>
</div><!--.toggle-content-->
</div><!--.works-post-->
</div><!--.parent-box-->
<div class="parent-box">
<h3>2012</h3>
<div class="works-post">
<div class="x-image" style="color: blue">click</div><!--open/close content-->
<div class="works-thumb">
<img width="150" height="112" />
</div><!--.works-thumb-->
<div class="toggle-content">
<h4>Content</h4>
</div><!--.toggle-content-->
</div><!--.works-post-->
<div class="works-post">
<div class="x-image">click</div><!--open/close content-->
<div class="works-thumb">
<img width="150" height="112" />
</div><!--.works-thumb-->
<div class="toggle-content">
<h4>Content</h4>
</div><!--.toggle-content-->
</div><!--.works-post-->
</div><!--.parent-box-->
my CSS:
h3 {
clear: both;
width: 100%;
}
.x-image {
border: solid thin #000;
float: left;
padding: 0 2px 0 0;
position: relative;
z-index: 15;
}
.works-thumb {
margin: 5px 0 0 10px;
width: 25%;
}
.works-thumb img {
border: solid 2px #a8b9b7;
}
.works-post {
border: none;
float: left;
padding-bottom: 2em;
}
.toggle-content {
display: none;
margin: 0px 0 0 1.5em;
padding-bottom: 1em;
min-height: 150px;
}
.open {
background-color: #eee;
clear: both;
width: 100%;
border-top: solid thin #ccc;
border-bottom: solid thin #ccc;
}
and my jQuery:
$(document).ready(function(){
$('.x-image').on('click', (function(event){
var other = $(this).parent().siblings('.works-post');
var beyond = $(this).closest('.parent-box').siblings().find('.works-post');
$(this).closest('.works-post').find('.works-thumb').toggle('fast');
$(this).closest('.works-post').find('.toggle-content').slideToggle('fast', function(){
$(this).closest('.works-post').toggleClass('open',$(this).is(':visible'));
other.removeClass('open').insertAfter($('.open'));
other.find('.toggle-content').hide();
other.find('.works-thumb').show();
beyond.removeClass('open');
beyond.find('.toggle-content').hide();
beyond.children('.works-thumb').filter(':hidden').show();
})
}))
});
Thanks!
A:
Removing the call to .insertAfter($('.open')) seems to solve the issue you are referencing. At the time that method is called, there are two elements with the class open and you are therefore inserting the contents of other in two places. What is your intent with performing the insert?
other.removeClass('open');
jsfiddle
Update:
If you are trying to move the opened works-post to the top of the set in its parent-box, you can do so by using .insertBefore() in reference to other.first().
I took the liberty of modifying your code a bit for clarity. It essentially does the same thing as the original besides the removal of the .insertAfter() and the addition of the .insertBefore() at the end.
$(document).ready(function () {
$('.x-image').on('click', (function (event) {
var thisPost = $(this).closest('.works-post');
var thisBox = $(this).closest('.parent-box');
var otherPosts = thisPost.siblings('.works-post');
var beyondPosts = thisBox.siblings('.parent-box').find('.works-post');
thisPost.find('.works-thumb').toggle('fast');
thisPost.find('.toggle-content').slideToggle('fast', function () {
thisPost.toggleClass('open', $(this).is(':visible'));
otherPosts.removeClass('open');
otherPosts.find('.toggle-content').hide();
otherPosts.find('.works-thumb').show();
beyondPosts.removeClass('open');
beyondPosts.find('.toggle-content').hide();
beyondPosts.children('.works-thumb').filter(':hidden').show();
thisPost.insertBefore(otherPosts.first());
});
}));
});
jsfiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Azure Backup & Restore strategy
We have a web based (ASP.NET MVC) application that uses SQL Server 2008 for its database.
Because the data is important to us (and our clients), we have a Backup & Restore strategy in place which, in a nutshell, looks like this:
-Weekly: Full database backup
-Nightly: Differential backup
-Hourly: Log backup
The strategy we use was greatly influenced by listening to a webcast done by Kimberly Tripp (which can be viewed here: https://msevents.microsoft.com/CUI/EventDetail.aspx?culture=en-US&EventId=1032278589&CountryCode=US).
Question:
Since we are looking into moving the database to SQL Azure, I wanted to know if anyone has put in place a similar Backup & Restore strategy within SQL Azure.
Has anyone encountered any known issues with trying to put in place a Backup & Restore strategy with Azure?
Thanks for any help on this.
A:
Backup/restore is a whole different animal in SQL Azure as the traditional backup/restore commands are not available. See the article SQL Azure Backup and Restore Strategy for a good overview and then read Copying Databases in SQL Azure. Also take a look at redgate's (beta) third party tool for SQL Azure Backup.
EDIT: Adding a reference to a new blog post that appeared today (Sept 29, 2011): Data backup strategies for Windows and SQL Azure
| {
"pile_set_name": "StackExchange"
} |
Q:
Get a pattern in a string starts and ends with a specific character
I am working on shell script and I want to get a pattern in a string starts and ends with a specific character. As much as I can do was:
a=`grep -oh ^\/ $1`
grep -oh \'$ $a
I know that grep -oh command finds a word in a file and prints it so I tried to find the words starts with / and ends with '.
But it still finds words, but I need patterns to find, like if /bin/ls'dir is the string, I have to get /bin/ls. Also like this I can not suppress ' character at the end.
How could it be done?
A:
Perl regular expressions are handy with the lookahead assertions:
str="like if /bin/ls'dir is the string, I have to get /bin/ls. "
grep -oP "/.*?(?=')" <<< "$str"
/bin/ls
| {
"pile_set_name": "StackExchange"
} |
Q:
How to test a Platform Event Trigger that makes callout(s)?
I am integrating with a third-party API that calls an unauthenticated webhook (HTTP Post) that I have implemented with a small payload; my code then uses that payload to make an authenticated call to the remote API to fetch the sensitive data associated with the notification. For various reasons, we have implemented the inbound HTTP Post by publishing platform events. There is a trigger that fires on the event; it is responsible for making the callout to the remote API and taking action on the result.
I can test all of the pieces in separation, but when I attempt to test the Trigger by publishing an event, I get a System.CalloutException: Callout from triggers are currently not supported error, even though I have mocked the HTTP request. I know the mocking works, as I have other tests which use the same mocking setup and call the Trigger handler directly. I'm guessing that when the EventBus fires the event in test context, the Trigger must run in a different context which does not see the HttpCalloutMock that I've setup. And yes, I have wrapped the EventBus.publish() call in Test.startTest()/Test.stopTest(), and I have tried manually delivering the event with Test.getEventBus().deliver(). Here's my current test method:
@IsTest
static void testTrigger() {
setupMocks(); // used by all test which make callouts
MY_Platform_Event__e evt = new MY_Platform_Event__e(
EventType__c = 1,
PackageId__c = '717cda19-b348-447c-96b4-018ac806be13',
MessageId__c = '717cda19-b348-447c-96b4-018ac806be13\\1',
Description__c = 'Package.Create',
Environment_Token__c = ENV_TOKEN
);
Test.startTest();
Database.SaveResult sr = EventBus.publish(evt);
System.assertEquals(true, sr.isSuccess());
Test.getEventBus().deliver();
Test.stopTest();
}
I really only need the required 1% code coverage for my trigger, as all of the handler logic is tested elsewhere in isolation. Because the whole point of the Trigger is to call the remote API, however, I can't construct even a minimum test that will successfully fire the trigger, unless I add an Test.isRunningTest() check inside the Trigger handler. I can do so if needed, but the need for such a test is a red flag to me that I need to check my assumptions. Is it possible to test a Platform Event Trigger that makes an HTTP callout, without using Test.isRunningTest() to skip the callout?
edit to add: upon reflection, I can't even use Test.isRunningTest() in the handler, since the handler is called directly in other tests. I can either check Test.isRunningTest() directly in the Trigger, or use a @TestVisible private Boolean flag in the handler to allow a test method to turn off the callout code... neither of which approaches do I like.
A:
Apex triggers can't do synchronous callouts. This includes Apex triggers that subscribe to/consume Platform Events.
It doesn't really matter (in the testmethod) whether the platform events are delivered by:
Test.getEventBus().deliver() or
Test.stopTest() without the deliver()
because the exception is caused by a trigger doing a synchronous callout.
You need to delegate the callouts to one of the Apex async feature: future, queueable, batchable, schedulable. Which you choose will determine how your testmethod is written.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlibplot and scipy Interpolate: Show and evenly disperse Dates
In Python I am trying to plot two graphs and I am really struggling madly with the dates on the x-axis, since I am using interpolate from scipy which does not accept the dates format that matlibplot does accept. I achieved conversion to acceptable formats but then my graph is squashed and the dates are all printed on above each other at one place.
This is the original code:
f = interp1d(dates_unix_raw, pis_raw, kind='cubic')
g = interp1d(dates_unix_io, pis_io, kind='cubic')
x = np.linspace(dates_unix_raw[0],dates_unix_raw[-1],smooth_factor_raw)
y = np.linspace(dates_unix_io[0],dates_unix_io[-1],smooth_factor_io)
plt.plot(x, f(x), '-')
plt.plot(y, g(y), '--')
plt.xlabel("Time-Delta: " + str(dates_raw[0]) + " - " + str(dates_raw[-1]))
plt.ylabel('PIs')
plt.gcf().autofmt_xdate()
plt.title(domain)
I have above code producing below output
You can find the full code here: http://codepad.org/GvfKoyfP
In dates_raw and dates_io I have a list of supposedly Matlibplot-acceptable ".strftime-formatted" Dates and in dates_unix_raw and dates_io_raw I have Unix timestamps.
pis_raw and pis_io are lists with integer values.
Q: How can I show the dates from either dates_io or dates_raw (it does not matter which) on the x-axis, evenly dispersed?
A:
Looks like your data_raw and data_io are the same. The following example should get you there:
import matplotlib as mpl
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
dates_unix_raw = [1402185606.0, 1402272005.0, 1402358406.0, 1402444805.0, 1402531206.0, 1402617606.0, 1402704005.0, 1402790405.0, 1402876804.0, 1402963205.0, 1403049605.0, 1403136005.0, 1403222406.0, 1403308807.0, 1403395206.0, 1403481606.0, 1403568006.0, 1403654405.0, 1403740805.0, 1403827205.0, 1403913605.0, 1404000006.0, 1404086405.0, 1404172805.0, 1404259206.0, 1404345605.0, 1404432004.0, 1404518405.0, 1404604806.0, 1404691206.0]
dates_unix_io = [1402178400.0, 1402264800.0, 1402351200.0, 1402437600.0, 1402524000.0, 1402610400.0, 1402696800.0, 1402783200.0, 1402869600.0, 1402956000.0, 1403042400.0, 1403128800.0, 1403215200.0, 1403301600.0, 1403388000.0, 1403474400.0, 1403560800.0, 1403647200.0, 1403733600.0, 1403820000.0, 1403906400.0, 1403992800.0, 1404079200.0, 1404165600.0, 1404252000.0, 1404338400.0, 1404424800.0, 1404511200.0, 1404597600.0, 1404684000.0]
dates_raw = ['2014-06-08', '2014-06-09', '2014-06-10', '2014-06-11', '2014-06-12', '2014-06-13', '2014-06-14', '2014-06-15', '2014-06-16', '2014-06-17', '2014-06-18', '2014-06-19', '2014-06-20', '2014-06-21', '2014-06-22', '2014-06-23', '2014-06-24', '2014-06-25', '2014-06-26', '2014-06-27', '2014-06-28', '2014-06-29', '2014-06-30', '2014-07-01', '2014-07-02', '2014-07-03', '2014-07-04', '2014-07-05', '2014-07-06', '2014-07-07']
dates_io = ['2014-06-08', '2014-06-09', '2014-06-10', '2014-06-11', '2014-06-12', '2014-06-13', '2014-06-14', '2014-06-15', '2014-06-16', '2014-06-17', '2014-06-18', '2014-06-19', '2014-06-20', '2014-06-21', '2014-06-22', '2014-06-23', '2014-06-24', '2014-06-25', '2014-06-26', '2014-06-27', '2014-06-28', '2014-06-29', '2014-06-30', '2014-07-01', '2014-07-02', '2014-07-03', '2014-07-04', '2014-07-05', '2014-07-06', '2014-07-07']
pis_raw = [205742, 233162, 290272, 364284, 363555, 340799, 313614, 274266, 311757, 353822, 360780, 335548, 355210, 342263, 246891, 321237, 69446, 20, 24, 12, 9, 10, 22, 11, 12, 266469, 323873, 256060, 281979, 313210]
pis_io = [213660, 240602, 298600, 374582, 375739, 353645, 324713, 281913, 318321, 364016, 368859, 345466, 364679, 352250, 253938, 327049, 73698, 21, 19, 9, 9, 16, 11, 9, 6, 272650, 338088, 264947, 284192, 314740]
f = interp1d(dates_unix_raw, pis_raw, kind='cubic')
g = interp1d(dates_unix_io, pis_io, kind='cubic')
x = np.linspace(dates_unix_raw[0],dates_unix_raw[-1],100)
y = np.linspace(dates_unix_io[0],dates_unix_io[-1],100)
T = pd.to_datetime(dates_raw)
plt.plot(mpl.dates.num2date(np.linspace(*mpl.dates.date2num(T.to_pydatetime())[[0, -1]], num=100)), f(x), '-')
plt.plot(mpl.dates.num2date(np.linspace(*mpl.dates.date2num(T.to_pydatetime())[[0, -1]], num=100)), g(y), '--')
plt.xlabel("Time-Delta " + str(dates_raw[0]) + " - " + str(dates_raw[-1]))
plt.ylabel('PIs')
plt.gcf().autofmt_xdate()
Basically there is mpl.dates.num2date and mpl.dates.date2num methods that you can use to convert time to number back and forth. I use pandas to convert the dates from a list of str. The are of course other ways to do it, but I think pd.to_datetime is the most concise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress Plugin: Show html only on standard page and not in admin area
I'm writing a plugin and I need to display a piece of text in the WP page, but not in the admin area. How can I do so?
I tried this in the construct:
add_action( 'init', array( $this, 'initPage' ) )
and then:
public function initPage() {
echo 'hello';
}
but the text is displayed also in the admin area. Is there a way to do this? It would be the opposite of the action admin_init I assume.
A:
I solved this by adding it to a shortcode action. Like this:
add_shortcode( 'myPlugin', array( $this, 'shortcode' ) );
and:
public function shortcode( $atts ) {
return 'hello';
}
With the above code, 'hello' will only display on the front-end. Not sure if that's the cleaner way to do it, but does the job.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery hover over quadrant
I am looking to create a JQuery page with a hover over effect. when it hovers over the top left quadrant of the page, a div must be filled with text, and different text for the other three quadrants over the page.
I am new to JQuery, but I do have a programming background of some sort so I do know how to navigate through the language. I am going to use the css properties to change the text in the div's as they will be different divs, displayed in the same spot (so I will alter their visibility/display) or should I rather go with JQuery's .hide() and .show() methods?
My main question, is how do I set up the page so that JQuery picks up when the mouse is in the top left quadrant, top right quadrant, bottom left quadrant or bottom right quadrant of the screen?
Thanks in advance, any advice would be greatly appreciated.
A:
You can bind on mousemove event and compare cursor position with window width and height. Something like this http://jsfiddle.net/tarabyte/DUJQ4
<div id="topleft" class="message">Top Left</div>
<div id="topright" class="message">Top Right</div>
<div id="bottomleft" class="message">Bottom Left</div>
<div id="bottomright" class="message">Bottom Right</div>
$(function(){
var current; //will save current quadrant here
$(document).mousemove(function(ev){
var left = ev.pageX, top = ev.pageY, //cursor coordinats
win = $(window),
width = win.width(), height = win.height(), horizontal, vertical, id;
horizontal = (left < width/2) ? "left": "right";
vertical = (top < height/2) ? "top": "bottom";
id = vertical + horizontal;
if(id == current) { //not changed
return;
}
current = id;
$(".message").hide(); //hide all messages
$("#" + id).show(); //show only one with corrent id.
});
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Enqueue CSS Function
I am creating my own WordPress theme and trying to enqueue my css in functions.php
When I navigate to wp-admin/Themes it says my template is missing, I can only assume its todo with my function but I cannot see where.
My PHP files live in the themes root folder and the css is in its own folder
Functions.php
<?php
function LoadResources () {
wp_enqueue_style( 'style', get_template_directory_uri() . '/css/style.css' );
}
add_action('wp_enqueue_style', 'LoadResources');
Header.php
<!doctype html>
<html>
<head>
<meta charset="<?php bloginfo('charset') ?>">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title><?php the_title() ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
Edit
A:
The correct hook is wp_enqueue_scripts, not wp_enqueue_style. Change the following line
add_action('wp_enqueue_style', 'LoadResources');
to
add_action('wp_enqueue_scripts', 'LoadResources');
Also, function names should be lowercase letters
EDIT
Please note, the main stylesheet of the theme has to go into the root folder. It cannot be in a subfolder. Wordpress will automatically load the main stylesheet from there
| {
"pile_set_name": "StackExchange"
} |
Q:
Remote images and sizes for hdpi/mdpi/ldpi etc
So on device there's the drawable directories for hdpi, mdpi, ldpi etc...
Now lets say I want to download images from the internet to view in the app (on the fly).
Can I have the three different densities of image available for download? Is there some way I can check if the current device is hdpi/mdpi/ldpi and download the right resolution accordingly? Or is it much more simple than that?
I guess if I download a high res image onto a hdpi phone then it will assume its a mdpi image that just has larger dimensions than intended?
Thanks
A:
This is how you get the density programatically
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
case DisplayMetrics.DENSITY_LOW:
break;
case DisplayMetrics.DENSITY_MEDIUM:
break;
case DisplayMetrics.DENSITY_HIGH:
break;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to replace characters using regular expressions?
How to replace characters '-' using regular expressions?
There some date or datetime fields in my json string and they all use character '/' as separator, such as '2016/10/10 10:10:10'.
now i need the date or datetime fields with this form '2016-10-10 10:10:10'.
For example:
{
"code": "200",
"error": "",
"total": "10",
"page": "1",
"result": [
{
"CustomerNo": "0432215",
"Name": "ACE-Dick/USA",
"LastUpdatedDate": "2015/08/07 13:25:32",
"LastUpdatedBy": "System"
}
]
}
The text below is correct json what i want.
{
"code": "200",
"error": "",
"total": "10",
"page": "1",
"result": [
{
"CustomerNo": "0432215",
"Name": "ACE-Dick/USA",
"LastUpdatedDate": "2015-08-07 13:25:32",
"LastUpdatedBy": "System"
}
]
}
I can find the date string using regular expresion as follow,but how can replace it?
\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}
A:
Use capturing groups around the values you need to keep, and just match what you need to replace:
(\d{4})/(\d{2})/(\d{2} \d{2}:\d{2}:\d{2})
^ -1- ^ ^ -2- ^ ^ --------- 3---------- ^
and replace with $1-$2-$3 where $1 is a backreference to the value captured with Group 1, $2 references Group 2 value, etc.
See the regex demo
Java demo:
String s = "2016/10/10 10:10:10";
String rx = "(\\d{4})/(\\d{2})/(\\d{2} \\d{2}:\\d{2}:\\d{2})";
System.out.println(s.replaceAll(rx, "$1-$2-$3"));
See more on capturing groups and backreferences here.
| {
"pile_set_name": "StackExchange"
} |
Q:
API call with for-loop in Angular
I have an API get call that I want to loop several times depending on the length of the mockInput.json file.
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
const localMockInput = 'assets/mock-input.json';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(environment.api.username+':'+environment.api.password)
})
};
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
fetchRealData(_pid: any, _extUserId: any){
return this.http.get('XXXXX/XXXXX?product='+_pid+'&externalUserId='+_extUserId, httpOptions);
}
collectMockRounds(){
return this.http.get(localMockInput)
}
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
realData: any = [];
mockInput: any = [];
constructor(private api: ApiService) {}
ngOnInit(){
this.doArray();
}
collectMockInput(){
this.api.collectMockRounds()
.subscribe(data => {
for (const e of (data as any)) {
this.mockInput.push({
pId: e.PID,
extUserId: e.extUserID,
});
}
// console.log('Mock Input Successfully Collected:');
// console.log(this.mockInput);
});
}
doArray(){
this.collectMockInput();
for(let i = 0; i < this.mockInput.length; i++){
console.log(this.mockInput.length)
this.api.fetchRealData(this.mockInput[i].pId, this.mockInput[i].extUserId)
.subscribe(data => {
for (const d of (data as any)) {
this.realData.push({
x: d.x,
y: d.y,
});
}
},
error => {
console.log(error.error.errorMessage);
});
}
}
}
So when I've fetched the mockdata and its length, I want to loop it with my API call. It seems like I'm doing something wrong here; I do not receive any errors or even the console.log within the loop: console.log(this.mockInput.length).
Any advice or hints would be highly appreciated.
Thanks in advance
A:
Try something like this:
import { combineLatest } from 'rxjs'
import { switchMap, tap } from 'rxjs/operators'
....
doArray() {
this.api.collectMockRounds().pipe(
// this is an array so it should work
tap(data => console.log(data)), // can you see what the log is here, make sure data is an array...
// switch to a new observable
switchMap(data => {
console.log(data); // make sure this is an array
return combineLatest(
// combine all of the requests
...data.map(input => this.api.fetchRealData(input.PID, input.extUserID)),
})),
).subscribe(data => {
for (const d of (data as any)) {
this.realData.push({
x: d.x,
y: d.y,
});
}
}, error => {
// handle error
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I shut off a USB fan automatically when the Mac goes to sleep?
I have a Mac Mini 1.1 on which I updated the EFI firmware to v2.1 and installed Mac OS X 10.7
I'm wondering how I can cool the Mac with an external fan somehow.
I found the internal cooling to be slow, so I put an external handmade USB fan on the system in an open case and this works well for my purpose.
The problem with the external fan is that when I put the computer to sleep, the fan keeps on working and I don't know how to make it stop.
I don't want to use the system fan as it looks very weak and makes a lot of noise at 3000 rpm. I don't like noise.
A:
To turn off the power to your "self made USB cooling fan" (nice one) you need to put the mac mini to hibernate mode not to sleep mode.
In Terminal (found in Applications -> Utilities) type
sudo pmset hibernatemode 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Generics : cant call a function with said generics even though type matches
I have this code where I have defined two classes using generics.
1. Section which can have a generic type of data.
2. Config which uses kind of builder patterns and stores list of such sections.
On running this code it gives compilation error and I am no where to understand why. I have mentioned the type.
Error : incompatible types: java.util.List> cannot be converted to java.util.List>
public class Main {
public static void main(String[] args) {
Section<String> section = new Section<>("wow");
List<Section<String>> sections = new ArrayList<>();
sections.add(section);
Config<String> config = new Config<>().setSections(sections);
}
public static class Section<T> {
private T data;
public Section(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
public static class Config<T> {
private List<Section<T>> sections;
public Config() {
}
public Config<T> setSections(List<Section<T>> sections) {
this.sections = sections;
return this;
}
}
}
A:
The problem is at line 7, you are creating new Config and call setSections on the same line.
So the solutions are two:
Explicit type:
Config<String> config = new Config<String>().setSections(sections);
Split operations:
Config<String> config = new Config<>();
conf.setSections(sections);
| {
"pile_set_name": "StackExchange"
} |
Q:
vba ADOBE.recordset filter/find
I have a ADOBE.Recordset in Excel VBA returned from a query to database. How should I find a certain record in this set that fits certain criteria? Below is the code. Could anyone fill in the " 'print out the name of one person whose age is i" part for me? Thanks in advance!
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US'"
Set rs = conn.Execute(q) 'conn is an ADOBE.Connection
For i = 30 To 40
'print out the name of one person whose age is i
Next i
Update 1:
Thanks KazJaw! I think your solutions should work. However, I am looking for a cleaner solution -
I don't want to save the query results into a sheet. I'd prefer them in memeory.
Is there a .Find or .Search function I can use so that I don't need to implement the search with a loop (as you did in the Second Solution)?
Maybe I am being greedy here, but ideally, I'd like something like this:
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US'"
Set rs = conn.Execute(q) 'conn is an ADOBE.Connection
For i = 30 To 40
name = rs.Find("age = i")!name 'this line is where I am not sure how to achieve
MsgBox name & "'s age is " & i
Next i
Apologies for the formatting. I am new to the site, not sure how to properly indent the two lines in the For loop.
Update 2:
Yes KazJaw, other problem rises. ".Find" requires rs to be able to scrolled back, which requires its lockType to be set to adLockOptimistic. Haven't figured out how yet. Will post if I do.
Solution:
The Key is to use rs.Open instead of conn.Execute and to set CursorType.
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US' Order By i"
Set rs = New ADODB.Recordset
rs.Open Source:=q, CursorType:=adOpenStatic, ActiveConnection:=ThisWorkbook.conn 'conn is an ADOBE.Connection
For i = 30 To 40
name = rs.Find("age = i")!name 'this line is where I am not sure how to achieve
MsgBox name & "'s age is " & i
Next i
A:
First solution, without looping, you could do it in this way but you need to stick to @mehow suggestion where age condition should be implemented in SQL query.
'return all results as of cell A2, direction down+right, in activesheet
ActiveSheet.Range("A2").CopyFromRecordset rs
Second solution, with looping, instead of your For i...Next loop try below solution.
Dim lRow as long
lRow=2
With rs
Do Until .EOF
'return only those which age equals to i
'if implemented in SQL query then you could get rid of if statement below
if .Fields(1).Value = i then
Cells(lRow, 1) = .Fields(1).Value
Cells(lRow, 2) = .Fields(2).Value
.MoveNext
lRow = lRow + 1
end if
Loop
End With
Third solution. If you really need to use .Find method then do it in this way:
'...your loop here
rs.Find "age = " & i
name = rs(0)
MsgBox name & "'s age is " & i
'... rest of your code here
Unfortunately, I'm not sure if it will work. I think you will need to sort your results by age within SQL code. If not I expect some of the ages can be omit. Some other problems could arise. Therefore try with other solutions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ignore the innerText of child elements
<a href="#">
<span class="myspan"> Don't want this text </span>
I want this text
</a>
How can I grab just the text above without the text inside the span?
Assume the span might appear or not
A:
That's not as pretty as you may have wished, but at least it doesn't involve cloning:
$('a').contents()
.get()
.map(function(n) { return n.nodeType === 3 ? n.textContent.trim() : ''; })
.join('')
See Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending Enum Values via TCP
As part of a 'protocol' I have an Enum, which is shared across the client and server, which dictates what to do with the rest of the data
Client:
byte[] outStream = Encoding.UTF8.GetBytes((int)Shared.CommandType.ClientJoin + "sometext");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
And at the server end:
string dataFromClient = null;
byte[] bytesFrom = new byte[1024];
NetworkStream networkStream = tcpclient.GetStream();
int bytesread = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
Byte[] commandBytes = new Byte[4];
Array.Copy(bytesFrom, commandBytes, 4);
dataFromClient = Encoding.UTF8.GetString(bytesFrom, 4, bytesread - 4);
//test values
int receivedcommand = BitConverter.ToInt32(commandBytes, 0);
int actualcommand = (int)Shared.CommandType.ClientJoin;
However, the received 'value' (1634222896 in tests) is wildly different to the actual value (0)
I'm sure I'm doing something wildly wrong, something to do with the byte array splitting, but i can't for the life of me see what
Any ideas?
(as always, if there is a better method of implementation than the one above, i am open to suggestions :) )
A:
byte[] outStream = Encoding.UTF8.GetBytes((int)Shared.CommandType.ClientJoin + "sometext");
becomes
byte[] outStream = Encoding.UTF8.GetBytes(0+ "sometext");
byte[] outStream = Encoding.UTF8.GetBytes("0sometext");
After receiving commandBytes will have bytes representation of {'0','s','o','m'}
and BitConverter.ToInt32(commandBytes, 0); will just make an integer representation of 4 byte array,all of whose members having a non zero value (Since all are ascii text).
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does GLUT_DEPTH destroy the rendering of my rotating teapot?
If I remove GLUT_DEPTH from glutInitDisplayMode() the teapot doesn't hide hidden surfaces but it does render. I want to hide hidden surfaces so I add GLUT_DEPTH and the teapot disappears. I don't know if something is out of order or if I'm missing something with the depth buffer?
void reshape( int x, int y )
{
if( y == 0 || x == 0 ) return;
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 39.0, (GLdouble)x / (GLdouble)y, 0.6, 40.0 );
glMatrixMode( GL_MODELVIEW );
glViewport( 0, 0, x, y ); //Use the whole window for rendering
}
GLfloat xRotated, yRotated, zRotated;
GLdouble size = 0.5;
void display( void )
{
glMatrixMode( GL_MODELVIEW );
// clear the drawing buffer.
glClear( GL_COLOR_BUFFER_BIT );
// clear the identity matrix.
glLoadIdentity();
// traslate the draw by z = -4.0
// Note this when you decrease z like -8.0 the drawing will looks far , or smaller.
glTranslatef( 0.0, 0.0, -4.5 );
// Red color used to draw.
glColor3f( 0.8, 0.5, 0.1 );
// changing in transformation matrix.
// rotation about X axis
glRotatef( xRotated, 1.0, 0.0, 0.0 );
// rotation about Y axis
glRotatef( yRotated, 0.0, 1.0, 0.0 );
// rotation about Z axis
glRotatef( zRotated, 0.0, 0.0, 1.0 );
// scaling transfomation
glScalef( 1.0, 1.0, 1.0 );
glPushMatrix();
// built-in (glut library) function , draw you a Teapot.
glutSolidTeapot( size );
// Flush buffers to screen
glPopMatrix();
glFlush();
// swap buffers called because we are using double buffering
glutSwapBuffers();
}
void reshapeFunc( int x, int y )
{
if( y == 0 || x == 0 ) return; //Nothing is visible then, so return
//Set a new projection matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
//Angle of view:40 degrees
//Near clipping plane distance: 0.5
//Far clipping plane distance: 20.0
gluPerspective( 40.0, (GLdouble)x / (GLdouble)y, 0.5, 20.0 );
glViewport( 0, 0, x, y ); //Use the whole window for rendering
}
void idleFunc( void )
{
yRotated += 0.3;
display();
}
int main( int argc, char **argv )
{
//Initialize GLUT
glutInit( &argc, argv );
//double buffering used to avoid flickering problem in animation
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
// window size
glutInitWindowSize( 400, 350 );
// create the window
glutCreateWindow( "Teapot Rotating Animation" );
glEnable( GL_LIGHTING ); // enable the light source
glEnable( GL_LIGHT0 );
glShadeModel( GL_SMOOTH );
glEnable( GL_DEPTH_TEST ); // for hidden surface removal
glEnable( GL_NORMALIZE ); // normalize vectors for proper shading
//set properties of the surface material
GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f }; // color
GLfloat mat_diffuse[] = { 0.6f, 0.6f, 0.6f, 1.0f };
GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat mat_shininess[] = { 50.0f };
glMaterialfv( GL_FRONT, GL_AMBIENT, mat_ambient );
glMaterialfv( GL_FRONT, GL_DIFFUSE, mat_diffuse );
glMaterialfv( GL_FRONT, GL_SPECULAR, mat_specular );
glMaterialfv( GL_FRONT, GL_SHININESS, mat_shininess );
// set the light source properties
GLfloat lightIntensity[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat light_position[] = { 2.0f, 6.0f, 3.0f, 0.0f };
glLightfv( GL_LIGHT0, GL_POSITION, light_position );
glLightfv( GL_LIGHT0, GL_DIFFUSE, lightIntensity );
xRotated = yRotated = zRotated = 0;
yRotated = 40;
glClearColor( 0.1f, 0.1f, 0.1f, 0.0f ); // background is light gray
//Assign the function used in events
glutIdleFunc( idleFunc );
glutDisplayFunc( display );
glutReshapeFunc( reshapeFunc );
//Let start glut loop
glutMainLoop();
return 0;
}
A:
If a depth test should be used, three things have to be done:
The window needs a depth buffer. In glut this is done by adding GLUT_DEPTH to glutInitDisplayMode()
Depth testing has to be enabled by calling glEnable(GL_DEPTH_TEST);
The depth buffer has to be cleared (in every frame) by calling glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
You are doing 1 and 2 but not 3. Since you're not clearing the buffer, depth values might lie behind the currently stored depth values and the teapot disappears.
| {
"pile_set_name": "StackExchange"
} |
Q:
In a Quantum Turing Machine, how is the decision to move along the memory tape made?
Let, for a Quantum Turing machine (QTM), the state set be $Q$, and the alphabet of symbols be $\sum=\{0,1\}$, which appear at the tape head. Then, as per my understanding, at any given time while the QTM is calculating, the qubit that appears at its head will hold an arbitrary vector $V_\sum = a|1\rangle+b|0\rangle$. Also, if $|q_0\rangle , |q_1\rangle, ... \in Q$, then the state vector at that instance will also be an arbitrary vector $V_q=b_0|q_0\rangle + b_1 |q_1\rangle+ ...$.
Now, after the instruction cycle is complete, the vectors $V_\sum$ and $V_q$ will decide whether the QTM will move left or right along the Qubit tape. My question is- since Hilbert space formed by $Q \otimes \sum$ is an uncountable infinite set and $\{\text{Left,Right}\}$ is a discrete set, the mapping between them will be difficult to create.
So how is the decision to move left or right made? Does the QTM move both left and right at the same time, meaning that the set $\{\text{Left,Right}\}$ also forms a different Hilbert space, and hence the motion of the QTM becomes something like $a|\text{Left}\rangle+b|\text{Right}\rangle$.
Or, just like a Classical Turing machine, the QTM moves either left or right, but not both at the same time?
A:
If we have a QTM with state set $Q$ and a tape alphabet $\Sigma = \{0,1\}$, we cannot say that the qubit being scanned by the tape head "holds" a vector $a|0\rangle + b|1\rangle$ or that the (internal) state is a vector with basis states corresponding to $Q$. The qubits on the tape can be correlated with one another and with the internal state, as well as with the tape head position.
As an analogy, we would not describe a probabilistic Turing machine's global state by independently specifying a distribution for the internal state and for each of the tape squares. Rather, we have to describe everything together so as to properly represent correlations among the different parts of the machine. For example, the bits stored in two distant tape squares might be perfectly correlated, both 0 with probability 1/2 and both 1 with probability 1/2.
So, in the quantum case, and assuming we're talking about pure states of quantum Turing machines with unitary evolutions (as opposed to a more general model based on mixed states), the global state is represented by a vector whose entries are indexed by configurations (i.e., classical descriptions of the internal state, the location of the tape head, and the contents of every tape square) of the Turing machine. It should be noted that we generally assume that there is a special blank symbol in the tape alphabet (which could be 0 if we want our tape squares to store qubits) and that we start computations with at most finitely many squares being non-blank, so that the set of all reachable configurations is countable. This means that the state will be represented by a unit vector in a separable Hilbert space.
Finally, and perhaps this is the actual answer to the question interpreted literally, the movement of the tape head is determined by the transition function, which will assign an "amplitude" to each possible action (new state, new symbol, and tape head movement) for every classical pair $(q,\sigma)$ representing the current state and currently scanned symbol. Nothing forces the tape head to move deterministically -- a nonzero amplitude could be assigned to two or more actions that include tape head movements to both the left and right -- so it is possible for a QTM tape head to move both left and right in superposition.
For example, you can imagine a QTM with $Q = \{0,1\}$ and $\Sigma = \{0,1\}$ (and we'll take 0 to be the blank symbol). We start in state 0 scanning a square that stores 1, and all other squares store 0. I won't explicitly write down the transition function, but will just describe the behavior in words. On each move, the contents of the scanned tape square is interpreted as a control bit for a Hadamard operation on the internal state. After the controlled-Hadamard is performed, the head moves left if the (new) state is 0 and moves right if the (new) state is 1. (In this example we never actually change the contents of the tape.) After one step, the QTM will be in an equally weighted superposition between being in state 0 with the tape head scanning square -1, and being in state 1 with the tape head scanning square +1. On all subsequent moves the controlled-Hadamard does nothing because every square aside from square 0 contains the 0 symbol. The tape head will therefore continue to move simultaneously both left and right, like a particle travelling to the left and to the right in superposition.
If you wanted to, you could of course define a variant of the quantum Turing machine model for which the tape head location and movement is deterministic, and this would not ruin the computational universality of the model, but the "classic" definition of quantum Turing machines does not impose this restriction.
A:
The quantum Turing machine can move into a superposition of moving left and right. This is different from the classical Turing machine which can only move either left or right.
| {
"pile_set_name": "StackExchange"
} |
Q:
Has anyone tried moving a php Azure App Service to IIS?
I'm not really an expert with php. But I've got an Azure app service which is built using Laravel php and Sql database. All these currently sittig on Azure...
I need to move this Azure app service to IIS. Has any one out there done this before???
A:
Generally speaking, you can leverage Git or FTP to download your whole Laravel application to local, then you move your application to your IIS server.
Log in to the Azure Portal.
In your App Service app's blade, click Settings > Deployment source. Click Choose source, then click Local Git Repository, and then click OK.
If this is your first time setting up a repository in Azure, you need to create login credentials for it. You will use them to log into the Azure repository and push changes from your local Git repository. From your app's blade, click Settings > Deployment credentials, then configure your deployment username and password. When you're done, click Save.
Then you can find the Git, FTP url in the Overview Essentials
tab
Any further concern, please feel free to let me know.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did the Justice League poster intentionally use the same style as a graphic novel collection?
Eaglemoss have released The DC Comics Graphic Novel Collection where the combined spines of the hardback comics show the following image:
I noticed that the new Justice League poster shows our heroes in remarkably similar poses (minus Cyborg but he does stand quite similar to Green Lantern above):
It looks like the Justice League poster is almost mirroring that of the comics.
Was this intentional?
A:
The poster is an homage to Alex Ross, who has done the artwork for many DC comics, and that one on the comic cover was done by him. This article shows that there are many comparisons, and confirms that the photographer did base the poster off of his work.
According to Clay Enos, the photographer for the movie poster:
“I first saw this painting as part of the Ayman Hariri’s Impossible Collection and it inspired me to shoot our gang in the same style,” Enos said, referring to Ross’s painting of the Justice League for the 2005 Justice comic book series seen below and to the DC Comics collection of a billionaire. “I used this exact image as my reference for what became the latest JL poster. I simply had the idea and took the initiative to pay homage to Alex Ross by making a few quick portraits in that distinctive light.”
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get records from field having contain field ids like (1,2,3) in a field in mysql?
I have 2 tables students and ex_students
(1) Table name: students
+----+--------+
| id | name |
+----+--------+
| 1 | Alex |
| 2 | Bill |
| 3 | Cath |
| 4 | Dale |
| 5 | Evan |
+----+--------+
Other table of ex_students
(2) Table name: ex_students
+----+--------+-------+
| id | parent | s_ids |
+----+--------+-------+
| 1 | Abcs | 1,2,3 |
| 2 | Bcde | NULL |
| 3 | Cdef | NULL |
| 4 | Defg | NULL |
| 5 | Efgh | NULL |
+----+--------+-------+
Finally i want result like
+----+--------+-------+
| id | name | status|
+----+--------+-------+
| 1 | Alex | 1 |
| 2 | Bill | 1 |
| 3 | Cath | 1 |
| 4 | Dale | NULL |
| 5 | Evan | NULL |
+----+--------+-------+
How to fetch records using mysql queries?
I try below query but isn't work..
SELECT students.id, students.name, IF(COALESCE(ex_students.id,1) = 1,'1','2') as status FROM students LEFT JOIN ex_students on FIND_IN_SET(ex_students.s_ids,students.id) > 0 Group By students.id
A:
Change
FIND_IN_SET(ex_students.s_ids, students.id)
to
FIND_IN_SET(students.id, ex_students.s_ids)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write two-way binding in dart angular
I need a component to choose user role with two-way binding
role-chooser-comp.html
<div class="roleChooser">
<role-item #owner (select)="role(owner.role)" [role]="'owner'" [title]="'Owner'"></role-item>
<role-item #writer (select)="role(writer.role)" [role]="'writer'" [title]="'Writer'"></role-item>
<role-item #viewer (select)="role(viewer.role)" [role]="'viewer'" [title]="'Reader'"></role-item>
</div>
its class is the following:
role-chooser-comp.dart
@Component(
selector: 'role-chooser-comp',
templateUrl: 'role_chooser_comp.html',
styleUrls: const ['role_chooser_comp.css'],
directives: const [RoleItem])
class RoleChooser implements OnInit {
final PlaceService _placeService;
final Router _router;
final Environment _environment;
@ViewChild('owner') RoleItem owner;
@ViewChild('writer') RoleItem writer;
@ViewChild('viewer') RoleItem viewer;
List<RoleItem> choices;
String lastSelected;
RoleChooser(this._placeService, this._router, this._environment) {
}
Future<Null> ngOnInit() async {
choices = [owner, writer, viewer];
if (lastSelected != null)
role(lastSelected);
}
String get selected => lastSelected;
@Input()
set selected(String role) {
//on init, the choices are still not set
if (choices == null)
lastSelected = role;
else
this.role(role);
}
void role(String role) {
if (choices == null) {
window.alert("No roles are set");
return;
}
for (RoleItem item in choices) {
if (item.role == role) {
item.selected = true;
lastSelected = role;
} else {
item.selected = false;
}
}
}
}
Now what I need is to be able to update the value of my model automatically in a use like :
usecase
<role-chooser-comp [(selected)]="userRole.roleName"></role-chooser-comp>
or
<role-chooser-comp [(ngModel)]="userRole.roleName"></role-chooser-comp>
I found an article about angular.js that show how to use [(ngModel)] with any element (implementing two methods so angular knows how to get the value from the component and backward) : https://docs.angularjs.org/guide/forms (section Implementing custom form controls (using ngModel))
I'd like to do the same in dart, but I don't know how...
The role item is very simple for now, I just paste it for reference :
role-item.html
<div class="role" [class.selected]="selected" (click)="clicked()">
<btn #icon
[sources]="images"></btn>
</div>
role-item.dart
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'package:share_place/environment.dart';
import 'package:share_place/place_service.dart';
import 'package:share_place/common/ui/button_comp.dart';
@Component(
selector: 'role-item',
templateUrl: 'role_item.html',
styleUrls: const ['role_item.css'],
directives: const [ButtonComp])
class RoleItem {
final PlaceService _placeService;
final Router _router;
final Environment _environment;
@Output() final EventEmitter<String> pressAction = new EventEmitter<String>();
@Output() final EventEmitter<String> select = new EventEmitter<String>();
get role => itemRole;
@Input() set role(String role) {
itemRole = role;
images = [
'../images/roles/$role.png',
'../images/roles/$role-h.png',
'../images/roles/$role-c.png'
];
}
@Input() String title;
@Input() String desc;
@ViewChild('icon')
ButtonComp icon;
String itemRole;
List<String> images;
bool isSelected = false;
bool toggle = false;
RoleItem(this._placeService, this._router, this._environment);
void clicked() {
bool newlySelected;
if (!isSelected)
newlySelected = true;
if (toggle)
selected = !selected;
else
selected = true;
pressAction.emit(role);
if (newlySelected)
select.emit(role);
}
bool get selected => isSelected;
void set selected(bool isSelected) {
this.isSelected = isSelected;
icon.select(isSelected);
}
}
A:
You need to add
@Output() EventEmitter<String> selectedChange = new EventEmitter<String>();
to your RoleChooser component.
To notify about changes call
selectedChange.add('foo');
then userRole.roleName from
<role-chooser-comp [(selected)]="userRole.roleName"></role-chooser-comp>
will be updated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Having difficulty in understanding wordpress Plugin data
I am beginner at wordpress world. I am having difficulty to retrieve the intended value from following data.
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => MCQ Botany 101
[settings] => a:24:{s:9:"limit_one";s:2:"no";s:12:"limit_one_wp";s:2:"no";s:16:"limit_one_cookie";s:2:"no";s:11:"save_resume";s:2:"no";s:16:"question_numbers";s:3:"yes";s:5:"timer";s:4:"5000";s:9:"pass_mark";s:2:"80";s:17:"show_progress_bar";s:3:"yes";s:20:"automark_whenfreetxt";s:2:"no";s:14:"finish_display";s:11:"Quiz Review";s:6:"status";s:7:"enabled";s:9:"send_user";s:2:"no";s:7:"contact";s:2:"no";s:6:"use_wp";s:2:"no";s:16:"notificaton_type";s:7:"instant";s:14:"email_template";s:0:"";s:12:"pdf_template";s:0:"";s:7:"use_pdf";s:2:"no";s:13:"store_results";s:3:"yes";s:18:"notification_email";s:0:"";s:14:"finish_message";s:0:"";s:11:"pass_finish";s:2:"no";s:19:"pass_finish_message";s:0:"";s:11:"fail_review";s:3:"yes";}
[type] => quiz
[timestamp] => 2016-07-10 21:02:44
)
)
I want 5000 from s:4:"5000". Any help will be highly appreciated.
A:
You have an array, which has an object as a first key. You want to get a 'settings' value from this object, but it's a serialized string. So you need to unserialize it first.
Assuming that $myArr is the given array you'll do something like this:
$settingsArr = unserialize($myArr[0]->settings);
$settingsArr['timer'];
Because the timer key holds the 5000 value.
You can recreate this in php sandbox:
<?php
$myObj = new stdClass;
$myObj->id = 1;
$myObj->name = 'MCQ Botany 101';
$myObj->settings = 'a:24:{s:9:"limit_one";s:2:"no";s:12:"limit_one_wp";s:2:"no";s:16:"limit_one_cookie";s:2:"no";s:11:"save_resume";s:2:"no";s:16:"question_numbers";s:3:"yes";s:5:"timer";s:4:"5000";s:9:"pass_mark";s:2:"80";s:17:"show_progress_bar";s:3:"yes";s:20:"automark_whenfreetxt";s:2:"no";s:14:"finish_display";s:11:"Quiz Review";s:6:"status";s:7:"enabled";s:9:"send_user";s:2:"no";s:7:"contact";s:2:"no";s:6:"use_wp";s:2:"no";s:16:"notificaton_type";s:7:"instant";s:14:"email_template";s:0:"";s:12:"pdf_template";s:0:"";s:7:"use_pdf";s:2:"no";s:13:"store_results";s:3:"yes";s:18:"notification_email";s:0:"";s:14:"finish_message";s:0:"";s:11:"pass_finish";s:2:"no";s:19:"pass_finish_message";s:0:"";s:11:"fail_review";s:3:"yes";}';
$myObj->type = 'quiz';
$myObj->timestamp = '2016-07-10 21:02:44';
$myArr = array(
'0' => $myObj
);
$settingsArr = unserialize($myArr[0]->settings);
print_r($settingsArr['timer']);
You can also see the contents of the settings array
print_r($settingsArr);
Array
(
[limit_one] => no
[limit_one_wp] => no
[limit_one_cookie] => no
[save_resume] => no
[question_numbers] => yes
[timer] => 5000
[pass_mark] => 80
[show_progress_bar] => yes
[automark_whenfreetxt] => no
[finish_display] => Quiz Review
[status] => enabled
[send_user] => no
[contact] => no
[use_wp] => no
[notificaton_type] => instant
[email_template] =>
[pdf_template] =>
[use_pdf] => no
[store_results] => yes
[notification_email] =>
[finish_message] =>
[pass_finish] => no
[pass_finish_message] =>
[fail_review] => yes
)
| {
"pile_set_name": "StackExchange"
} |
Q:
FullCalendar 4 - add and then access additional values to the Event Object
How do I add and then access additional values My_Custom_Value to the Event Object?
events: [
{
title: 'My Title',
My_Custom_Value: 'some details',
allDay: false,
start: 1501056000000,
end: 1501057800000
}
],
A:
Access your value through "extendedProps":
A plain object holding miscellaneous other properties specified during parsing. Receives properties in the explicitly given extendedProps hash as well as other non-standard properties."
https://fullcalendar.io/docs/event-object
eventRender: function(info){
console.log("_______ info _______\n");
console.log(info.event.extendedProps.My_Custom_Value);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ExpectedConditions is throwing error in Protractor
I want to implement ExpectedConditions in my framework but it is throwing some error which i'm not able to understand. can someone help me in this.
Step Definition
this.Then(/^Select Any Opty and click on New button$/, async () => {
cmBrowser.sleep(10000);
await cmBrowser.wait(EC.visibilityOf(await loginPO.optyList()),20000);
var list=await loginPO.optyList();
});
page object
this.optyList = function () {
// return $$("table[role='grid'] th span a");
return element.all(by.xpath("//a/ancestor::th[@scope='row']"));
}
Error Log
TypeError: Cannot read property 'bind' of undefined
at ProtractorExpectedConditions.presenceOf (C:\Users\srongala\AppData\Roaming\npm\node_modules\protractor\built\expectedConditions.js:341:40)
at ProtractorExpectedConditions.visibilityOf (C:\Users\srongala\AppData\Roaming\npm\node_modules\protractor\built\expectedConditions.js:381:30)
at World.(anonymous) (C:\Users\srongala\Documents\My Received Files\Automation\Proc\Test_modules\step_definitions\PGS_ES.js:47:39)
at runMicrotasks ((anonymous))
at processTicksAndRejections (internal/process/task_queues.js:93:5)
The application i'm using is non angular applicatio.. i reviewed solutions provided in the others questions and they said like need to use browser.ignoreSynchronization=true but i tried both browser.waitForAngularEnabled(); and browser.ignoreSynchronization=true, both are not working.
A:
Have you tried changing the locator definition from function to a variable?
Also you don't have to use await twice in the expected conditions line.
Try the following:
Page Object
// You should specify the index if using .all (with .get(index); at the end)
this.optyList = element.all(by.xpath("//a/ancestor::th[@scope='row']"));
Spec (Here you could try with visibilityOf or presenceOf)
this.Then(/^Select Any Opty and click on New button$/,async ()=>{
await cmBrowser.wait(EC.presenceOf(loginPO.optyList),20000);
// or:
await cmBrowser.wait(EC.visibilityOf(loginPO.optyList),20000);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict users in django
I have a panel to manage posts by admin or the users that are admin.
How can I restrict panel and display it only for admins not other users that register in system.
View:
class IndexView(LoginRequiredMixin, ListView):
model = Post
template_name = 'panel/index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context["posts"] = Post.objects.all()
context["counter"] = self.post_counter(context["posts"])
return context
def post_counter(self, posts):
postNumber = 0
for post in posts:
postNumber +=1
return postNumber
A:
Since you are having CBV you can use the PermissionMixin and then specific the permission. Something like this :
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = ("is_staff", "is_superuser", )
....
Reference : https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.mixins.PermissionRequiredMixin
If you would be having function based view then you can use @staff_member_required
Something like this :
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def my_view(request):
...
Reference and further read : https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.views.decorators.staff_member_required
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving hashmap values in java
I wrote below code to retrieve values in hashmap. But it didnt work.
HashMap<String, String> facilities = new HashMap<String, String>();
Iterator i = facilities.entrySet().iterator();
while(i.hasNext())
{
String key = i.next().toString();
String value = i.next().toString();
System.out.println(key + " " + value);
}
I modified the code to include SET class and it worked fine.
Set s= facilities.entrySet();
Iterator it = facilities.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
Can anyone guide me what went wrong in above code without SET class??
P.S - I do not have much programming exp and started using java recently
A:
You are calling next() two times.
Try this instead:
while(i.hasNext())
{
Entry e = i.next();
String key = e.getKey();
String value = e.getValue();
System.out.println(key + " " + value);
}
In short you could also use the following code (which also keeps the type information). Using Iterator is pre-Java-1.5 style somehow.
for(Entry<String, String> entry : facilities.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " " + value);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparing stored procedure performance ex and new version
I did create two new indexes on the tables that are used on a the sp.
The new results shows that on the part of problematic joins, the scans are converted to seek. I think seek is better rather than scan operations. On the other hand, the time takes more or less the same duration as it was without new indexes.
So clearly, how can i get satisfied before putting my new version sp to production.
For instance, changing parameters of sp can help me to see if the new version faster than old version or what else?
Regards
bk
A:
A few things to do:
1) ensure you are comparing performance fairly by clearing the data and execution plan cache after each test run. You can clear these down using (recommend only doing this on your dev/test environment):
CHECKPOINT -- force dirty pages in the buffer to be written to disk
DBCC DROPCLEANBUFFERS -- clear the data cache
DBCC FREEPROCCACHE -- clear the execution plan cache
2) Run SQL Profiler to record the Reads/Writes/CPU/Duration for each situation (with/without the indexes). This will give you a range of metrics to compare on (i.e. as opposed to just the time shown in SSMS).
Edit:
To run an SQL Profiler trace, in Management Studio go to Tools -> SQL Server Profiler. WHen prompted, specify the db server to run the trace against. A "Trace Properties" dialog will appear - you should just be able to click "Run" to start running a default trace. Then just execute your stored procedure and see it appear in SQL Profiler - it will show the Duration, number of reads etc alongside it.
3) Test with much larger volumes of data than you already have. If you test with small amounts of data, then the difference is often difficult to see on duration alone.
I recently blogged here about how to fairly test the performance of different variants of a query, which goes into a bit more detail about how I do it.
| {
"pile_set_name": "StackExchange"
} |
Q:
display only one logging line, removing the previous ones
I have a program using the logging module and the print statement. The logging is to inform the user what the program is doing, for example
logging.info("downloading HTML")
time.sleep(1)
logging.info("parsing HTML")
time.sleep(1)
print "the result"
at the end the output on the screen (mixing stdout and stderr) will be:
INFO:downloading HTML
INFO:parsing HTML
the result
I want to hide the last logging output when the next logging output is displayed or when the print is called. For example, start the program, you will see:
INFO:download HTML
wait one seconds, the next info "parsing HTML" will replace the previous "downloading HTML", so on the screen you will see only:
INFO:parsing HTML
and nothing else before, then wait one second, I want to see on the screen only:
"the result"
I want this feauture only when logging on the stderr, and not when logging to a file for example, there I want to see all the logging outputs.
Is it possible?
A:
On unix-like terminals, you can try prepending ANSI escape sequences to the text;
import time
import sys
print 'this is a text',
sys.stdout.flush()
time.sleep(1)
print '\x1b[80D'+'\x1b[K'+'Second text',
sys.stdout.flush()
The character '\x1b' is the escape character. The first sequence moves the cursor up to 80 positions to the left. The second clears the line.
You need the comma at the end of the print statement to prevent it from going to the second line. Then you need to flush the stdout stream otherwise the text won't appear.
Edit: For combinging this with logging, wrap it in a simple function:
def mylog(text):
logging.info(text)
print '\x1b[80D' + '\x1b[K'+ text,
sys.stdout.flush()
EDIT 2: Integrating this into the standard logging;
import logging
# create console handler
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter('\x1b[80D\x1b[1A\x1b[K%(message)s')
# add formatter to console handler
ch.setFormatter(formatter)
# add console handler to logger
logger.addHandler(ch)
Since the logging module seems to add newlines by itself, I've added an ANSI sequense (\x1b[1A) to go up one line.
Also see the logging howto for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql ClusterJ Plug-in
Mysql cluster comes with jars for clusterj. I downloaded Mysql Cluster 7.2.7. In shared/java folder,clusterj-7.2.7.jar,clusterj-api-7.2.7.jar,etc. exist. But when I add them to my project class path and write my first Java application that uses clusterj, some classes like SessionFactory,Session,ClusterJHelper is not included in the available jars. In another words, in none of the my jars includes these classes and then I cannot import. Why ?
A:
You are really need to download the latest MySQL Cluster 7.2. SessionFactory, Session, and ClusterJHelper included in
clusterj-7.2.10.jar
clusterj-api-7.2.10.jar
clusterjpa-7.2.10.jar
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert 3M rates to 6M rates using Basis Swaps (3M vs 6M)
How can I convert a 6M Libor rate e.g. 1Y Tenor to a 3M Libor rate using a basis swap 3M vs. 6M? I wanted to know the math and also an example would be great.
Update:
Example:
6M Swap 1Y Tenor: 1.925
3M Swap 1Y Tenor: 1.77109
3v6M Basis Swap 1Y Tenor = 15.625
When calculating now the 3N Swap 1Y Tenor based on the 6M Swap and the Basis Swap I receive the following value:
Calc 3M Swap 1Y Tenor: 1.76875
which is a relative differdnce og 0.13%.
The day count conventions are the same so I am not sure why I receive this kind of difference.
A:
Let's say 1yr semiannual rate versus 6m Libor is 2.00% and 1yr basis swap is 6m libor = 3m libor + 15bp. Then , to a first approximation 1yr rate versus 3m libor is 2.00-0.15= 1.85%.
More precisely , we have to take into account daycount conventions. So, we know that a swap consisting of 2.00% semiannual 30/360 daycount versus 3m libor +15 bp quarterly Act/360 is a fair swap, since both sides are equivalent to 6m libor. So the fixed rate equivalent of 3m libor is actually 2.00% minus the semiannual equivalent of 15bp quarterly Act/360. This conversion is not exactly solvable without having the discount factors for all the cash flows, but an approximation would be to first convert the 15bp to 30/360 daycount by calculating 15*365/360. Then you need to find the semiannual stream equivalent to the above quarterly stream. You might end up with 15.5bp instead of 15bp, so the answer would be 1.845%.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change versionCode with cordova?
I upload my application in Google Play with the default versionCode and versionName, but i have a new code and i need to change this versionCode and versionName.
I searched for some solutions for this problem but any solution works for me
config.xml
android-versionCode="2" android-versionName="2.0"
AndroidManifest.xml
android:versionCode="2" android:versionName="2.0"
build.gradle
defaultConfig {
android:versionCode 2
android:versionName "2.0"
}
After configure this files i use the command
aapt dump badging myappPath.apk
It always returns versionCode="1" and versionName="1.0"
Please, help me.
A:
edit your config.xml, add "android-versionCode" and specify your versionCode manually:
widget id="com.xxxxx.yyyyyyyyyyy" android-versionCode="201018"
version="2.1.1"
A:
You may specify it in your config.xml file :
<widget id="io.cordova.hellocordova"
version="0.0.1"
android-versionCode="7"
ios-CFBundleVersion="3.3.3">
A:
Cordova / PhoneGap / Ionic all accept arguments to the build command
# ionic
ionic build --release android -- --versionCode=3
# phonegap
phonegap build --release android -- --versionCode=3
# plain cordova
cordova build --release android -- --versionCode=3
You can see this command line arg being referenced in the source in cordova/lib/build.js:
if (options.argv.versionCode)
ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode);
(Me: using Cordova version 6.1.1, ionic version 1.7.16)
| {
"pile_set_name": "StackExchange"
} |
Q:
Under what circumstances would StyleCop choose to skip a file?
I have a solution that contains twenty c# projects. Until recently, StyleCop would run against all files, except auto-generated files, across all projects and report any issues that it found. Recently (it's not clear exactly when) it has become picky about which files it will report issues against.
Within a given project, I deliberately add the same defect to multiple source files and StyleCop will report the issue in some cases but not others.
An earlier branch of the same code, largely unaltered since October, does not display this behavior. Changing nothing but the source code I can demonstrate the problem existing in the latest code, but not in the code from October.
The skipped files do not contain any of the "I am auto-generated" markers that I would expect to cause StyleCop to skip them and I can find no commonality between either the skipped files or the analyzed files.
The solution file is unaltered between branches and the only changes to the csproj files are the addition/removal of source files.
Does anyone have any ideas what might be causing this behavior?
A:
So, after significant chocolate consumption and much swearing, I have the answer:
We recently inserted a copyright notice at the top of all our source files. It turns out that some of our source files had a byte order mark (U+FEFF) at the start of the file and the notice ended up being inserted ahead of this character.
StyleCop takes offense to the presence of this character and silently ignores the rest of the file.
Given that the character is, correctly, not rendered by the Visual Studio IDE, it took me three days to spot it :(
EDIT (2013.01.14) : I've created a Perl script to remove BOMs from our source files:
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;
my @dir = "C:/TopLevelSourceCodeDirectory";
find(\&edits, @dir);
sub edits() {
my $file = $_;
if( (-f $file)
&&
(
($file =~ /.*\.cs$/)
||
($file =~ /.*\.xaml$/)
||
($file =~ /.*\.whatever$/)
)
) {
#Open the file and read in the data
open (my $in, '<', $file) or die "Can't open $file: $!\n";
my @lines = <$in>;
close $in;
#Open same file for writing
open (my $out, '>', $file) or die "Can't open $file: $!\n";
#Walk through lines, putting into $_, and remove BOMs
for ( @lines ) {
s/\xef\xbb\xbf//g;
print $out $_;
}
close $out;
}
}
One final note; I had all manor of issues writing this script because notepad seemed to add BOMs in the middle of my file (which are, of course, invisible) when I pasted certain character strings in (even though those strings didn't originally contain a BOM). Working out why your regex doesn't match when you can't tell that it has an invisible BOM in the middle of the matcher string is not pleasant.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access the nth element of every list inside another list?
This must be a very basic question, so please bear with me. I have a list of lists like this
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
I want to access the second value in each list within the outer list as another list
[2, 5, 8, 11]
Is there a one-step way of doing this? Having programmed in Matlab quite a lot before, I tried l[:][1] but that returns me [4, 5, 6]
A:
Use a list comprehension:
>>> lis = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> [ x[1] for x in lis]
[2, 5, 8, 11]
Another way using operator.itemgetter:
>>> from operator import itemgetter
>>> map( itemgetter(1), lis)
[2, 5, 8, 11]
| {
"pile_set_name": "StackExchange"
} |
Q:
Select specific child elements with BeautifulSoup
I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements.
Given the html:
<div id="top">
<div>Content</div>
<div>
<div>Content I Want</div>
</div>
</div>
I want a easy way to to get the "Content I Want" given I have the object top. Coming to BeautifulSoup I thought it would be easy, and something like topobj.nodes[1].nodes[0].string. Instead I only see variables and functions that also return the elements together with text nodes, comments and so on.
Am I missing something? Or do I really need to resort to a long form using .find() or even worse using list comphrensions on the .contents variable.
The reason is that I don't trust the whitespace of the webpage to be the same so I want to ignore it and only traverse on elements.
A:
You are more flexible with find, and to get what you want you just need to run:
node = p.find('div', text="Content I Want")
But since it might not be how you want to get there, following options might suit you better:
xml = """<div id="top"><div>Content</div><div><div>Content I Want</div></div></div>"""
from BeautifulSoup import BeautifulSoup
p = BeautifulSoup(xml)
# returns a list of texts
print p.div.div.findNextSibling().div.contents
# returns a list of texts
print p.div.div.findNextSibling().div(text=True)
# join (and strip) the values
print ''.join(s.strip() for s in p.div.div.findNextSibling().div(text=True))
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get an anchor button to fit inside a listed order tag?
I have an anchor button that links to a contact page on a website. It is inside a listed item tag and it is stretching the header top and the listed item tag. The anchor button currently looks like this:
<li><div id="contact_us">
<a href="/contact" class="red-bg" role="button">FREE Boiler Evaluation</a>
</div></li>
The CSS for the anchor button currently looks like this:
a.red-bg{
display: inline-block;
overflow:hidden;
padding: 0 10px;
}
But the CSS for the header looks like this:
.header-top {
background: #252525;
}
.header-top a {
line-height: 40px;
}
.header-top .header-search a.red-bg {
padding: 0 10px;
display: block;
}
.header-top .container {
position: relative;
}
.header-top ul li {
list-style: none;
}
.header-top ul {
margin: 0;
}
.header-top ul li, .header-search {
float: left;
margin-left: 25px;
}
.header-top ul li a {
color: #f5f5f5;
display: inline-block;
}
.header-top .red-bg {
padding: 0 10px;
}
#header_wrapper ul.social-icons {
float: right;
}
#header_wrapper ul.social-icons li {
float: left;
list-style: none;
margin: 5px;
}
#header_wrapper ul.social-icons li a {
background: url(img/social-icons.png) no-repeat;
width: 27px;
height: 30px;
display: block;
text-decoration: none;
}
#header_wrapper ul.social-icons li.facebook a {
background-position: 0 -40px;
}
#header_wrapper ul.social-icons li.twitter a {
background-position: -27px -40px;
}
#header_wrapper ul.social-icons li.linkedin a {
background-position: -55px -40px;
}
#header_wrapper ul.social-icons li.blog a {
background-position: -84px -40px;
}
#header_wrapper .pull-right ul {
padding: 0 10px;
}
#header_wrapper ul.social-icons {
display: none;
}
How do I get it to fit inside the listed item tag so that it doesn't keep stretching the header or the listed item tag?
A:
You have a div inside the li so I made that a span, but your code doesn't include styling for that id so I'm pretty sure this will fix it. It's not semantically correct to have a block element inside an inline element.
See fix:
.header-top {
background: #252525;
}
.header-top a {
line-height: 40px;
}
.header-top .header-search a.red-bg {
padding: 0 10px;
display: block;
}
.header-top .container {
position: relative;
}
.header-top ul li {
list-style: none;
}
.header-top ul {
margin: 0;
}
.header-top ul li, .header-search {
float: left;
margin-left: 25px;
}
.header-top ul li a {
color: #f5f5f5;
display: inline-block;
}
.header-top .red-bg {
padding: 0 10px;
}
#header_wrapper ul.social-icons {
float: right;
}
#header_wrapper ul.social-icons li {
float: left;
list-style: none;
margin: 5px;
}
#header_wrapper ul.social-icons li a {
background: url(img/social-icons.png) no-repeat;
width: 27px;
height: 30px;
display: block;
text-decoration: none;
}
#header_wrapper ul.social-icons li.facebook a {
background-position: 0 -40px;
}
#header_wrapper ul.social-icons li.twitter a {
background-position: -27px -40px;
}
#header_wrapper ul.social-icons li.linkedin a {
background-position: -55px -40px;
}
#header_wrapper ul.social-icons li.blog a {
background-position: -84px -40px;
}
#header_wrapper .pull-right ul {
padding: 0 10px;
}
#header_wrapper ul.social-icons {
display: none;
}
a.red-bg{
display: inline-block;
background: red;
padding: 0 10px;
}
<ul>
<li><span id="contact_us">
<a href="/contact" class="red-bg" role="button">FREE Boiler Evaluation</a>
</span></li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Reproducing intersection of two curves in tikz
I am looking to reproduce the figure below using tikz:
The codes that I have aren't producing this figure exactly.
\begin{tikzpicture}[nodes={text height=0.7em,text depth=0.25ex},
my arc/.style={insert path={(4,0) arc[start angle=0,end angle=180,radius=2]}},
my curve/.style={insert path={(0,0) to[out=-90,in=-135] (1,0) -- ++ (66:4)}}]
\begin{scope}
\clip[my curve] -| cycle;
\fill[red!20,my arc] -- ++ (0,-1) -- ++ (4,0);
\end{scope}
\draw (0,4) node[above left] {$x$} |- (5,0) node[below left] {$y$};
\draw[my arc] node[pos=0.1,above right]{$\alpha\, W(y)$};
\draw[my curve] node[right] {$P(y)$};
\draw (0,2) node[left]{$x^{*}$} -| (2,0) node[below] {$y^*$}
\draw (0,1.8) node[left]{$x_{0}$} -| (1.8,0) node[below] {$y_{0}$}
(0,1) node[left]{$a$} -- (2,1) node[above left]{Incentive-feasible set};
\end{tikzpicture}
The $P(y)$ curve is too straight and the bottom is kind of flat. Also I cannot add $x_{0}$ and $y_{0}$ for some reason. My Texstudio editor would just collapse with it. Any help would be appreciated.
EDIT: With Schrodinger's cat's help:
\begin{tikzpicture}[nodes={text height=0.7em,text depth=0.25ex},
my arc/.style={insert path={(4,0) arc[start angle=0,end angle=180,radius=2]}},
my curve/.style={insert path={(0,0) to[out=-90,in=-114,looseness=1.5] (1,0) -- ++ (70:4)}}]
\begin{scope}
\clip[my curve] -| cycle;
\fill[red!20,my arc] |- ++ (4,-1);
\end{scope}
\draw (0,4) node[above left] {$x$} |- (5,0) node[below left] {$y$};
\draw[my arc,name path=arc] node[pos=0.1,above right]{$\alpha\, W(y)$};
\draw[my curve,name path=curve] node[right] {$P(y)$};
% \draw (0,2) node[left]{$x^{*}$} -| (2,0) node[below] {$y^*$};
\draw[name intersections={of=arc and curve,by={i0,i1}}]
(i1-|0,0) node[left]{$x_{0}$} -| (i1|-0,0) node[below] {$y_{0}$}
-| (2.1,0) node[below] {$y^*$} node[anchor=east,yshift=6ex,align=left]{Incentive-\\ feasible set} ;
\end{tikzpicture}
A:
This computes the intersection. The first code in this answer also does.
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[nodes={text height=0.7em,text depth=0.25ex},
my arc/.style={insert path={(4,0) arc[start angle=0,end angle=180,radius=2]}},
my curve/.style={insert path={(0,0) to[out=-90,in=-114,looseness=1.5] (1,0) -- ++ (66:4)}}]
\begin{scope}
\clip[my curve] -| cycle;
\fill[red!20,my arc] |- ++ (4,-1);
\end{scope}
\draw (0,4) node[above left] {$x$} |- (5,0) node[below left] {$y$};
\draw[my arc,name path=arc] node[pos=0.1,above right]{$\alpha\, W(y)$};
\draw[my curve,name path=curve] node[right] {$P(y)$};
% \draw (0,2) node[left]{$x^{*}$} -| (2,0) node[below] {$y^*$};
\draw[name intersections={of=arc and curve,by={i0,i1}}]
(i1-|0,0) node[left]{$x_{0}$} -| (i1|-0,0) node[below] {$y_{0}$}
(0,1) node[left]{$a$} node[anchor=west,yshift=-1.4ex,align=left]{Incentive-\\
feasible set}
-- (i1|-0,1) ;
\end{tikzpicture}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How does the judicial independence in Poland after the reforms compare to other EU countries?
There have been a lot of talks recently about the erosion of judicial independence in Poland after the new government has decided to change the way judges are nominated. However to me (as a Czech resident) this criticism seems a bit strange since in the Czech Republic judges have always been nominated directly by the executive (subject to approval by the Parliament) and therefore the judicial system has never really been independent in the first place.
How does the new situation in Poland compare to the situations in other EU countries? Is it really true that judges are usually independent from the Executive and the Legislative branches of the government?
A:
There's a key difference:
In the Czech Republic, judges are appointed for life and cannot be revoked. Once appointed they can go rabid against the Executive and Legislative branches of government if the situation calls it. (EU countries all have a similarly independent Judiciary branch, whereby Judges cannot readily be dismissed nor can they have their salary slashed on a whim.)
By contrast the Polish Justice Ministry would be able to dismiss judges if the reform passes, i.e. the Executive branch of government would be able to keep the Judiciary on a tight leash.
Further reading on Judicial independence.
A:
According to the National Law Review there are several major changes, including the following:
Increasing the number of judges and reducing their retirement age – The number of the judges of the Supreme Court will be increased from the current 81 sitting judges to at least 120. The current retirement age of 72 will be reduced to 65. The right of a judge to continue to be active after the retirement age after providing evidence of good health is limited to judges who receive the consent of Poland’s President to remain active. Because approximately 30 of the current 81 judges are above the age of 65, these two changes will mean that a new majority of judges on the Supreme Court will need to be appointed.
Changes to the method of appointing judges – Judges of the Supreme Court will be appointed by Poland’s President, following their nomination by the National Council of the Judiciary. In separate legislation, the parliament has changed the method of electing members of the National Council of the Judiciary. Before, a majority of the members of this council were judges chosen from assemblies representing various levels of the judiciary. Now, Poland’s Sejm (the lower chamber of the parliament), will have the right to choose 15 members of the council – a majority — from among Polish judges, thereby ending the dominance by members of the judiciary to nominate judges to the Supreme Court.
This means that now not only a majority of the Supreme Court judges will have to be appointed, but also that the Sejm being able to replace the majority of the National Council of the Judiciary means that (indirectly) the PiS can appoint the majority of the Supreme Court with judges that are PiS-friendly.
Note that it is not unusual in Western countries that the legislative can appoint judges (although this has been repeatedly critized), so this alone is not remarkable.
But, as Denis de Bernardy already stated in his answer, judges typically are appointed by lifetime, which makes it virtually impossible for a government to install only judges suitable to them. By contrast, the PiS is now able to install a majority of judges that suits them - and is able to fire them again when deemed necessary. This severely limits the independence of the Supreme Court and thus violates the separation of powers.
Note that it is not one aspect alone that is the problem, but the combination of all the aspects. You may find each of the aspects (legislative nominating the judges, executive being able to fire judges, judges not nominated for lifetime etc.) in some democratic states, but not all at one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible to dump AJAX content from webpage?
I would like to dump all the names on this page and all the remaining 146 pages.
The red/orange previous/next buttons uses JavaScript it seams, and gets the names by AJAX.
Question
Is it possible to write a script to crawl the 146 pages and dump the names?
Does there exist Perl modules for this kind of thing?
A:
You can use WWW::Mechanize or another Crawler for this. Web::Scraper might also be a good idea.
use Web::Scraper;
use URI;
use Data::Dump;
# First, create your scraper block
my $scraper = scraper {
# grab the text nodes from all elements with class type_firstname (that way you could also classify them by type)
process ".type_firstname", "list[]" => 'TEXT';
};
my @names;
foreach my $page ( 1 .. 146) {
# Fetch the page (add page number param)
my $res = $scraper->scrape( URI->new("http://www.familiestyrelsen.dk/samliv/navne/soeginavnelister/godkendtefornavne/drengenavne/?tx_lfnamelists_pi2[gotopage]=" . $page) );
# add them to our list of names
push @names, $_ for @{ $res->{list} };
}
dd \@names;
It will give you a very long list with all the names. Running it may take some time. Try with 1..1 first.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to use the numeric keypad in DOSBox?
Searching around Google and the DOSBox Wiki there doesn't seem to be a way to use the numeric keypad as a numeric keypad, instead it seems to behave like the arrow keys. Looking at the dosbox.config there isn't anything apparent. The keyboard setting looked promising but apparently that is for changing the language of the keyboard (as per their wiki).
A:
Press the NumLock key on your keyboard while active in DOS Box (it may not work before-hand).
| {
"pile_set_name": "StackExchange"
} |
Q:
how can I trigger a jenkins job after claim a failure?
In jenkins plugin, claim plugin can help to claim a failure job with reasons.
And with the latest version (2.6+), it is able to run a global groovy script to do some notification whenever a claim is changed
But how can I trigger another job in this script ? it shall pass important parameters like jenkins name, build number and failure reason.
A:
Finally I got answer by myself, the claim plugin is hacked using post job action, so it could be done like trigger downstream job. See code sample below:
import hudson.model.*
def job = Hudson.instance.getJob('ClaimNotify')
def build = action.owner
def causeAction = new CauseAction(new Cause.UpstreamCause(build))
Hudson.instance.queue.schedule(job,0, causeAction)
You can pass parameter there as well or in downstream job to fetch it as well.
see similar question and solution in how-do-i-dynamically-trigger-downstream-builds-in-jenkins
more information about schedule function, can check jenkins javadoc
| {
"pile_set_name": "StackExchange"
} |
Q:
My global var keeps re-defining itself
edit: solved. unsigned char fixed it.
I'm having problems with a home brew library that is supposed to psuedo-emulate vga 80x25 terminal so that I can work on some bad OS logic. Whenever I call s_put_char, it completely resets the flags char, and re-initializes my buffer.
My goal is for s_init() to be called only if s_put_char is called for the first time.
My code:
#include <stdio.h>
//this is so I can start coding logic without having to build a cross-compiler
//the only s_* method that should access by external code is s_put_char(char,int)
//all methods beginning with s_* are referring to the screen output
#define s_rows 25
#define s_columns 80
#define s_buffer_size 2000 //80x25 = 2000
char flags = 0;
//first bit is if the screen is inited or not.
char s_buffer[s_buffer_size]; //80x25
void s_update()
{
system("cls");
printf(s_buffer);
}
void s_init()
{
int index = 0;
while(index < s_buffer_size)
{
//s_buffer[index] = ' ';
index++;
}
flags += 128; //flip first bit
s_update;
}
void s_put_char(char c, unsigned int index)
{
if(flags < 128){ s_init(); }
//checks to see if the first bit is flipped or not.
//if first bit not flipped, then screen needs to be inited
s_buffer[index] = c;
s_update();
}
My specs: Mingw + Msys, Win 8
A:
In s_init():
s_update;
should be
s_update();
shouldn't it?
Also – since flags is a signed char –
flags < 128
is always true.
Try defining flags as unsigned char.
EDIT:
Actually – as noted by @KeithThompson – char might behave either as signed or as unsigned depending on the implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
make: xscale_be-gcc: Command not found
I'm new to embedded and am reading 'Embedded Linux Primer' at the moment.
I tried to build an xscale arm kernel:
make ARCH=arm CROSS_COMPILE=xscale_be- ixp4xx_defconfig
#
# configuration written to .config
followed by the make:
~/linux-stable$ make ARCH=arm CROSS_COMPILE=xscale_be- zImage
make: xscale_be-gcc: Command not found
CHK include/config/kernel.release
CHK include/generated/uapi/linux/version.h
CHK include/generated/utsrelease.h
make[1]: `include/generated/mach-types.h' is up to date.
CC kernel/bounds.s
/bin/sh: 1: xscale_be-gcc: not found
make[1]: *** [kernel/bounds.s] Error 127
make: *** [prepare0] Error 2
I had downloaded and extracted gcc-arm-none-eabi-4_9-2014q4 from
https://launchpad.net/gcc-arm-embedded
and set the path
PATH=/opt/gcc-arm-none-eabi-4_9-2014q4/bin/
Do I need another compiler for the xscale architecture?
Any ideas where I can find xscale_be-gcc?
A:
I'm reading the same book and get stuck in the same part, so... after some research i finally compiled the kernel for ixp4xx target
Download the ARM toolchain from:
Devloper arm Compiler v6
then...
$ mkdir -p ~/opt
$ cd ~/opt
$ tar xjf ~/Downloads/gcc-arm-none-eabi-6-2017-q2-update-linux.tar.bz2
$ chmod -R -w ~/opt/gcc-arm-none-eabi-6-2017-q2-update
look if the installation is correct
~/opt$ gcc-arm-none-eabi-6-2017-q2-update/bin/arm-none-eabi-gcc --version
The output will be something like this:
arm-none-eabi-gcc (GNU Tools for ARM Embedded Processors 6-2017-q2-update) 6.3.1 20170620 (release) [ARM/embedded-6-branch revision 249437]
Copyright (C) 2016 Free Software Foundation, Inc...
Now you can prepare your Kernel source tree
make ARCH=arm CROSS_COMPILE=~/opt/gcc-arm-none-eabi-6-2017-q2-update/bin/arm-none-eabi- ixp4xx_defconfig
And finally compile...
make ARCH=arm CROSS_COMPILE=~/opt/gcc-arm-none-eabi-6-2017-q2-update/bin/arm-none-eabi- zImage
Maybe it is not the best compiler for the target or need a kernel patch but... in order to follow each step in the book i think is enough.
BR,
| {
"pile_set_name": "StackExchange"
} |
Q:
rxjs - Subject subscriber misses a value
I have a Subject that is next'ed with a value before it has any subscribers - how do I make subscribers not miss values that got sent before the subscription?
Some code:
subject = new Subject<string>;
subject.next('value');
// at a later time
subject.subsribe(val => {...});
A:
If you want a subject that will emit values to subscribers that subscriber after next has been called, you can use a ReplaySubject.
When creating a ReplaySubject, you can specify the number of next notifications that are to be replayed. To replay only one, you'd use:
subject = new ReplaySubject<string>(1);
| {
"pile_set_name": "StackExchange"
} |
Q:
binary number maximum 1's
If we are given a binary number we have to find the number of maximum ones that can be obtained if we can invert( $ 1\rightarrow0, 0\rightarrow1$ ) exactly $x$ number of bits in one iteration. We can do as many iterations as we like.
$\text{Here we can reverse 3 bits at a time so }x=3;\\
100000\\
111100\\
110010\\
111111\\
$
A:
Obviously, if the binary length of your number is $n$, you won't be able to achieve the goal if $x=n$. So we'll assume that $x<n$.
Let us first prove the following lemma:
You cannot turn all zeroes into ones if the initial number of zeroes is odd and $x$ is even.
Proof: Suppose that in $x$ selected bits you have $x_1$ zeroes and $x-x_1$ ones. After the switch the number of zeroes decreases by $x_1$ and increases by $x-x_1$. So the net change in the number of zeroes is:
$$x-x_1-x_1=x-2x_1$$ The point is: if $x$ is even, the number of zeroes changes by an even number and if you start with an odd number of zeroes, you will never reach the number with all ones.
end of lemma proof
But you can get pretty much close:
Base Case: Suppose that you have at least two zeros in the binary representation of your number. WLOG, we can assume that the first two bits are zeros (same logic applies to a pair of zeroes wherever they are). So pick the first zero and $x-1$ bits starting from third and switch them. After that, pick the second zero and the same set of $x-1$ bits starting from third and switch them.
Obviously, all bits starting from the third are unchanged, but the first two zeroes are now ones. The procedure described in this case is guaranteed to reduce the number of zeroes by two. If you have an even number of zeroes in the beginning you will turn all of them into ones and you are done.
If you have an odd number of zeroes in the beginning you can bring down the number of zeroes to a single one. All other bits are ones by now.
If $x$ is odd, pick any number of ones and turn them into zeroes. Now you have an even number of zeroes and by applying "base case" you will be able to switch the number into all bits equal to one.
In case when $x$ is even and you have an odd number of zeroes in the beginning you will be able to get the number with a sinle zero but you won't be able to turn it into one. One zero has to remain.
So you can either reach a number with a single zero (if the starting number of zeroes is odd and $x$ is even) or no zeroes at all (in all other cases).
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle: How can I introspect a view?
How can I introspect a view in Oracle? For example, if I have
create view v as select foo, bar from baz
I would like to know that foo and bar are the first and second columns selected.
A:
You can use all_tab_columns also for views. So the first two columns of view v will be something like:
SELECT *
FROM all_tab_columns
WHERE TABLE_NAME = 'V' AND column_id IN (1, 2);
Then you can do ask for specific columns:
SELECT COUNT(*) TOTAL
FROM all_tab_columns
WHERE TABLE_NAME = 'V' AND (table_name,column_id) IN (('FOO',1), ('BAR',2));
If total is 2 means that foo and bar are the first and second columns selected. You can make this more readable with a case or decode:
SELECT CASE WHEN TOTAL = 2 THEN 1 ELSE 0 END RESULT FROM
(SELECT COUNT(*) TOTAL
FROM all_tab_columns
WHERE TABLE_NAME = 'V' AND (table_name,column_id) IN (('FOO',1), ('BAR',2)));
| {
"pile_set_name": "StackExchange"
} |
Q:
Combinatorial Inequality
For any integer $n>1$ prove that,
$$\large 2^n < {2n \choose n} < \frac{2^n}{\prod^{i=n-1}_{i=0}(1-\frac{i}{n})}$$
Now proving that the first term is smaller than the third term is trivial, since the term in the denominator is merely a product of $(1-\frac{i}{n})$ for $i \in \{0,1,2,....n-1\}$. Thus each individual term is less than $1$ and the entire denominator is less than 1, and we know
$$t<1 \implies 1<\frac{1}{t} \implies x<\frac{x}{t}|x,t>0$$
$2^n$ happens to be the total number of possible ways to select $r$ objects from $n$ objects for $r \in \{0,1...n\}$ and $2n \choose n$ happens to be the number of ways to choose $n$ objects from a selection of $2n$ objects, and it seems quite obvious to me that it would be greater than $2^n$ because selecting $r$ objects from $n$ followed by selecting $n-r$ from $2n-r$ would lead to $2n \choose n$. But I am not being able to prove that the second term in the inequality is smaller than the third.
Any help would be warmly appreciated. Also are there any flaws in the argument I presented?
A:
...and here is a combinatorial proof. If you want to construct an $n$-letter word from an alphabet containing $2n$ letters, the number of words is
$(2n)!/n!$ if repeated letters are not allowed;
$(2n)^n$ if repeated letters are allowed.
Clearly the first is less than or equal to the second,
$$\frac{(2n)!}{n!}\le (2n)^n\ ,$$
and this gives your desired inequality after some simple algebra.
| {
"pile_set_name": "StackExchange"
} |
Q:
Splash screen with fade in animation of ImageView
So i am trying to implement splash screen with image view fade in animation which i want to start simultaneously with the start of the splash screen activity. I also want splash screen activity to end after short delay (on touch event is optional), after animation of image view is finished.
My SplashScreen.java:
package hillbillys.delivery;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
public class SplashScreen extends AppCompatActivity implements Animation.AnimationListener {
protected Animation fadeIn;
protected ImageView img1;
protected ImageView img2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_splash);
fadeIn = AnimationUtils.loadAnimation(this,R.anim.fade_in);
/*
img1.setVisibility(View.VISIBLE);
img2.setVisibility(View.VISIBLE);
img1.startAnimation(fadeIn);
img2.startAnimation(fadeIn);
*/
Thread timerThread = new Thread(){
public void run(){
try{
sleep (2000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
@Override
protected void onPause() {
super.onPause();
finish();
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Toast.makeText(getBaseContext(), "Animation Stopped!", Toast.LENGTH_SHORT).show();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
Application crashes every time i try to add the block of code in comment, no matter where i put it. Without fade in animation works everything just fine. Is there any way how to synchronize these two in easy way? Im quite new with coding so there may be some fatal mistake in what im trying to achieve.
My screeen_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff0d9"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal"
android:src="@drawable/logo1"
android:layout_marginTop="250dp"
android:visibility="gone" />
<ImageView
android:layout_width="260dp"
android:layout_height="41dp"
android:id="@+id/imageView2"
android:layout_gravity="center_horizontal"
android:src="@drawable/logo2"
android:visibility="gone" />
</LinearLayout>
My fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0"
/>
</set>
A:
you need to initialize the ImageView before trying to access their properties. E.g.
img1 = (ImageView) findViewById(R.id.imageView);
img2 = (ImageView) findViewById(R.id.imageView2);
img1.setVisibility(View.VISIBLE);
img2.setVisibility(View.VISIBLE);
img1.startAnimation(fadeIn);
img2.startAnimation(fadeIn);
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.