Q: dojo: Show or hide divs based on selection in a list Is there a simple way to accomplish this using dojo (jQuery would be easier for me but I have to use dojo): I have a simple unordered list. I don't want dojo to style the list (as it might if I used some widget). When I click a link on the list I want to show a div associated with the link. Then if I click another link in the list the first div hides and that one shows.

Header

Link 1

Link 2

Link 3

Sub Content Header 1

Lorem ipsum veritas britas conflictum civa

Sub Content Header 2

Lorem ipsum mobius ceti

Sub Content Header 3

Lorem ipsum citrus pecto

Lemons

Limes

A: So in fact you're creating your own tabcontainer? If you really want to do it yourself you should probably need something like this:
require(["dojo/ready", "dojo/on", "dojo/dom-attr", "dojo/dom-style", "dojo/query", "dojo/NodeList-dom"], function(ready, on, domAttr, domStyle, query) {
    ready(function() {
        query("ul li a").forEach(function(node) {
            query(domAttr.get(node, "href")).forEach(function(node) {
                domStyle.set(node, "display", "none");
            });

            on(node, "click", function(e) {
                query("ul li a").forEach(function(node) {
                    if (node == e.target) {
                        query(domAttr.get(node, "href")).forEach(function(node) {
                            domStyle.set(node, "display", "block");
                        });
                    } else {
                        query(domAttr.get(node, "href")).forEach(function(node) {
                            domStyle.set(node, "display", "none");
                        });
                    }
                });
            });
        });
    });
});

I'm not sure how familiar you are with Dojo, but it uses a query that will loop all links in lists (with the dojo/query and dojo/NodeList-dom modules) (you should provide a classname or something like that to make it easier). Then it will, for each link, retrieve the div corresponding to it and hide it, it will also connect a click event handler to it (with the dojo/on module).
When someone clicks the link, it will (again) loop all the links, but this time it's doing that to determine which node is the target one and which isn't (so it can hide/show the corresponding div).
I made a JSFiddle to show you this. If something is still not clear you should first try to look at the reference guide of Dojo since it really demonstrates the most common uses of most modules.
But since this behavior is quite similar to a TabContainer, I would recommend you to look at the TabContainer reference guide.


Q: CSS3 :target on named tag not working I am having a hard time getting :target to work on a named tag.
The fiddle is here: https://jsfiddle.net/vgcLartp/1
Any ideas why this is not working?

A: You need to use target on the sections that you want to show not the links
section:target {...}

See updated jsfiddle

nav {
  height: 60px;
  border-bottom: 1px solid #eaeaea;
}

.nav-item {
  display: block;
  float: left;
  margin-right: 20px;
  height: 60px;
  font-size: 26px;
  line-height: 60px;
  text-align: center;
  overflow: hidden;
  color: #666;
  text-decoration: none;
  border-bottom: 3px solid transparent;
  outline: none;
}

.nav-item:last-child {
  margin-right: 0;
}

.nav-item:hover {
  color: #333;
}

.nav-item.active,
.nav-item.active:hover {
  color: #333;
  border-bottom-color: #b39095;
}

section:target {
  visibility: visible;
  opacity: 1;
}

/* -------------------------------- SECTIONS -------------------------------- */

#sections {
  float: left;
  width: 1200px;
  height: 400px;
}

section {
  position: fixed;
  width: 630px;
  height: 400px;
  float: left;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.5s linear;
}

section p {
  padding-top: 5px;
  line-height: 1.6em;
}

section a {
  color: #b39095;
  text-decoration: none;
}

section a:hover {
  color: #7b618a;
}

/* --------------------------------- OPTIONS -------------------------------- */

fieldset {
  margin: 26px 0 15px 0;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}

input {
  padding-left: 2px;
}

#oxford-app-id {
  width: 80px;
}

#oxford-app-key {
  width: 290px;
}

label {
  padding-left: 5px;
}

      options
saved
      about

        Options

        About

A: try this
:target {
  visibility: visible;
  opacity: 1;
}

A: From w3school:

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
  The :target selector can be used to style the current active target element.

:target selector is useful when within an URL is specified (using an anchor  for example) an element in your HTML.
In your case you can use:
:target {
    visibility: visible;
    opacity: 1;
}


Q: Как правильно в модели связать поле с родной таблицей Django? Добрый день!
Подскажите, пожалуйста, как правильно в модели связать поле с родной таблицей Django auth_user (чтобы при добавлении в базу записывался id пользователя).
И стоит ли использовать родную авторизацию и регистрацию Django если она подходит под проект или лучше делать что-то свое?
A: Связать объекты с юзером элементарно - user = models.ForeignKey('auth.user'), в свежих версиях Django несложно сделать свою модель пользователя, но если вас устраивает стандартный - берите для начала его.


Q: Android AVD install chrome and firefox I created few AVD's using the AVD Manager. I want to know how can I install chrome/firefox on these AVD's?

A: Chrome's .apk
Firefox's .apk
Download both .apk files and install to your AVD using adb install apk_name

A: To install something onto a device, you need to already have the device running.
So first, start the device using the emulator command.
Then, in a different terminal/command window, use the adb command to install the package. In my case, I've copied the apk file to the platform-tools folder:
./adb install Firefox_17.0.apk

Like the rest of the emulator, the installation is slow, so be patient.
Of course, this just installs the packages. Getting them to run successfully is another matter entirely. So far, I cannot get the Chrome or Firefox packages to run. Chrome says "Not supported on this version of Android. Version 4.0 is minimal supported version." I am running 4.3 in the emulator. And Firefox starts but then immediately terminates with a "Unfortunately, Firefox has stopped" message.

A: Get the apk files and install them through adb (adb install .apk.


Q: Zookeeper - cant telnet into xxx.xxx.xxx.xxx 2181 on one server. Any other - no issue I have three zookeeper nodes in tokyo, london, and freemont on linode servers. All are gossiping.
I have a monitoring server in tokyo.
I have NOT activated the zookeeper firewall on all zookeeper servers.
From my local dev laptop, aws, etc machine I can telnet into anyone of the zookeeper nodes.
From linode, monitoring server, I cant connect by using any client.
I did use UFW to block incoming ports on the monitoring server but I dont see
how that is causing issues with zookeeper port.  I even disable as well to avail.
From the monitoring server I get nothing.
telnet xxx.xxx.xxx.xxx 2181

Trying xxx.xxx.xxx.xxx...
Connected to xxx.xxx.xxx.xxx.
Escape character is '^]'.
Connection closed by foreign host.

using mtr --report from both ends shows no issues.
So, I cant connect to zookeeper from a server.  How do I find out what is going on?

A: But you are connected:
Connected to xxx.xxx.xxx.xxx.

Whether or not you get any initial communication from the server you're connecting to (a la SSH or SMTP) or the server is waiting for the client to start (HTTP) is a protocol specific issue.  However the problem is (almost) certainly not a firewalling problem.


Q: Compositions of prime numbers This question is related to numbers found in the OEIS sequence A191837.
In this sequence, $a(2) = 48 = 5 + 7 + 17 + 19$, where the summands of 48 are all prime numbers that are less than or equal to $48/2=24$.  The prime factors of 48 are $2^4$ and $3$, and neither $2$ nor $3$ are summands in $a(2)$.  Similarly, $a(3) = 108 = 5 + 7 + 11 + 19 + 29 + 37$ and the prime factors of $108$ ($2^2$ and $3^3$) are not summands in $a(3)$.  This appears to hold for all fourteen (verified and unverified) integers in the sequence.
Is there some way to prove or disprove the conjecture that for every integer in sequence A191837, the prime factors of $a(n)$ will never be an element of the summands of $a(n)$?

A: Yes, of course, it's easy to prove the statement. In fact, the greatest common divisor of $a(n)$ and any of the summands $s$ in $a(n)$ has to be equal to one - they have to be relatively prime.
If they were not relatively prime, then we could look at the greatest common divisor $g>1$ of $s$ and $a(n)$. If $g<s$, then $s$ wouldn't be a prime because it would have a divisor $g$, and such composite $s$ isn't allowed as a summand of $a(n)$ in the sequence.
If $g=s$, then we couldn't prove that $s$ is non-prime. However, $a(n)-s$ would also be a multiple of $g$ but we would have $a(n)-s > a(n)/2 > g$, so $a(n)-s$ wouldn't be a prime which would again violate the condition that both the summands $s$ and the differences $a(n)-s$ have to be prime for the elements $a(n)$ of your sequence (check the page you linked to carefully how the numbers are defined).
Not only you can omit candidate summands of $a(n)$ that are prime factors of $a(n)$: you may omit all candidate summands that fail to be relatively prime with $a(n)$. Well, truth to be told, it's almost the same thing if you know that the summands have to be prime.


Q: Fibonacci Sunflower spirals Counting the clockwise and counterclockwise spirals that reach the outer edge, and we find a pair of numbers from the Fibonacci sequence: 34 and 55, or 55 and 89, or, with very large sunflowers: 89 and 144.
How can one sketch these symmetrical spirals in a plane? It requires the $r-\theta$ polar relation. The interpolating function for continuous polar curve is:
FunctionExpand[Fibonacci[n]]
=((1/2 (1 + Sqrt[5]))^n - (2/(1 + Sqrt[5]))^n Cos[n π])/Sqrt[5]


Q: How to remove "continue;"? I have this c++ program that tries to remove vowels from a char array. This works, but I want to do this without continue;.
#include <iostream>
#include <string.h>
using namespace std;

int main() {

    char s[21],afterElimination[19],vowels[] = "aeiou";
    cin.get(s,20);
    int i, n = strlen(s),VowelPos = -1,h = 0;
    for (i = 0; i < n; i++) {
        if (strchr(vowels,s[i])) {
            if(VowelPos == -1) {
                VowelPos = i;
                continue;
            }
            VowelPos = i - 1;
        }
        afterElimination[h++] = s[i];

    }
    afterElimination[h] = NULL;
    strcpy(afterElimination + VowelPos, afterElimination + VowelPos + 1);

    cout<<afterElimination;

    return 0;
}

A: It's pretty easy to remove continue from the loop.  What you need is two indexes in your loop.  One for the position in the source array and one for the position in the array to copy to.  Then you put the copy operation inside the if statement so if there is no copy you do nothing to go to the next iteration.  That would make you loop look like
for (int source_index = 0, copy_index = 0; source_index < n; ++source_index) { // increment source_index always
    if (!strchr(vowels,s[i])) {
        // this isn't a vowel so copy and increment copy_index
        afterElimination[copy_index++] = s[i];
    }
    // now this is the continue but we don't need to say it
}

A: This is a typical approach to filtering letters from a given string.
#include <string.h>

char s[20] = "something";
char no_vowels[20] = {0};

int i = 0;
int j = 0;
const char *vowels = "aeiou";
while (s[i]) {
  if (!strchr(vowels, s[i])) {
    no_vowels[j] = s[i];
    j++;
  }
  i++;
}

Here's a working example.


Q: I can't make this JavaScript count working I want to make a button (out of divs) and a paragraph (or any text field) below the divs that counts the clicks.

$(document).ready(function() {
  $('#butt').mousedown(function() {
    $("#butt").hide();

  });
  $("#pushed").mouseup(function() {
    $("#butt").show();

  });
  $("#butt").click(function() {
    button_click();
  });
});

var clicks = 0;

function button_click() {
  clicks = parseInt(clicks) + parseInt(1);
  var divData = document.getElementById("showCount");
  divData.innerHTML = "Clicks:" + clicks;
}

<form name="ButtonForm">

</form>

A: Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them.
Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well.
Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div.
Lastly, to increment a number by one, you can just use the pre or post-increment operator (++).

$(document).ready(function() {
  var clicks = 0;
  var divData = $("#clickCount");

  $("#pushed").on("click", function() {
    $("#butt").show();
  });

  $("#butt").on("click", function() {
    $("#butt").hide();
    clicks++;  // increment the counter by one
    divData.html(clicks);
  });
});
#pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;}

  <form name="ButtonForm">

Clicks

  </form>

A: First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for.
Second, change the #butt element to an actual button so that you have something to see and click.
Third, make sure your script is loading after jquery is included.

<button id="butt">I'm a button</button>


Q: Proxy for MSGraph APIs I am trying to create an adapter (WEB API that will act as a pass through)
for invoking the MS Graph APIs for managing my Active Directory.
AD objects like application and users will be customized to meet our application needs (removing some attributes, adding some extension attributes etc.) and a transformation from our application specific object to AD object would happen in our adapter layer before and after calling MS Graph APIs.
MS Graph APIs currently supports OData queries.
Applications and users would be read as page-wise.
If I have to provide the same OData options in my pass thru Web API layer, how can I do that?
i.e.

*

*API A supports OData queries.

*API B calls the methods that support OData queries in API A.

*API B is exposed to the client. When the client calls the method from API B
 with OData $Filter, the result has to be returned.

How can I support the OData options in API B?
Thanks in advance.

A: Well, I'm not sure I get your question correctly but, from what I understand, you just want to proxy the API calls to MS Graph and make some changes on the fly to the response.
OData queries are just simple query parameters (see the OData tutorial). So, basically, you just have to get those query parameters in your proxy and forward them to the MS Graph. The response you'll get will then be compliant with the original query.
However, depending on how you mangle the data, you may end up not being compliant with the user query. For example:

*

*The user made a $select(Id) query, but your logic add a custom property Foo. The user just wanted Id but you added Foo anyway.

*The user made an $orderby Name asc query, but your logic modify the property Name. It may not be ordered after your logic.

*The user wants to make $filter query on the Foo property. MS Graph will complain because it doesn't know the Foo property.

*Etc.

If you want to handle that cases, well, you'll have to parse the different OData queries and adapt your logic accordingly. $orderby, $top/$skip, $count, $expand and $select should be pretty straight-forward ; $filter and $search would require a bit more work.

A: Thanks. I was looking for a solution to this.
https://community.apigee.com/questions/8642/how-do-we-fetch-the-query-parameters-odata-standar.html
Instead of parsing the URL to get the OData query parameters, i wanted to understand the standard method to process the OData requests.
Now I am doing the below to extract the OData query parameters and passing them to MSGraph API.
string strODataQuery = String.Join("&", HttpContext.Request.Query.Where(kvp => kvp.Key.StartsWith("$")) .Select(kvp => String.Format("{0}={1}", kvp.Key, Uri.EscapeDataString(kvp.Value))));
And I am performing the conversions after retrieving the results.
Regards


Q: $ \lim_{x \to 0^{-}} 1 + e^{1/x}$ (Definition) Using the definition of limit, I need to show that $\lim_{x \to 0^-} 1 + e^{1/x} =1$.
Using the definition, I have that $x > \frac{1}{\ln \epsilon}(|e^{1/x}|=e^{1/x} < \epsilon)$, but this is not helping since I need a positive delta. Also, I coudn't deal with the case $\epsilon = 1$
Can you help me with it?
Thanks!

A: Hint: $e^{1/x} < \varepsilon \iff \dfrac1x < \ln \varepsilon \iff \dfrac1{\ln\varepsilon} < x < 0$.


Q: GPO to disable server manager icon does not restrict access for users I have two servers in a domain, running on VMWare. WS2K8R2 domain controller and Server 2012 RD Session host. I want to disable/remove  the server manager and powershell icons from the taskbar, and make them inaccessible to users.
I have configure group policy  Computer Configuration > Policies > Windows Settings > Security Settings > File System and made these entries:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\Server Manager.lnk
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\Windows PowerShell Modules.lnk
Removed Creator Owner and Users from the permissions and run gpupdate.
Users still have those icons available and clicking on them opens up those applications. There are additional GPO's that are active and do work.
Is there something else I need to check?
Thank you

A: If the users have already logged in, those shortcuts will still appear to them. You need to configure this before they log in or delete their local profile. New users logging in should not see these icons.
This will not restrict access to these executables though. If you want to keep the Start Menu and Taskbar tidy, this is fine. If you want to limit what they can launch, you should use a software restriction policy or applocker update through GPO to whitelist only what you want running on that machine.

A: Do this to simplify your life:
Go the the GPO in question, edit it and go to the following:
User COnfiguration/policies/Administrative Templates/system

Enable: Don't run specified Windows Applications
In that other also click on Show disallowed apps, and add the following:
ServerManager.exe
cmd.exe
powershell.exe

Apply and log off and on depending on the replication of server may take up to an hour to replicate, if that fails do a GPupdate /force.
This will prevent users from accessing the server manager, remember that the Administrator should not be part of the GPO you are setting up.


Q: Secure permissions setup for Drupal website with multiple maintainers For several Drupal sites a colleague of mine and I (for demonstration purposes alice and bob) are responsible for maintaining these installations. We both have an SSH account to log into the server (with ID file, no password). However, we are not server administrators and have no sudo rights or permissions.
On drupal.org there is a detailled page on file permissions and I also read this question on serverfault. But I can't come up with are secure system for our situation.
Current setup of users:
uid=16(alice)    gid=1001(webteam) groups=1001(webteam),32(www-data)
uid=17(bob)      gid=1001(webteam) groups=1001(webteam),32(www-data)
uid=32(www-data) gid=32(www-data)  groups=32(www-data)

From what I understand, the Apache user (www-data) shouldn't have write access to files which it will execute. Depending on whether Alice or Bob have installed the system, file owner is different for system files, but group is set to webteam and permissions are 664, so both owner and group can write, Apache can only read the file:
-rw-rw-r--+   1 alice  webteam    529 Oct 15 16:36 index.php
-rw-rw-r--+   1 bob    webteam   3847 Sep 28 12:03 update.php

In Drupal (as probably in other CMS as well), there is a special folder (by default at ./sites/default/files) where Drupal saves cache files and user uploads. So this folder must have rw for Apache. Currently it looks like this (files is for public files, hotlinking allowed; secure is for the private file system in Drupal):
drwxrwsr-x+ 12 alice www-data  4096 Oct 29 11:43 files
drwxrwsr-x+  3 alice www-data 20480 Oct 24 15:27 secure

In this case, Alice created the website and thus is owner of the directories. www-data is allowed to do everything in there as well as it is required (as mentioned before). Bob does have access to these directories as well as he is member of www-data.
Question 1: Is there a better way to distribute permissions, do you see any (security) flaws with this setup?
When using the drush tool to update modules and/or Drupal core, another problem arises. drush uses the user who executes drush and also sets the permission as advised by Drupal. The first files (index/update.php) look like this after drush was executed by Alice:
-rw-r--r--+   1 alice  webteam    529 Oct 15 16:36 index.php
-rw-r--r--+   1 alice  webteam   3847 Sep 28 12:03 update.php

The problem is clear, Bob can no longer write or delete these files. Also, he can't run drush on that installation (it will fail with permissions issues).
Question 2: What is the best way to avoid this or to straighten it after drush ran?
First option we thought of would be to have a single user (e.g. webteam) which both Alice and Bob use to log into the server. But personally, I prefer to have my own home directory and my own .bash_rc file with custom prompt and aliases. Second, since drush is already executed through a shell script, we could (re)set the file permissions after drush runs. Maybe there's an even better way?

A: What we do is we checkout the code to a directory outside of the webserver's DocumentRoot. Then we have install and update scripts that chmod the files/directories and rsync them over to the webserver's DocumentRoot. We also --exclude certain files/directories that we don't want on our production servers (e.g. xmlrpc.php, sites/all/modules/simpletest) while doing the rsync.
Essentially all files are 440 and all directories are 550 with the exception of the ../sites/$SITE/files directories which are 770, all apache:apache for owner:group.
We do grant sudo to our admins and when using drush we execute like so:
sudo -u apache drush ...

Hope this helps.
P.S.
You might want to cross-post to drupal.stackexchange.com if you haven't done so already.


Q: Hibernate - Updating an ID of a parent in a child without updating parent? I couldn't find the answer or didn't phrase this question properly. If you guys know... let me know :-)
I have a parent which has children....
on the child, I have regular vars that map to column names
However, one is mapped as many-to-one. The child basically contains the ID for the parent. Except in the child I obviously contain the entity of the parent, not the id.
ie: (QUICK simple example....)
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name="bcId",referencedColumnName="id")
private ParentEntityClass theParentClass;

How, can I set the the parent object in this hibernate entity so it ONLY uses the parent entity for the ID and doesn't try to save the parent. Should I use Cascade.refresh so it refreshes but doesn't update the parent?
Thanks :)


Q: Why are these MongoDB sums not adding up? Lets say I have 2 documents:
{
    "_id" : "8tvgUTKt2U",
    "answers" : [
        [
            NumberInt(-1)
        ]
    ]
},
{
    "_id" : "BDTESUEIlm",
    "answers" : [
        [
            NumberInt(1)
        ],
        [
            NumberInt(-1)
        ]
    ]
}

I would like to total the values of the array items. But when I $unwind 'answers' and $sum them in $group pipeline I get this:
{
    "_id" : "BDTESUEIlm",
    "answerTotal" : NumberInt(0)
}
{
    "_id" : "8tvgUTKt2U",
    "answerTotal" : NumberInt(0)
}

What am I doing wrong?

A: It’s because when you $unwind a two dimensional array once you end up with just an array and $sum gives correct results when applied to numerical values in $group pipeline stage otherwise it will default to 0 if all operands are non-numeric.
To remedy this, you can use the $sum in a $project pipeline without the need to $unwind as $sum traverses into the array to operate on the numerical elements of the array to return a single value if the expression resolves to an array.
Consider running the following pipeline to get the correct results:
db.collection.aggregate([
    { '$project': {
        'answerTotal': {
            '$sum': {
                '$map': {
                    'input': '$answers',
                    'as': 'ans',
                    'in': { '$sum': '$$ans' }
                }
            }
        }
    } }
])


Q: SQL update query not cooperating I am adding a save/update button to the bottom of my editing form on my admin panel. For some reason, whenever I make a change to the form and click save it just reloads the page with no changes made. I also noticed that ONLY when I try to run the code from the pages.php file(runnning from index then clicking pages is fine) it says:

Undefined variable: dbc in
  C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
  on line 12
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
  in
  C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
  on line 12

I can get rid of this error by declaring a new $dbc(databaseconnection) variable in pages.php, but I still have the same problem updating my form data.
PAGES.PHP:
<?php ## Page Manager ?>

Page Manager

        <?php

           $q = "SELECT * FROM pages ORDER BY name ASC";
           $r = mysqli_query($dbc, $q);

           if ($r)
           {
                while ($link = mysqli_fetch_assoc($r))
                {
                    echo '
'.$link['name'].'
';
                }
           }

        ?>

    <?php

     if (isset($_POST['submitted']) == 1) {

            $q = "UPDATE pages SET title='$_POST[title]', name='$_POST[name]', body='$_POST[body]', WHERE id = '$_POST[id]'";
            $r = mysqli_query($dbc, $q);

     }

     if (isset($_GET['id'])) {

            $q = "SELECT * FROM pages WHERE id = '$_GET[id]' LIMIT 1";
;
            $r = mysqli_query($dbc, $q);
            $opened = mysqli_fetch_assoc($r);

    ?>

        <form action="?page=pages&id=<?php echo $opened['id'] ?>" method="post">

Page title: <input type="text" size="30" name="title" value="<?php echo $opened['title']?>">

Page name: <input type="text" size="30" name="name" value="<?php echo $opened['name']?>">

            Page body:

            <textarea name="body" cols="30" rows="8"><?php echo $opened['body'] ?></textarea>

               <input type="hidden" name="submitted" value="1"/>
               <input type="hidden" name="id" value="<?php echo $opened['id'] ?>"/>

<input type="submit" name="submit" value="Save Changes"/>

        </form>

    <?php } ?>

INDEX.PHP:
<?php
// Setup document:
include('config/setup.php');
?>

<!DOCTYPE HTML>

<meta charset="utf-8">
<title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">

 <?php head(); ?>

 <?php nav_main(); ?>

 <?php include('content/'.$pg.'.php'); ?>

 <?php footer(); ?>

SETUP.PHP
<?php
## Setup Document

// host(or location of the database), username, //password, database name

$dbc = @mysqli_connect('127.0.0.1', 'root', 'password', 'main') OR die ('Could not connect to the database because: '. mysqli_connect_error() );

include('Functions/sandbox.php');
include('Functions/template.php');

if (isset($_GET['page']) == '')
{
    $pg = 'home';
}
else
{
    $pg = $_GET['page'];
}

$page_title = get_page_title($dbc, $pg);

?>

A: on Pages.php you have
$r = mysqli_query($dbc, $q);

$q is fine but you have not mentioned $dbc
on your setup page, create a class for connection, declareing a connection method and then, on PAGES.PHP:
$db_obj =  new setup();  /* create object for setup class */
$dbc = $db_obj -> connect_db();/* call connection method */


Q: Show that this process is a martingale Let $B_t$ be a Brownian motion and $M_t=\max_{0\leq s\leq t}B_s$. Show that: $$(M_t-B_t)^4-6t(M_t-B_t)^2+3t^2$$
is a martingale for $t\geq0$.

A: I would go this way using the fact  that (see my comment below) :
$(M_t-B_t)$ and $|B_t|$ are processes equal in law.
I would use Itô's lemma with $f(x,t)=x^2-6t.x+3t^2$ and show (if true) that there is no drift.
The delicate part is then to justify the fact that if you have 2 processes equal in law and if one of them is a martingale then the other one is also a martingale.
Comment (edited thank's to did's comment):
For the fact that  $(M_t-B_t)$ and $|B_t|$ are equal in law you can have a look at Karatzas and Shreve's book for a proof.
Best regards

A: Observe that
$$(M_t-B_t)^4 = \left(\max_{0 \leq r \leq t} (B_r-B_t)\right)^4 = \max_{0 \leq r \leq t} ((B_r-B_t)^4) \\ = \max_{0 \leq r \leq s} ((B_r-B_s)^4) + \max_{0 \leq r \leq t-s} \left(((B_{s+r}-B_s)-(B_t-B_s))\right)^4$$
Moreover,
$$\max_{0 \leq r \leq t-s} ((B_{s+r}-B_s)-(B_t-B_s))^4 = \max_{0 \leq r \leq t-s} (W_r-W_{t-s})^4 = (M_{t-s}^\ast-W_{t-s})^4$$
where $W_{r} := B_{s+r}-B_s$ (is again Brownian motion), $M_t^\ast := \max_{0 \leq r \leq t} W_r$. From reflection principle we know that
$$M_{t-s}^\ast - W_{t-s} \sim \sqrt{\frac{2}{\pi \cdot (t-s)}} \cdot \exp \left(- \frac{x^2}{2(t-s)} \right) \cdot 1_{(0,\infty)}(x)$$
hence $$\mathbb{E}((M_{t-s}^\ast-W_{t-s})^4)=3(t-s)^2$$
Thus
$$\mathbb{E}((M_t-B_t)^4|\mathcal{F}_s) = (M_s-B_s)^4 + \mathbb{E} \left( \max_{0 \leq r \leq t-s} (B_{s+r}-B_t)^4 |\mathcal{F}_s \right) \\ =(M_s-B_s)^4 + \underbrace{\mathbb{E} \left( \max_{0 \leq r \leq t-s} (B_{s+r}-B_t)^4 \right)}_{\mathbb{E}((M_{t-s}^\ast-W_{t-s})^4)} =(M_s-B_s)^4 +3 \cdot (t-s)^2$$
Similar proof works for $(M_t-B_t)^2$. Adding it all up finishs the proof.


Q: What does "Candygram" mean?
Candygram? What does it mean? I read this entry, but it didn't make sense.

Candygram
  candy that can be ordered by wire for delivery with an accompanying message, as on the recipient's birthday or anniversary.

The caption on the image says:

A: Assault happened sometime after they closed, a little after 2:00. Bodyguard Luis Lopez was hit first. Frankie Adkins, he's the owner of the bar, he was hit next. We ID'd the body as Isaac Proctor.
B: Proctor? Name's familiar.
A: Isaac is the son of cirminal defense attorney Amanda Proctor.
B: I dealt with her. She's kept a lot of bad people on the street.
C: So someone kills her son. Is someone trying to send a message?
A: If they are, it's a pretty brutal candygram.
B: Sword. It's pretty old-school.
C: Any witnesses?

...

A: Candygram a derived form of the word telegram, where the suffix -gram means "sent from someone else".
Officially, NOAD says that the suffix -gram means:

in nouns, denoting something written or recorded (especially in a certain way):
cryptogram | heliogram.

However, at least informally, the suffix -gram has come to be used by companies that deliver things other than messages, presumably because candygram sounded more catchy than telecandy. Other quaint forms I've heard include pajamagram, a website that lets you order pajamas online and send them to someone else as a gift. There are websites called flowergram and candygram as well, and kissograms have been around for some time.
If I sent you a candygram, it might look something like this:

That explains what a candygram is. In the crime drama you are citing, a pun is being made on the phrase "send a message.” In the criminal underworld, when we send a message to someone, that means we are warning them about something we don't appreciate, often under a threat or act of violence. (As an example, there's the famous horse head scene in the movie The Godfather.)
So when they see the victim on the street, one investigator asks, "Are they trying to send a message?" meaning, "Are they trying to intimidate someone, or maybe warn some group about more potential violence?"
The other makes a grim joke, because one way to send a message (like a nice message, to a close friend) is a Candygram. He may have just as well said, “If so, it’s a pretty brutal message indeed,” but I assume the writers thought the use of the word “Candygram” would make the dialogue seem more clever. This sort of verbal exchange is not uncommon on television crime shows.


Q: c++ how to create a std::vector of functors class A
{
public:
    int x;
    //create a vector of functors in B and C here
};

class B
{
public:
    struct bFunctor
    {
        void operator()() const
        {
            //some code
        }
    };
};

class C
{
public:
    struct cFunctor
    {
        void operator()() const
        {
            //some code
        }
    };

};

void main()
{
 A obj;
 //iterate through the vector in A and call the functors in B and C
}

My question is what should be the format of the vector in class A for calling functors in B and C? Or is the only way this is possible to have a base functor in A and make the functors in B and C derive from it? Or is there a better approach?

A: There are essentially two ways to approach this (that I can think of ATM):
Note: I would rename cFunctor and bFunctor to simply Functor in both cases. They are nested inside respective classes and thus such prefix makes little sense.
Type erased
Example of type erasure is std::function.
class A {
public:
    int x;
    std::vector<std::function<void(void)>> functors;

    A() : functors { B::bFunctor(), C::cFunctor() }
    { }
};

If you need the functors to have more advanced behaviour, Boost.TypeErasure any might help.
Polymorphic

*

*Create an abstract functor type.

*Make B::bFunctor and C::cFunctor inherit from it.

*Store vector of that abstract functor type smart pointers.

struct AbstractFunctor {
    virtual void operator()() const = 0;
};

class B {
public:
    struct Functor : public AbstractFunctor {
       void operator()() const {
       //some code
       }
    };
};

class A {
public:
    int x;
    std::vector<std::unique_ptr<AbstractFunctor>> functors;

    A() {
        // this could most probably be shortened with make_unique
        functors.emplace_back(std::unique_ptr<AbstractFunctor>(new B::Functor()));
        functors.emplace_back(std::unique_ptr<AbstractFunctor>(new C::Functor()));
    }
};


Q: Cannot validate, with novalidate option Hi I was inserting some date do my table. For some reasons I had to disable my constraint. The constraint was associated with index. I. ve used this line of code:
ALTER TABLE my_table DISABLE CONSTRAINT "my_constraint" drop index

And my_constraint is in disable state.
No I' d like to enable this constraint, but after calling this line:
ALTER TABLE my_table ENABLE NOVALIDATE CONSTRAINT "my_constraint";\

I recive an error:

ORA-02299: cannot validate (USER.my_constraint) -  - duplicate keys found

A: You cannot have non-unique values with a unique index.  But you can have non-unique values with a unique constraint that is enforced by a non-unique index.  Even if you initially created a non-unique index, the drop index and enable syntax will try to recreate a unique index unless you provide more details in the using index section.
For example:
SQL> create table my_table(my_column number,
  2     constraint my_constraint unique (my_column));

Table created.

SQL> alter table my_table disable constraint my_constraint drop index;

Table altered.

SQL> insert into my_table select 1 from dual union all select 1 from dual;

2 rows created.

SQL> alter table my_table enable novalidate constraint my_constraint;
alter table my_table enable novalidate constraint my_constraint
*
ERROR at line 1:
ORA-02299: cannot validate (USER.MY_CONSTRAINT) - duplicate keys found

SQL> alter table my_table enable novalidate constraint my_constraint
  2     using index (create index my_index on my_table(my_column));

Table altered.

SQL> --The constraint is enforced, even though other rows violate it.
SQL> insert into my_table values(1);
insert into my_table values(1)
*
ERROR at line 1:
ORA-00001: unique constraint (USER.MY_CONSTRAINT) violated

A: When you inserted the rows into your table you violated the constraint, looks like it is a unique constraint based on the error message "duplicate keys found"
check what columns the constraint is based on, and then do a quick query like the following to see if you have any rows with duplicates (columna and columnb are the columns in your unique constraint)
SELECT columna, columnb COUNT()
FROM mytable
HAVING COUNT() > 1
You won't be able to enable the unique constraint until all the rows in the table meet the rules of the constraint.


Q: Handling the Windows.UI.Xaml.Application.Suspending event I try to resolve the dreaded .WindowsPhone.exe!{<ID>}_Quiesce_Hang hang issue of my WinRT (Windows Phone 8.1) app.
At the moment I have the following handling of the Windows.UI.Xaml.Application.Suspending event:
    private void App_Suspending(object iSender, SuspendingEventArgs iArgs)
    {
        SuspendingDeferral clsDeferral = null;
        object objLock = new object();

        try
        {
            clsDeferral = iArgs.SuspendingOperation.GetDeferral();
            DateTimeOffset clsDeadline = iArgs.SuspendingOperation.Deadline;

            //This task is to ensure that the clsDeferral.Complete()
            //is called before the deadline.
            System.Threading.Tasks.Task.Run(
                async delegate
                {
                    //Reducing the timeout by 1 second just in case.
                    TimeSpan clsTimeout = clsDeadline.Subtract(DateTime.UtcNow).Subtract(TimeSpan.FromSeconds(1));

                    if (clsTimeout.TotalMilliseconds > 100)
                    {
                        await System.Threading.Tasks.Task.Delay(clsTimeout);
                    }

                    DeferrerComplete(objLock, ref clsDeferral);
                });

            //Here I execute the suspending code i.e. I serializing the app
            //state and save it in files. This may take more than clsTimeout
            //on some devices.
            ...

            //I do not call the Complete method here because the above
            //suspending code is old-fashoin asynchronous i.e. not async but
            //returns before the job is done.
            //DeferrerComplete(objLock, ref clsDeferral);
        }
        catch
        {
            DeferrerComplete(objLock, ref clsDeferral);
        }
    }

    private static void DeferrerComplete(object iLock, ref SuspendingDeferral ioDeferral)
    {
        lock (iLock)
        {
            if (ioDeferral != null)
            {
                try
                {
                    ioDeferral.Complete();
                }
                catch
                {
                }

                ioDeferral = null;
            }
        }
    }

I have read the answer about the _Quiesce_Hang problem. I get the idea that it might be related to app storage activity. So my question is: what am I missing? Does my handling of the Suspending event look OK?


Q: Unity 2 and Enterprise library configuration tool Can someone show me how to use Enterprise library configuration tool with Unity2
Whatever I did, when I open the Enterprise library configuration tool, I could not have it working with a Unity config file.
When I click on the menu to add a new block, there is no Unity configuration block
What am I doing wrong?
Thank you for your help

A: Unity 2.0 and documentation is available as a separate download as of today.
http://msdn.microsoft.com/unity
http://blogs.msdn.com/agile/archive/2010/04/20/microsoft-enterprise-library-5-0-released.aspx
Unfortunately the limited support for the Unity configuration in the Configuration Tool that you may have seen in one of the EntLib 5.0 betas didn't make it into the final release due to time constraints.
However, we have made the Unity configuration XML significantly easier to author with things like assembly and namespace aliasing to save having to repeatedly specify fully qualified types.

A: We have released Unity 2.0 standalone, Unity 2.0 for Silverlight as well as Enterprise Library 5.0 full documentation set today.

A: Unity 2 is not yet finalized (still in Beta 2). I guess we have to wait.
Besides, Unity 2 config file is much easier to be typed manually, compared to the 1.x versions.

A: If interested in Unity config tool, which was part of the beta but didn't make it to the final EntLib5.0 release, you can find it here


Q: Testing android app. Trying to mock getSystemService. Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually.
We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before.
The method I'm trying to test:
public boolean isGPSEnabled()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return GPSEnabled;
}

This method checks if the android device got the GPS enabled and returns true if it is, false if not.
I'm trying to mock the LocationManager and the Context, and this is what I have so far:
@RunWith(MockitoJUnitRunner.class)

public class IsGPSEnabledTest
{

    @Mock
    LocationManager locationManagerMock = mock(LocationManager.class);
    MockContext contextMock = mock(MockContext.class);

    @Test
    public void testGPSEnabledTrue() throws Exception
    {
        when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock);
        when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);

        MapsActivity activity = new MapsActivity();
        assertEquals(true, activity.isGPSEnabled());
    }
}

When I run this test I get this error:
"java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked."
Any help on this would be appreciated.

A: Pass the mocked context to your method in activity.
    @Test
    public void isGpsOn() {
        final Context context = mock(Context.class);
        final LocationManager manager = mock(LocationManager.class);
        Mockito.when(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(manager);
        Mockito.when(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);
        assertTrue(activity.isGpsEnabled(context));
    }


Q: double returning only one precision in java in my code i am performing division on numbers and storing it in a double variable. but the variable is returning with only one precision. i want to increase the precision how could i do that.
double x;
        for ( int i =0 ; i<10000 ; i++)
        {

            x= w[i] / l[i];
            System.out.println(x);
        }

in the above code w and l are integer arrays;
i am getting output like
3.0
0.0
1.0
0.0

i want to increase the precision upto 4 atleast.

A: Use
x = ((double) w[i]) / l[i];

As it is, you're dividing two integers using integer division, and assigning the resulting int to a double. Casting one of the operands to a double makes it do a double division instead.

A: If you divide an int by another int you get an int not a double.  Try
x = (double) w[i] / l[i];

A: System.out.printf("%10.4f", x);

Mind, only BigDecimal has precise precision. Doubles are approximations.


Q: Show that the vector space of real functions is not finitely spanned Here's what I've come up with. Let $\mathcal B$ be a generating set of $\mathcal F(R)$. Let us assume that $\mathcal B$ is a finite set, thus: $\lt  \mathcal B \gt = \lt \{b_1, ..., b_n \}\gt, n \in N$. Let  $\mathcal f \in F(R).$ Thus: $\mathcal f = \alpha_1 b_1 + ... + \alpha_nb_n,$ where $ \alpha_1,..., \alpha_n \in R$ are not all zeroes.
If  $\mathcal F(R)$ is a vector space, so there can be a function  $\mathcal g \in F(R)$ such as  $\mathcal g \neq \lambda f, \lambda \in R$. Thus  $\mathcal f+g \in F(R)$  but  $\mathcal f+g \neq \alpha_1 b_1 + ... + \alpha_nb_n$. If is $\mathcal g$ is to belong to $ \lt \mathcal B \gt$ we must add a new vector to $\mathcal B$.
Repeating the above mentioned procedure, we can find a function $\mathcal g\in F(R)$ such as $\mathcal h \neq \mathcal\lambda g$. Thus, we can find infinite functions and thus need infinite base vectors.
Is this proof right?

A: I think I understand the spirit of your proof, but it doesn't seem rigorous.
What you are trying to prove is equivalent to saying that $\mathcal{F}(R)$ is an infinite-dimensional vector space (if $\mathcal{F}(R)$ were finite dimensional, any basis would be a finite spanning set). Therefore if we could display an infinite collection of linearly independent vectors, we'd be done.
Can you show that the set $\{1, x, x^2, \dots \}$ is linearly independent?

A: Here is a pretty silly proof:
Let $S$ be any infinite set, and let $F(S, \mathbb{R})$ be the $\mathbb{R}$-vector space of functions $S \to \mathbb{R}$. Furthermore, let $\mathbb{R}_d [x]$ denote the $\mathbb{R}$-vector space of polynomials in $x$ of degree $\le d$.
Suppose $f_1, \cdots, f_n \in F(S, \mathbb{R})$ is a finite basis.
Choose some $f \in F(S, \mathbb{R})$ that takes on infinitely many values. For each polynomial $p \in \mathbb{R}_d [x]$, we may write $p(f)$ uniquely in the form $\sum_{i=1}^{n} a_i f_i$ for some real scalars $a_i$. Hence, we get a linear map $\mathbb{R}_d [x] \to \mathbb{R}^n$ given by $$p \mapsto (a_1, \cdots, a_n).$$ In fact, this map is injective, since $p(f) = 0$ implies $p = 0$, given as a polynomial may have only finitely many roots.
Thus, $\dim(\mathbb{R}_d [x]) \le n$ for all $d$; taking $d\to\infty$ gives a contradiction.


Q: Can the models.py file created by Django be used by another python file to fill in a database? I have followed the tutorial (parts 1 and 2) on the Django site (https://docs.djangoproject.com/en/1.4/intro/tutorial01/) and have managed to create a couple folders and to connect to my website. My app is called 'app', so my folder structure looks a bit like:

*

*mainFolder

*---__init__.py

*---test.py

*---djangoSite (created by Django)

*------ manage.py

*------ djangosite

*--------- other .py files

*------ app

*----------__init__.py

*--------- models.py

*--------- other .py files

I changed the models.py file to be something like:
class Result(models.Model):
    options = models.CharField(max_length = 1000, unique = False)
    reverse = models.DecimalField(decimal_places = 6, max_digits = 12)

test.py currently runs a couple tests on some other classes. What I want is for my test.py class to run these tests and save the results in a database (in columns
and reverse). I was hoping to do something like this in my test.py class:
import models.py
if __name__ == "__main__":
    optionResult = someTestsThatRuns
    reverseResult = someOtherTestThatRuns
    models.Result c;
    c.options = optionResult
    c.reverse = reverseResult

I'd like for the last two lines to save the result in the database.
Is this possible? How would I import the models.py from the app folder?
Thank you
EDIT:
When I say someTestsThatRuns, these aren't unit tests. They are practically a function that returns a list and some strings with either 'PASS' or 'FAIL'. Sorry for the confusion

A: Create an empty __init__.py file in the app folder so Python treats the directory as a package. Then do:
from app.models import Result

optionResult = someTestsThatRuns
reverseResult = someOtherTestThatRuns
c = Result()
c.options = optionResult
c.reverse = reverseResult
c.save()

That will save 'c' to the database.
Note that Django's test suite can create its own test database, which runs tests on a separate database. You can read more about Django testing here.
https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs

A: FIXED As David mentioned in the comments, the environment variable was indeed not set. Since I was in Windows, what I had to do was Start -> Computer -> Properties -> advanced System Settings -> Environment Variables -> add Environment Variable.
There I added 'DJANGO_SETTINGS_MODULE' and its location as 'C:\path\to\your\settings.py' Afterwards, in command prompt, I had to do the following:
enter python
>import sys
>import os
>sys.path.append(r"C:\location\to\settings.py")
>from django.core.management import setup_environ
>setup_environ(settings)
>sys.path.append(os.getcwd() + '\\from\\current\\to\\models.py'
>from models import Result

This is all explained at http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ , though I did find it somewhat difficult to understand. Another problem I had with importing my models is that there were TWO folders named exactly the same (djangoSite), so when importing, the computer had some issues trying to figure out which one. I had to rename, remove, reset environment variable and recheck all of the paths I have throughout my files =/
I am sorry if my explanations aren't the best, I barely understood what I did, but I do hope this will help other in the future


Q: Will using the dedicated graphics card improve performance? I have a HP 1000-1205TX Notebook PC which has a Intel® Core™ i3-2328M Processor and AMD Radeon HD 7450M (1 GB DDR3 dedicated) graphics card. The processor also has integrated graphics.
I am running linux and having some problems with getting the dedicated card to work well with two monitors. So before I spend time on getting that to work, I would like to know what kind of impact it would have on the performance of the laptop. I don't play any games with high graphics needs. I use mostly Firefox, Chrome browsers, and Eclipse IDE and sometimes play games like Wesnoth and Nexuiz.
So will switching to the dedicated graphics card give any performance improvements? Does a dedicated graphics card use the CPU and RAM? If this is the case, will it reduce the CPU power/RAM available for other programs?


Q: Integration class Hey everybody here is my code:
package Chapter5;

import java.util.Scanner;

public class MainMenu extends Integration
{

static Scanner s = new Scanner(System.in);
static int c;
static double lower, upper;
static double Curves;
static double sum = 0;

public static void main(String[] args)
{

    while(true)
    {
        System.out.println("Please choose one of the options");
        System.out.println("1: Calculate the area between two curves");
        System.out.println("2: Calculate the volume when two curves are revolved about a disk");
        System.out.println("3: Calculate the volume when a single curve is revolved about a shell");
        System.out.println("4: Quit");
        c = s.nextInt();
        if(c == 1)
        {
            System.out.println("Area between two curves");
            System.out.println("Please enter the lower limit");
            lower = s.nextInt();
            System.out.println("Please enter the upper limit");
            upper = s.nextInt();
            System.out.print("Lower limit: " + lower);
            System.out.println("  Upper limit: " + upper);
            System.out.println("The area under the f curve: " + sumf);
            System.out.println("The area under the g curve: " + sumg);
            sum = sumf - sumg;
            System.out.println("Area between the two curves = " + sum);
        }
        if(c == 2)
        {
            System.out.println("Working");
        }
        if(c == 3)
        {
            System.out.println("Working");
        }
        if(c == 4)
        {
            break;

        }
    }
}

Here is my Integration class:
   package Chapter5;

   /*Author: Cory Zander
   * Purpose: Find the area and volume between two curves
   */
   public class Integration
   {

static double x;
static double dx;
static double f, g;
static double sumg = 0;
static double sumf = 0;
public static double f(double x)
{
    f = x * Math.exp(x);
    return x;

}
public static double g(double x)
{
    g = Math.pow(x, 2);
    return x;

}

public static double Areaf(double lower, double upper)
{
    int i;
    x = lower;
    dx = (upper - lower)/2000;
    for(i = 0; i <= 2000; i++)
    {
        if(i == 0 || i == 2000)
        {
            sumf += f;
        }
        else
        {
            sumf += 2 * f;
        }
        x += dx;

    }
    sumf *= dx/2;
    return sumf;

}
public static double Areag(double lower, double upper)
{
    int i;
    x = lower;
    dx = (upper - lower)/2000;
    for(i = 0; i <= 2000; i++)
    {
        if(i == 0 || i == 2000)
        {
            sumg += g;
        }
        else
        {
            sumg += 2 * g;
        }
        x += dx;

    }
    sumg *= dx/2;
    return sumg;
}

Okay I just edited this and fixed the areaf and areag issue, but for some reason when I get the area under the f curve I still get 0. Why is it not taking the sumf from the Integration class

A: public static void main(String[] args){
    if (c == 1){
        //...
        double area1 = Integration.Areaf(lower, upper);
        double area2 = Integration.Areag(lower, upper);
        sum = area1 - area2;//sum and minus used?
        System.out.println("Area between the two curves = " + sum);
   }
}

Also you used inheritance incorrectly cause all your methods in base class (Integration) are static. You can simply delete extends clause from sub class or adjust it in correct way.


Q: create value to a model from another model's method I'm trying to create a new table (Payslip model) that will contain the computed salary on an employee in a cutoff.
I want Payslip.salary to get value from  Employee.compute_pay()
Given the example in the url link above, what should my views.py look like?
Is this the best approach to this kind of process? or Is there any library that can help with what I want to do here?
https://imgur.com/a/wVG5qrd
model.py
class Employee(models.Model):
    name = models.CharField(max_length=20)
    rate = models.IntegerField()
    absent = models.IntegerField()
    def __str__(self):
        return self.name
    def compute_pay(self):
        daily = rate / 20
        return rate - (daily*absent)

class Payslip(models.Model):
    name = models.CharField(max_length=20)
    salary = models.IntegerField()
    def __str__(self):
        return self.name

views.py
def compute(request):
    if request.method == "POST":
        return render(request,'payroll/compute/compute.html')

A: I do not think there is a need for another model Payslip, also you have no ForeignKey connections between the two models for it to work.
Considering your requirement, property decorator should work. Read up on how @property works. Basically, it acts as a pseudo model field, keep in mind the value of this field is not stored anywhere in the database, but it is tailor-made for situations like this where the field changes based on other fields and is needed for read-only.
Try this
class Employee(models.Model):
    name = models.CharField(max_length=20)
    rate = models.IntegerField()
    absent = models.IntegerField()

    def __str__(self):
        return self.name

    @property
    def compute_pay(self):
        daily = self.rate / 20
        return (self.rate - (daily*self.absent))

you can get the employee's salary by Employee.compute_pay just like any other model field


Q: How to query classes with edges in orient Db?
My problem is, how can I query “Chat”  table to retrieve person’s details in Profile Table.
ParticipatinIn edge started from Person to chat.
HasProfile Edge came started person to Profile.
Please Help me to solve this..
Thank You

A: I have used this structure

You can use a query like this :
select name, person.name, person.out("hasProfile").name as profile from (select name, in('ParticipatinIn') as person from Chat unwind person) unwind profile

If you use traverse, if a person is a part of two different Chat, you got that person only one time.
Hope it helps.

A: With this schema:

Try this:
select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile

This is the output:

If you don't like see the bracket you can use the unwind command:
select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile unwind Person,Chat

This is the output:

UPDATE
select name, in('ParticipatingIn').name as  Person, in('ParticipatingIn').out('HasProfile').name as Profile from Chat

UPDATE 2
traverse * from Chat

Hope it helps
Regards.


Q: Split Strtotime('now') to seconds and minutes I am developing a browser game where the player gets hospitalized for 30 minutes when his health becomes 0. I am using strtotime to check how much time is left until he gets out of the hospital.

<?php
$current_time = strtotime('now') + 1800; // This variable goes to the database
// The player gets hospitalized for 30 minutes, that's 1800 seconds.

// Updating the database ...
$sql = "UPDATE playerstats SET hospitalized='1', hospitaltimer=$current_time WHERE id = $id";
?>

Now let's say the player is in the page where it says he has to wait ?? minutes ?? seconds until he gets out of the hospital.

<?php
// Getting the timer from the database ...
global $db;
$sql = "SELECT * FROM playerstats WHERE id=$id";
$stmt = $db->query($sql);
$result = $stmt->fetchAll();

$timer = $result[0]['hospitaltimer'];
// substracting strtotime('now') from the timer to see how many seconds are left
// until the player is released from the hospital

$timer = $timer - strtotime('now');
// Lets just say that 2 minutes have passed, the $timer should now be with a result
// like 1680 or something,

?>

My question is, how to split that timer to minutes and seconds? I want to split the 1680 seconds that remain to minutes and seconds. Thanks anyways.

A: Since you're storing hospitaltimer as seconds from the unix epoch, substracting both strtotime figures would then be converted to a date that's, for example, 1680 seconds after the unix epoch. Not what you're looking for.
I'd suggest approaching this by storing the "exit time" in yyyy-mm-dd format
a.- You'd need to alter your table and convert hospitaltimer to a DATETIME field. that's pretty straight-forward
b.- change your code to store the hospitaltimer value as a yyyy-mm-dd hh:mm:ss like this:
$current_time = date('Y-m-d H:i:s', strtotime('now') + 1800); // This variable goes to the database
and then change the logic to show the remaining time:
$timer = date_create($result[0]['hospitaltimer']); // the "exit time" you inserted
$now = date_create(date('Y-m-d H:i:s'));

$diff = date_diff($timer,$now)->format('%r%i minutes %s seconds');

if ($diff < 0)
{
    echo "out";
}

else
{
    echo $diff." before being able to leave";
}

Alternatively, substracting the output of different strtotime() operations would be a non-standard way to calculate dates which you could work around by:
$timer = $timer - strtotime('now');
// now the timer reads 1680 per your example

$seconds = $timer % 60; // use modulo 60 to calculate seconds remaining after dividing seconds by 60 and retrieving the integer part of the result

$minutes = ($timer - $seconds) / 60; // from full timer, substract the seconds and the remaining amount, divided by 60 is converted to minutes

Both of these alternatives would work, but the benefit of storing the hospitaltimer as a timestamp is that at any given point you could easily query the table to find out how many users are still hospitalized (for example) by simply using a where hospitaltimer > now()


Q: Vim AutoComplPop issues? I need auto-completion in vim for programming languages, for that I downloaded the AutoComplPop
followed the instructions mentioned there and copied the files cp -r
Downloads/ns9tks-vim-l9-3bb534a720fa/plugin/*
Downloads/ns9tks-vim-l9-3bb534a720fa/doc/*
Downloads/ns9tks-vim-l9-3bb534a720fa/autoload/*

to the vim directories
/usr/share/vim/vim74/plugin/
/usr/share/vim/vim74/autoload/
/usr/share/vim/vim74/doc/

It gave the error about L9 : Vim-script library, downloaded from here   and did the same with these files copied its file to the vim respective directories when I copied the autoload directory content of the L9 library there was sub directory named l9 when it goes there in vim autoload directory it gave the permissions problem so I changed its permissions to chmod 644, now it doesn't give the L9 Library error but when I edit a file
vim hello.html

it gives the errors when I press i to insert and keep giving the errors if I type anything.
Error detected while processing function <SNR>9_feedPopup..<SNR>9_finishPopup:
line    4:
E117: Unknown function: l9#tempvariables#end

Press ENTER or type command to continue

and surely auto-complete doesn't work !
Help !

A: i used this method to install this plugin and it worked perfectly :

*

*download the latest version of the plugin fron here http://www.vim.org/scripts/script.php?script_id=1879

*create the folder "~/.vim" with the command "mkdir ~/.vim".

*extract the contained of your downloaded file (the first step) (you will have a new folder called "vim-autocomplpop" when you finish the extraction)

*copy all the contained of the folder "vim-autocomplpop" into the folder "~/.vim" with the command "cp -r /path/to/vim-autocomplpop/* ~/.vim/".

*add the lines of this website in your ".vimrc" file http://fr.openclassrooms.com/forum/sujet/vim-autocompletion-avec-tab

*open vim now and you'll see that it works like magic.

A: you just have to create another .vimrc file with this command "touch ~/.vimrc", then all what you have to do is to put this lines in it with a text editor, then you just have to do what i told you to do in the firs message(except for the 4th step because i already included those lines in this answer)
runtime! debian.vim
if has("syntax")
  syntax on
endif
set background=dark
set showcmd     " Show (partial) command in status line.
set ignorecase      " Do case insensitive matching
set autowrite       " Automatically save before commands like :next and :make
set mouse=a     " Enable mouse usage (all modes)
set ts=4
set number
set lbr

set smartindent
set shiftwidth=4

autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete
highlight PmenuSel ctermfg=0 ctermbg=7 guibg=Grey

" Source a global configuration file if available
if filereadable("/etc/vim/vimrc.local")
  source /etc/vim/vimrc.local
endif

A: Did you make the same chmod changes to the files inside that autoload/l9 directory?
So you are talking about two plugins by the same author:
AutoComplPop 2.14.1 http://www.vim.org/scripts/script.php?script_id=1879
L9           1.1    http://www.vim.org/scripts/script.php?script_id=3252
Your text says you installed them both. I installed them both and they seem to work OK. Please double check they are installed properly. The error you are getting talks about not finding autoload/l9/tempvariables.vim line #46 where there's an end function.
If the permissions on the files in that autoload/l9 directory don't allow you to get to the proper function it seems like that would be the error it would give.


Q: A regular space which is not completely regular: Mysior's example. In this paper https://www.ams.org/journals/proc/1981-081-04/S0002-9939-1981-0601748-4/S0002-9939-1981-0601748-4.pdf, Mysior gives a example of a regular space which is not completely regular, but I didn't understand the construction of space (X). Is there any easier way to visualize, such as a picture?

A: The description is quite simple (it's two paragraphs); the set of points is just $\{(x,y)\in \Bbb R^2\mid y \ge 0\} \cup \{a\}$, where $a$ is some point outside the plane (sort of infinity, one could say).
All points in the plane part with $y>0$ are isolated (so lots of scattered dust there) and the "glue" is provided by points of the form $(x,0)$. A basic neighbourhood of $(x,0)$ is of the form
$$U((x,0),F) = \{(x,0)\} \cup \left( I_x:=\{(x,y)\mid 0 \le y < 2\} \cup I'_x:=\{(x,x+y)\mid 0 \le y < 2\right) \setminus F$$
where $F \subseteq I_x\cup I'_x$ is finite. $I_x$ is a fixed length vertical open-ended line segment emanating from $(x,0)$ and $I'_x$ is an angle-45-degrees open-ended line segment  emanating from $(x,0)$ to the right side. The substracted finite set is just to ensure that the space will be Hausdorff as otherwise we could not separate $(x,0)$ from $(x,1)$ by open sets and now we can, by using $F=\{(x,1)\}\subseteq I_x$ e.g.
A basic neighbourhood of $a$ looks like $U_n(a)= \{a\} \cup \{(x,y)\mid y \ge 0, x > n\}$ where $n$ varies over $\Bbb N$ (so $a$ lies "to the right" of the half plane.
All this is nice and consistent (e.g. all $U_n(a)$ consist of interior points only when we consider the points in it, and likewise for the sets $U((x,0),F)$) so in total this defines all open sets in the usual way.
So visually it's not that hard: scattered upper plane points that can be in two-pronged open sets for the axis points and one infinity point on the right.
Hope this helps a little bit.


Q: Quarkus and JDBI integration: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] I'm trying to use Quarkus and JDBI — not so many examples on this out there I would say :/
The Gradle script has these dependencies:
dependencies {
  implementation(enforcedPlatform("io.quarkus:quarkus-universe-bom:2.1.3.Final"))
  implementation(enforcedPlatform("org.jdbi:jdbi3-bom:3.21.0"))

  implementation("org.jdbi:jdbi3-core")
  implementation("org.jdbi:jdbi3-sqlobject")

  runtimeOnly("io.quarkus:quarkus-config-yaml")
  runtimeOnly("io.quarkus:quarkus-flyway")
  runtimeOnly("io.quarkus:quarkus-jdbc-h2")
  ...
}

I have a class to configure (and integrate) JDBI:
@ApplicationScoped
public class PersistenceConfig {
  @Inject
  DataSource dataSource;

  @Singleton
  public Jdbi jdbi() {
    return Jdbi.create(dataSource)
        .installPlugin(new SqlObjectPlugin());
  }

  @Produces
  public ActorRepository actorRepository(final Jdbi jdbi) {
    return jdbi.onDemand(ActorRepository.class);
  }
}

And I think the problem is somehow within that one (and the datasource), because I'm currently getting this error when starting the application:
2021-08-27 11:31:32,852 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

    at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:415)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:275)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:66)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.firstStart(IsolatedDevModeMain.java:91)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:424)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:64)
    at io.quarkus.bootstrap.app.CuratedApplication.runInCl(CuratedApplication.java:136)
    at io.quarkus.bootstrap.app.CuratedApplication.runInAugmentClassLoader(CuratedApplication.java:93)
    at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:145)
    at io.quarkus.deployment.dev.DevModeMain.main(DevModeMain.java:63)
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors

    [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

    at io.quarkus.builder.Execution.run(Execution.java:116)
    at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79)
    at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:151)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:413)
    ... 9 more
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

I can't fully comprehend why the datasource cannot be injected since I already have it configured in the YAML file:
quarkus:
  datasource:
    db-kind: "h2"
    jdbc:
      url: "jdbc:h2:mem:java_quarkus_graphql;DB_CLOSE_DELAY=-1;MODE=PostgreSQL"
    username: "sa"
  flyway:
    clean-disabled: true
    locations: "classpath:database/migration"
    migrate-at-start: true
    validate-on-migrate: true

I read the guide around this subject and it should be available as AgroalDataSource — or just DataSource.

UPDATE #1
By the way, this setup/configuration works if I use an older version (1.13.4.Final) of Quarkus:
> Task :quarkusDev
Listening for transport dt_socket at address: 5005
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2021-08-27 12:55:39,840 |- INFO  in io.quarkus:88 [Quarkus Main Thread] - java-quarkus-graphql 0.1.2-SNAPSHOT on JVM (powered by Quarkus 1.13.4.Final) started in 0.770s. Listening on: http://localhost:8080
2021-08-27 12:55:39,843 |- INFO  in io.quarkus:91 [Quarkus Main Thread] - Profile dev activated. Live Coding activated.
2021-08-27 12:55:39,843 |- INFO  in io.quarkus:92 [Quarkus Main Thread] - Installed features: [agroal, cdi, config-yaml, flyway, hibernate-validator, jdbc-h2, mutiny, narayana-jta, smallrye-context-propagation, smallrye-graphql]

UPDATE #2
Version 2.2.1.Final doesn't have the issue when starting the application, but somehow it fails when running the test cases:
@Stereotype
@QuarkusTest
@Transactional
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface QuarkusTransactionalTest {
  // ...
}

@QuarkusTransactionalTest
final class ActorRepositoryTest {
  @Inject
  ActorRepository repository;

  @Test
  void findById_WhenActorDoesNotExist() {
    Assertions.assertThat(repository.findById(UUID.fromString("c6b1d415-77ee-49c2-b912-fbd00e07702b"))).isNotPresent();
  }

  @Test
  void findById_WhenActorExist() {
    Assertions.assertThat(repository.findById(UUID.fromString("3bea7318-bb7a-4232-9343-59579dd5b2a2")))
        .contains(ActorFactory.penelopeGuiness());
  }
}

ActorRepositoryTest > findById_WhenActorExist() FAILED
    java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
        [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
        - java member: org.acme.config.PersistenceConfig#dataSource
        - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
        at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1100)
        at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:265)
        at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
        at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
        at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
        at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
        at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
        at java.base/java.lang.Thread.run(Thread.java:829)
        at org.jboss.threads.JBossThread.run(JBossThread.java:501)
    Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
        - java member: org.acme.config.PersistenceConfig#dataSource
        - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
        at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
        at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:471)
        at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:253)
        ... 13 more

A: yes , it works with AgroalDataSource

A: Fixed with latest (2.2.3.Final) version.


Q: Sorting list with searched input string I am working on a Parse/Android application in which I am getting array list of objects from the server, for example Apple, Banana, Carrot, Dino etc which I am displaying in my Adapter.
Now I want to make a search thing on my list, if I press any alphabet it will show the items according to those characters, for example: if I press "A" so it will show me : Apple, Apricot etc and do not show any other.
My code is given below:
// mItems is my arraylist of objects with "title" object.
mItems = (ArrayList<ParseObject>) objects;
mAdapter = new GenericAdapter<ParseObject>(getApplicationContext(),
mItems,R.layout.listview_dical_assist,mNotificationsBinder);
mListView.setAdapter(mAdapter);

My autoComplete editField where I want to make that sorting list thing.
autoComplete.addTextChangedListener(new TextWatcher() {

              @Override
              public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

               // I need to put that search query here user press any character

               adapter.notifyDataSetChanged();
              }

              @Override
              public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                      int arg3) {
                  // TODO Auto-generated method stub

              }

              @Override
              public void afterTextChanged(Editable arg0) {
                  // TODO Auto-generated method stub

              }
          });


Q: help with solving a simple differential equation How do I solve this differential equation:
$(x-y)dy=(x+y+1)dx$
This is simple but I am unable to solve this can someone help me with this?

A: $$y'=\frac{x+y+1}{x-y}$$
Set $x=X-\frac 12$ and $y=Y-\frac 12$, we have
$$Y'=\frac{X+Y}{X-Y}=\frac{1+\frac{Y}{X}}{1-\frac{Y}{X}}$$
let $Y=UX$, therefore
$$U+XU'=\frac{1+U}{1-U}$$
$$XU'=\frac{1+U^2}{1-U}$$
$$\frac{1-U}{1+U^2}dU=\frac{dX}{X}$$
thus
$$\tan^{-1}U-\frac{1}{2}\ln(1+U^2)=c+\ln X$$
Now set $U=\frac{y+\frac 12}{x+\frac 12}$


Q: BigQuery Regex to extract string between two substrings From this example string:
{&q;somerandomtext&q;:{&q;Product&q;:{&q;TileID&q;:0,&q;Stockcode&q;:1234,&q;variant&q;:&q;genomics&q;,&q;available&q;:0"}

I'm trying to extract the Stockcode only.
REGEXP_REPLACE(col, r".*,&q;Stockcode&q;:/([^/$]*)\,&q;.*", r"\1")

So the result should be

1234

however my Regex still returns the entire contents.

A: use regexp_extract(col, r"&q;Stockcode&q;:([^/$]*?),&q;.*")
if applied to sample data in your question - output is


Q: cannot get opengraph to scape url I know this is a pretty common problem but any of the solutions I have tried (thats a lot) haven't worked.
I am trying to scrape http://residencyradio.com/ using https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fresidencyradio.com%2F
The site itself is getting a complete overhaul, this will be revealed next week and I want the relevant images, title and info to appear if someone links to the site, but instead at the moment these properties are being shown as they were the very first time the site was cached on FB (nearly a year ago).
As far as I can see, I have included all the relevant meta tags etc how they should be, I even tried implementing a like button on the site, but to no avail. I have followed what has been set out on: http://ogp.me/ and can't see anything wrong.
Here is a sippet of the page from !DOCTYPE to </head>:
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset=utf-8>
<title>The Residency</title>

<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
    </script>
<![endif]-->
<link href="css/reset.css" rel="stylesheet" type="text/css" />
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="icon" type="image/png" href="images/favicon.png" />

<!--Meta Data-->
<meta name="keywords" content="The Residency, M. Budden, Neal McClelland, Michael Budden, Radio, Residency Radio,
Residency, Global, House, Electro, Progressive, Tech, Techno, DnB, Drum and Base, Dubstep, iTunes, Belfast,
Northern Ireland, UK" />
<meta name="description" content="Brought to you by Neal McClelland and M. Budden, The Residency is a weekly global underground dance show" />
<meta property="og:title" content="The Residency A global underground dance show" />
<meta property="og:type" content="musician" />
<meta property="og:url" content="https://www.facebook.com/theresidency" />
<meta property="og:image" content="https://www.residencyradio.com/images/Residency_logo_circle.png" />
<meta property="og:site_name" content="The Residency" />
<meta property="fb:admins" content="1324839758" />

Any help would be greatly appreciated, as I've been scratching my head for a few days trying to figure it out!
Thanks in advance!

A: This is a guess, but your html is not valid and maybe because of that the facebook scraper fail to parse and extract the data from it.
I haven't went through all of it, but you don't seem to close all tags.
For example the description and keywords meta tags don't end with "/>" or ">".

Edit
Screen capture of what the debugger shows when I load your html from my server:


Q: Is there a nice way to tell jQuery to not eval scripts on ajax requests that are HTML I'm using jQuery to make an ajax request, and everything is working as expected.  But it's evaluating the scripts in the wrong context.
I have an iframe (same domain, no worries here), and I'm trying to get the scripts to eval in the context of the iframe, instead of where the ajax request was made -- eg. a different frame.
I figured I could tell ajax not to eval the scripts, and I would do the work myself to eval them in the right context.  Any ideas, or ways to disabled the automatic eval?
Edit
So, I was somewhat wrong about the initial question.. The scripts are not evaluated when loaded, but rather when the content is being placed in the document.  You can see this by testing the example:
$('#some_element').html('content');

Now, when doing this from a different frame, the evaluation happens in the scope of where you're calling, not the element you're inserting content into.
I ended up setting the content without using jQuery, and then finding/evaling any script tags:
element.get(0).innerHTML = data;
element.find('script').each(function() {
  otherWindow.eval(this.innerText);
});

Final Update
I ended up tracking it down to the source, and overriding it from there.. the following is coffeescript, but you can get the idea.  I chose to override it because for my usage, this should never happen in the top window, but is expected in the iframe content.
    $.globalEval = (data) -> (iframeWindow.execScript || (data) -> iframeWindow["eval"].call(iframeWindow, data))(data) if (data && /\S/.test(data))

A: This questions shows how to do custom eval of the scripts:
jQuery: Evaluate script in ajax response
In the following piece of code...  ** this code is from the answer of the other question ** just got it as a snippet:
  $("body").append($(xml).find("html-to-insert").eq(0));
  eval($(xml).find("script").text());

eval itself is bound to a window, that you can define to be the context:
windowObject.eval - when calling just eval('...'), it supposes you are calling just like this: window.eval('...')
Now you need to get the window that corresponds to the frame you want to execute the eval in and do something like this:
myIFrameWindow.eval('...')
When you do this, it is execute in the context of that window. It is just a matter of finding the window associated with the iframe that you want now.
To find the window of a given frame, take a look at this post:
Getting IFRAME Window (And Then Document) References With contentWindow


Q: Ignore adapter creation when adaptee already of correct type I have the following setup:
class Target(Base):

  def __init__(name: str):
    self.name = name

class Adapter(Target):

  def __init__(self, adaptee: Base, name: str):
    super().__init__(name=name)
    self.adaptee = adaptee

def as_target(adaptee: Base, name: str):
  if isinstance(adaptee, Target):
    return adaptee
  else:
    return Adapter(adaptee, name)

I am wondering if I could get rid of as_target function and instead handle the logic on adapter creation.
Semantically, it would have the following meaning:
class Adapter(Target):

  def __init__(self, adaptee: Base, name: str):
    if isinstance(adaptee, Target):
      self = adaptee
    else:
      super().__init__(name=name)
      self.adaptee = adaptee

I've tried playing around with overriding __new__ but I wasn't able to make it work.

A: class Base:
    pass

class Target(Base):
    def __init__(self, name: str):
        self.name = name

    def __repr__(self):
        return "{}({})".format(type(self).__name__, repr(self.name))

class Adapter(Target):
    def __new__(cls, adaptee: Base, name: str):
        if isinstance(adaptee, Target):
            return adaptee
        else:
            return super().__new__(cls)

    def __init__(self, adaptee: Base, name: str):
        super().__init__(name=name)
        self.adaptee = adaptee

print(Adapter(Base(), "a"))  # Adapter('a')
print(Adapter(Target("b"), "c"))  # Target('b')


Q: Generate Permutations - Swap Function I'm going thru the EPI book and adapting the solutions in Go. I don't understand the solution for "generating permutations". Below is my implementation in Go (which works correctly):
    func permutations(A []int) [][]int {
    result := [][]int{}
    var directedPermutations func(i int)
    directedPermutations = func(i int) {
        if i == len(A)-1 {
            B := make([]int, len(A))
            copy(B, A)
            result = append(result, B)
            return
        }
        for j := i; j < len(A); j++ {
            A[i], A[j] = A[j], A[i]
            directedPermutations(i + 1)
            A[i], A[j] = A[j], A[i]
        }
    }
    directedPermutations(0)
    return result
}

Below is the result:
16.3_generate_permutations$  go run main.go
input:  [1 2 3]
[[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]

Specifically, I'm confused as to why the values are swapped before and after the recursive case. I've stepped thru with a debugger and see that for each successive call values are swapped to generate the permutation.
Is the swap before recursive case and swap back afterwards a common pattern?


Q: Only insert new rows in SQLIte with pandas to_sql() I've got a dataframe in Pandas and I want to export the dataframe to sqlite with the pandas function to_sql(), the problem I've got is that function only admit remplace or append values, and I can not export just by inserting new rows.
to_sql() function:
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’

How to behave if the table already exists.

    fail: Raise a ValueError.
    replace: Drop the table before inserting new values.
    append: Insert new values to the existing table.

Is there an option to do that?


Q: Update React [Native] View on Day Change I'm working on a React Native component that should update itself when the day changes, even when the user hasn't interacted with the view.
Is setInterval the only way to deal with this? If I call setTimeout in viewDidLoad specifying the number of ms until the next day, won't the interval be inaccurate if the app gets paused? Alternatively, I could run a periodic timer, but I'd need to give it a short interval so that there's not an apparent delay when the day changes -- seems pretty inefficient.
Am I missing something?

A: I suppose this is more of a general app architectural concern. The simplest answer is you should take the current time in seconds (new Date().getTime()), determine how many seconds there are until the next day, and set a timer for that number.
However, as you mentioned, once the app is killed, that timer will no longer be accurate.
You should use AppStateIOS to listen for when the app is backgrounded and foregrounded. Upon being sent to the background, clear the timer. Upon being brought to the foreground, run the original calculation again and generate a new timer.
Unfortunately there is no equivalent functionality on Android as of yet.

A: You can use react-native-midnight which subscribes to native APIs and fires event listeners when the day has changed from either a timezone change or crossing the midnight threshold.


Q: Error messages are not displayed using jQuery Validate I have the following jQuery script.
function updateItem(form) {
    var validator = $("#add-experience-form").validate({
        debug: true,
        rules: {
            eventTitle: {
                required: true
            }
        },
        messages: {
            eventTitle: {
                required: "Please, enter a title."
            }
        }
    });

    if (!validator.valid()) {
        return;
    }

}
Here's the HTML:
<form action="/User/AddExperience" id="add-experience-form" method="post" novalidate="novalidate">

        Experience Title*
        <input id="eventTitle" name="eventTitle" required="required" style="width: 350px;" type="text" value="">

         50 character maximum

                    {

                        Experience Title

                        @*@
                         50 character maximum

For some reason error message doesn't display for the above form even though validator.valid() evaluates to false.
If it helps, I put this form inside jQuery UI dialog, but I don't think it really matters.
Any ideas?

A: To validate html forms , the simplest way is to combine two open source powerful frameworks twitter bootstrap ( to get nice form ) and jquery.validate.js plugin ( for validation ).
Bootstrap framework : http://getbootstrap.com/getting-started/ .
Jquery validation plugin : http://jqueryvalidation.org/
So your html code and your script may appear like this
Html code :
First add this link
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">

Then
<form  method="post" action="/User/AddExperience" id="add-experience-form" class="form-horizontal">
    <fieldset>

fields required *

            Experience Title*

              <input type="text" class="form-control" id="eventTitle" name="eventTitle">

                <input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">

    </fieldset>

</form>

Jquery script : put it in a js file called validate.js
$(document).ready(function(){

jQuery.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-z]+$/i.test(value);
});

$('#add-experience-form').validate({
    rules: {
        eventTitle: {
            minlength: 2,
            lettersonly:true,
            required: true
        }
    },

    messages: {

        eventTitle: {
            required:"blablabla",
            minlenght:"blablabla",
            maxlenght:"50 character maximum",
            lettersonly: "Letters only please"
        }
    },

    highlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('error').addClass('success');
    },
    success: function (label) {
        $(label).closest('form').find('.valid').removeClass("invalid");
    },
    errorPlacement: function (error, element) {
        element.closest('.control-group').find('.help-block').html(error.text());
    }
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file

});
You can put all these scripts in one folder called js then add them in your code

For more details you can refer to the documentation http://jqueryvalidation.org/documentation/


Q: How to redirect from one servlet to another by using tricky redirection? If I have two servlets:
@WebServlet (urlPatterns = {"/s1"})
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 100);
        map.put("B", 200);
        map.put("C", 300);

        req.setAttribute("map", map);
        getServletContext().getRequestDispatcher("Servlet2").forward(req, resp);
    }
}

public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        Map map = (Map) req.getAttribute("map");

        for (Object o : map.values()) {
            System.out.println(o);
        }
    }
}

How can I make redirect between them? And which path I need to use in my getRequestDispatcher method? And one more condition - Servlet2 must be without any mapping in annotations or in web.xml.

A:
Servlet2 must be without any mapping in annotations or in web.xml.

Then you cannot use HttpServletRequest#getRequestDispatcher(String), which is a container managed method that checks those mappings.
That condition is ridiculous and makes no sense. If you aren't going to use the Servlet container, don't make a Servlet. Make a service class that performs the actions you need. You don't need to make everything a Servlet.
Your only (ridiculous) alternative is to instantiate Servlet2 and explicitly invoke its doGet method.


Q: Как сделать кнопку отправки формы Как сделать на сайте такую кнопку: нажимаешь - всплывающее окно появляется, и там будут формы.


Q: Unable to access rclone mount in Powershell I've mounted my server using SFTP (as F: drive) on Windows 10, but Powershell can't access the drive and as a result I must open all files via Windows Explorer which loads extremely slowly.
When running cd F:\:
cd : Cannot find drive. A drive with the name 'F' does not exist.
At line:1 char:1
+ cd F:\
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (F:String) [Set-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand