text:
Q: Jquery ajax call removing script tag Im using jquery to call a page via ajax. I have some jquery functions that load inside the returned html from the page being called from ajax. The problem is Im trying to include the js file inside the returned data, it gives back the html but seems to strip the script tag:
    function buildDisplayResults()
    {
         $.ajax({
             method: 'get',
             cache: false,
             url : '/display_results.php',
             dataType : 'text',
             success: function (text) { $('#showresults').html(text); }
         });

    }

The returned data I have
That script code above always gets stripped out, but I need it in the returned data so the functions work inside the data the ajax call sends back. Any ideas?

A: As far as I can tell, it should work; it must be something else in your environment or in the markup you're fetching. I've tested it and have it working on IE6, IE7, IE8, Chrome 9 on Linux and Windows, Firefox 3.6 on Linux and Windows, and Opera 11 on Linux and Windows; all using jQuery 1.5:
Ajax call on main example page:
$.ajax({
  url: "/okuli4/3",
  dataType: "text",
  method: "get",
  cache: false,
  success: function(data) {
    $('#target').html(data);
  },
  error: function(xhr, status, err) {
    $("
Error: Status = " + status + ", err = " + err + "
")
      .appendTo(document.body);
  }
});

...where the /okuli4/3 resource looks like this:

I'm the snippet.

I'm the snippet after.

...where the /etobe4/2 resource looks like this:
jQuery("
I was added by the external script file.
").appendTo(document.body);

Live example


text:
Q: Simulations with MonteCarlo and Autoregressive methods I am trying to find the best-fit trend for my data. Here I just generated it but let's say I don't know my data trend at all.
test = RandomVariate[NormalDistribution[100, 10], 100];
data = TemporalData[test];
proc = EstimatedProcess[data, ARMAProcess[3, 3]];
forecast = TimeSeriesForecast[proc, data, {5}, Method -> Automatic]
sims = RandomFunction[proc, {0, 10^2}, 4];
ListLinePlot[Join[data["Paths"], sims["Paths"]],
PlotStyle -> {Directive[Thick, ColorData[1, 1]], ColorData[10, 1],
ColorData[10, 2], ColorData[10, 3], ColorData[12, 4]},
PlotLegends -> {"data", "Simulations"}, ImageSize -> 550]

As results of the fit shows, neither of AutoRegressive methods of Mathematica are being fitted to my data. How can I use the Euler-Maruyama method mentioned here and disscuded here for fitting my data and have the fitness test data for it? How can I also do the Monte Carlo simulations for them and show upper, lower bound and mean of simulations on my data?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve properties and their descriptions from instances of the same class I want to retrieve all distinct object properties of instances with the same type (class), starting with two initial seeds (wd:Q963 and wd:Q42320). First, I ask for the type (and maybe subtype) of such seeds. Second, all instances of the same class of the seeds are retrieved. Third, properties of the instances are retrieved. Finally, I want to retrieve descriptions of such properties and if possible alternative labels. My query is as follows:
select distinct ?property ?description ?label where{
  {
    wd:Q963 wdt:P31 ?typesSubject .
    ?instancesS (wdt:P31|wdt:P279) ?typesSubject .
    ?instancesS ?property ?unknown .
  }
 UNION
  {
    wd:Q42320 wdt:P31 ?typesObject .
    ?instancesO (wdt:P31|wdt:P279) ?typesObject .
    ?unknown ?property ?instancesO .
  }

 ?claimPredicate wikibase:directClaim ?property .
 ?claimPredicate schema:description ?description .
 ?claimPredicate rdfs:label ?label .

   FILTER(strstarts(str(?property),str(wdt:)))
   FILTER(strstarts(str(?unknown),str(wd:)))

   FILTER(LANG(?description) = "en").
   FILTER(LANG(?label) = "en").

}

The problem is that my actual query takes a lot of time and it fails in the public Wikidata endpoint. Does anyone can provide me some hints to optimize such a query?

A: To be honest, I can't understand the aim of your query. I suppose you are interested in semantic similarity or something like.
Basically, you could reduce the number of joins, retrieving only unique wdt-predicates with nested SELECT DITINCT.
SELECT ?property ?claimPredicateLabel ?claimPredicateDescription
WHERE {
  hint:Query hint:optimizer "None" .
  {
  SELECT DISTINCT ?property {
    VALUES (?s) {(wd:Q963) (wd:Q42320)}
    ?s wdt:P31/^(wdt:P31|wdt:P279) ?instances .
    ?instances ?property ?unknown .
    }
  }
  ?claimPredicate wikibase:directClaim ?property .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
}

Try it!
This is fast enough (~ 3s)  even with SERVICE wikibase:label.
Also, you don't need FILTER(strstarts(str(?property),str(wdt:))) after ?claimPredicate wikibase:directClaim ?property.

As for hint:Query hint:optimizer "None", this hint forces Blazegraph to follow standard bottom-up evaluation order. In this particular query, hint:Query hint:optimizer "Runtime" or hint:SubQuery hint:runOnce true should also work.


text:
Q: Как запросить разрешение на работу на экране блокировки Android? Собственно, есть задача, запускать intent и показывать уведомление всплывающим сообщением даже если телефон заблокирован.
Удалось добиться запуска и корректной работы, если руками разрешить приложению работу на экране блокировку.
Теперь вот ищу, как можно программно запросить это разрешение?
Приложение корпоративное, сотрудники обязаны будут это разрешение принять. Но заставлять всех тащиться в настройки(а у всех они, естественно, в разных местах) ой как не хочется.


text:
Q: Laravel JSON response returns protected data return Response::json(array('status' => 'Group not found'));

returns protected data. Here's the JSON:
{"status":"Group not found"}
The following code
//$jsonData - the data returned above

var_dump($jsonData);

returns this:

object(Illuminate\Http\JsonResponse)#320 (10) {
  ["jsonOptions":protected]=> int(0) ["data":protected]=> string(28)
  "{"status":"Group not found"}" ["callback":protected]=> NULL
  ["encodingOptions":protected]=> int(15) ["headers"]=>
  object(Symfony\Component\HttpFoundation\ResponseHeaderBag)#317 (5) {
  ["computedCacheControl":protected]=> array(1) { ["no-cache"]=>
  bool(true) } ["cookies":protected]=> array(0) { }
  ["headerNames":protected]=> array(3) { ["cache-control"]=> string(13)
  "Cache-Control" ["content-type"]=> string(12) "Content-Type"
  ["date"]=> string(4) "Date" } ["headers":protected]=> array(3) {
  ["cache-control"]=> array(1) { [0]=> string(8) "no-cache" }
  ["content-type"]=> array(1) { [0]=> string(16) "application/json" }
  ["date"]=> array(1) { [0]=> string(29) "Tue, 17 Jun 2014 19:03:33 GMT"
  } } ["cacheControl":protected]=> array(0) { } }
  ["content":protected]=> string(28) "{"status":"Group not found"}"
  ["version":protected]=> string(3) "1.0" ["statusCode":protected]=>
  int(200) ["statusText":protected]=> string(2) "OK"
  ["charset":protected]=> NULL }

Take a look at ["data":protected]=> string(28) "{"status":"Group not found"}". The data is protected for some reason and doesn't appear when I decode the JSON. How do I "unprotect" it (make it publicly available)?

A: I don't think this is your issue.
If you look at the inheritance tree:
\Symfony\Component\HttpFoundation\Response
    \Symfony\Component\HttpFoundation\JsonResponse
        \Illuminate\Http\JsonResponse

The ancestor Response class has:
public function __toString()
{
    ...
    return ... . $this->getContent();
}

So we follow:
public function getContent()
{
    return $this->content;
}

It's okay that your data is stored inside member protected $content because when the JsonResponse object is cast to a string, PHP uses the return value of the __toString() method to be the string representation of that object.


text:
Q: Prevent keyboard from shrinking viewport In Firefox OS 1.3, when the keyboard slides in, then the browser's/app's viewport height is reduced.
Simple test page/app illustrating the issue:
<!doctype html>
<title>Test</title>

<input style="width: 100px" />

Is there some way to configure a Firefox OS web app not to shrink viewport height when the keyboard slides in?

A: No, there are plans to facilitate this from manifest file in the future. It will be opt-in though. The implementation bug is here: https://bugzilla.mozilla.org/show_bug.cgi?id=970093


text:
Q: How does PyPI decide what is the latest version of a package? I've recently uploaded an upgrade to a package I developed on PyPI, version 0.4.3. The next day I noticed a minor adjustment I forgot to add, and uploaded a new version, 0.4.3a0. Yet, PyPI kept marking the previous one as the latest version. What am I missing?

A: Using PEP 440, under which 0.4.3a0 is read as a pre-release (specifically, an alpha) of version 0.4.3.

Within a numeric release (1.0, 2.7.3), the following suffixes are permitted and MUST be ordered as shown:
.devN, aN, bN, rcN, <no suffix>, .postN

Consider using version 0.4.3post1 or just 0.4.4.


text:
Q: In tomcat force http connection to https I am trying to force a connection to http://localhost:8443 to https://localhost:8443.
The site works correctly if they go to https://localhost:8443. In case the user forgets the s in https I would like tomcat to correct it for them.
I only have one connector for https, defined as:
<Connector port="8443" rediretPort="8443"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    SSLEnabled="true"
    maxThreads="150"
    scheme="https"
    secure="true"
    clientAuth="false"
    sslProtocol="TLS"
    keyAlias="alias"
    keystoreFile="keystore.jks"
    keypass="PASSWORD"
/>

This is on a Windows server. Tomcat 6 is a standalone server (not connected to IIS).
I have tried to modify web.xml to include the following:
<security-constraint>
 <web-resource-collection>
    <web-resource-name>Protected Context</web-resource-name>
      <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>

This does not work for me. From what I have read, this would redirect a user from http://localhost:8080 to https://localhost:8443 (if the connector 8080 defined the redirectPort as 8443).
I am not sure this is even possible with a standalone Tomcat server. I know this is possible with apache mod_rewrite or some other similar solution, but I do not want to install any other service on the Windows machine.

A: when your first sentence is not a typo, just add a connector for http on port 8080 and add the redirect as you described. you can't have http and https listen on the same port. so let http listen on port 8080 and https on port 8443.


text:
Q: RabbitMQ Exclusive Queue Lost Messages For a consumer, when declaring a Queue to be 'exclusive', the Queue will be deleted when consumer disconnects per the documentation.
Assuming there are messages in the Queue awaiting processing and the consumer goes offline, all messages on this 'exclusive' Queue will be lost when Queue is removed.
Are there any strategies or ways to keep a Queue 'exclusive' but preserve the messages in the Queue/Broker so nothing is lost?
Thanks in advance.

A: Exclusive queue will be deleted when the channel created it disconnects.
What you probably want is exclusive consumer which can be done by setting exclusive parameter to true when consume from a queue. Exclusive consumer ensures that only one consumer can consume this queue .It excludes all other consumers from the queue once it is consumed.
In summary , to make a queue exclusive to one consumer and persist the messages in this queue, you should :

*

*Declare the queue to be durable

*When producer publishes message , the message 's delivery mode should set to persistent

*Use exclusive consumer


text:
Q: week number from given date in pandas I have a data frame with two columns Date and value.
I want to add new column named week_number that basically is how many weeks back from the  given date
import pandas as pd
df = pd.DataFrame(columns=['Date','value'])
df['Date'] = [ '04-02-2019','03-02-2019','28-01-2019','20-01-2019']
df['value'] = [10,20,30,40]
df
         Date  value
0  04-02-2019     10
1  03-02-2019     20
2  28-01-2019     30
3  20-01-2019     40
suppose given date is 05-02-2019.
Then I need to add a column week_number in a way such that how many weeks back the Date column date is from given date.
The output should be
    Date  value   week_number

0  04-02-2019     10    1
1  03-02-2019     20    1
2  28-01-2019     30    2
3  20-01-2019     40    3
how can I do this in pandas

A: First convert column to datetimes by to_datetime with dayfirst=True, then subtract from right side by rsub, convert timedeltas to days, get modulo by 7 and add 1:
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df['week_number'] = df['Date'].rsub(pd.Timestamp('2019-02-05')).dt.days // 7 + 1
#alternative
#df['week_number'] = (pd.Timestamp('2019-02-05') - df['Date']).dt.days // 7 + 1
print (df)
        Date  value  week_number
0 2019-02-04     10            1
1 2019-02-03     20            1
2 2019-01-28     30            2
3 2019-01-20     40            3


text:
Q: Improper integral convergence $I = \int_{0^+}^{1^-}\frac{\log(x)}{1-x}dx$ I was solving a few problems regarding convergence and divergence when I ran into this one. I tried searching on the internet but couldn't find an exact match to the problem. The task is to determine whether the following integral diverges or converges.
$$I = \int_{0^+}^{1^-}\frac{\log(x)}{1-x}dx$$
I tried solving it using comparison test but could not find an appropriate function to test it against. No other tests would fit. I also tried integrating the function using by parts but only reached till here (not entirely sure whether it is right or wrong) ($\log(x)$ - first part and $(1-x)$ - second part)
$$I=-\log(x)\cdot \log(1-x) + \int \frac{\log(1-x)}{x}dx$$
Putting $y=1-x$ in second part makes it equal to the original integral. So
$$I=-\frac12\log(x)\cdot \log(1-x)$$
Here, I face problems putting in the limits.
Please help.

A: Hint. The function $\frac{\log(x)}{1-x}$ is continuous and negative in $(0,1)$ so we can apply the comparison test.
As $x\to 0^+$ then
$$\frac{\log(x)}{1-x}\sim \log(x)$$
Is $\log(x)$ integrable in a right neighbourhood of $0$?
Moreover, as $x\to 1^-$,
$$\frac{\log(x)}{1-x}=\frac{\log(1-(1-x))}{1-x}\sim \frac{-(1-x)}{1-x}=-1.$$
What may we conclude?
P.S. The value of such integral is quite famous: see
integral representations of $\zeta(2)$.


text:
Q: Drawing a triangle using mouse clicks in java graphics this is my code. It worked for drawing a circle but I am having troubles drawing a triangle now.. A triangle should appear using mouse clicks but it is showing a triangle immediately after running the application. Please help. Thanks.
    package mouse;

import java.awt.*;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.event.*;

import java.awt.geom.*;

public class triangle extends JFrame implements ActionListener, MouseListener {
    int xx[]= {20, 50, 80};
    int yy[]= {80, 30, 80};

    public triangle () {
        setSize(2000,2000);
        addMouseListener(this);
    }

    public static void main(String[] args) {
        //TODO code application logic here
        java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                   triangle frame = new triangle();
                   frame.setVisible(true);
              }
        });
    }

    public void actionPerformed(ActionEvent ae) {

    }

    public void drawPolygon(int x, int y, int i)
    {
        Graphics g = this.getGraphics();
        g.setColor(Color.BLACK);
        g.drawPolygon(xx, yy, 3);

    }

    int x, y;

    public void mouseClicked(MouseEvent e) {
        x = e.getX();
        y = e.getY();

        repaint();
    }

    @Override
    public void paint(Graphics g) {
        drawPolygon(x, y, 3);
    }

    public void mouseExited(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }
}``

A: The problem you have is that you override the paint method and therefore the drawPolygon method is already called in the initial painting of the JFrame.
For the effect you want to have you should avoid overriding the paint method and only use the drawPolygon method when the MouseListener is invoked.
This should look like this:
@Override
public void mouseClicked(MouseEvent e) {
    x = e.getX();
    y = e.getY();

    drawPolygon(x,y,3);

    repaint();
}

In order to paint the triangle where you click with the mouse you need to add the current position to the original triangle coordinates like this:
public void drawPolygon(int x, int y, int i)
{
    Graphics g = this.getGraphics();
    g.setColor(Color.BLACK);

    int[] drawx = {xx[0]+x,xx[1]+x,xx[2]+x};
    int[] drawy = {yy[0]+y,yy[1]+y,yy[2]+y};

    g.drawPolygon(drawx, drawy, i);

}

I hope this answers you question.
Some general remarks on programming:
You should definitely include a
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

otherwise you program won't terminate on closing the frame and keep on running.
It would also help the readability of your code if you avoid having everything in one class and split your code into several classes.
The MVC model is something that is a very good general guideline for designing class structures.


text:
Q: Showing if $f \in R_{\alpha}([a,b])$ $\implies$ $f \in R_{\beta}([a,b])$ where $\beta = V_{a}^{x}(\alpha)$ I am learning about Riemann-Stieltjes Integrals from Carother's Real Analysis. Specifically, I'm trying to learn Riesz Representation. However, prior to that I need to learn the following Theorem:

Let $\alpha\in BV([a,b])$ and $B(x) = V_{a}^{x}(\alpha).$ Then the following holds:
  \begin{align*}
\Big|\int_{a}^{b}fd\alpha\Big| \leq \int_{a}^{b}| f|d\beta \leq ||f||_{\infty}V_{a}^{b}(\alpha)
\end{align*}

I understand most of the proof but one part of it is not obvious to me. I don't understand how the author makes the jump from saying $f \in R_{\alpha}([a,b])$ $\implies$ $f \in R_{B}([a,b])$. I believe they are using the following theorem, but I could be wrong:

Let $\alpha,\beta \in BV([a,b])$. Then the following holds:
  \begin{align*}
f \in R_{\alpha}\cap R_{\beta} \implies f \in R_{\alpha \pm\beta}
\end{align*}

Any help is greatly appreciated! Thanks again.

A: With the function $B$ defined using the total variation of $\alpha$ on the interval $[a,x]$:
$$B(x) = V_a^x(\alpha),$$
it can be shown that $f$ is Riemann-Stieltjes integrable with respect to $B$ and $B - \alpha$. Also if $f$ is integrable then so is $|f|$. A proof is given here.
It appears you understand this fact, and your idea about how to proceed is correct.
To obtain the inequality, take $g = (B+ \alpha)/2$ and $h = (B-\alpha)/2$. Both are increasing functions on $[a,b]$ and using basic properties of Riemann-Stieltjes integration we have
$$\begin{align}\left|\int_a^b f \, d\alpha \right| &= \left|\int_a^b f \, d(g - h)  \right|  \\ &= \left|\int_a^b f \, dg -  \int_a^b f \, dh \right| \\ &\leqslant   \left|\int_a^b f \, dg \right| +  \left|\int_a^b f \, dh \right| \\ &\leqslant \int_a^b |f| \, dg  +  \int_a^b |f| \, dh  \\ & = \int_a^b |f| \, d(g + h) \\ &= \int_a^b |f| \, dB \\ &\leqslant \sup_{t \in [a,b]}|f(t)|(B(b) - B(a)) \\ &= \|f\|_{\infty}V_a^b(\alpha)\end{align}$$


text:
Q: Unix sort command with blank value I am using below sort command to sort 2 fields in desc order and there is a chance that the second field can be blank in some cases.
sort -k 1.1,1.2n -brn -k 1.5,1.6 -o

sample data:
112321
112422
112526
1124
112623

output must be as below
1124
112526
112623
112422
112321

Can you please help me out with a solution, thanks!!!!

A: Do it as two separate commands and concatenate the results.
{ grep -v '^.....' input | sort -k 1.1,1.2n;
  grep '^.....' input | sort -k 1.1,1.2n -brn -k 1.5,1.6; } > output


text:
Q: binding different local IP's to one SOAP service client application - is it possibile? I have remote service to ask...
I have a service client defined in service reverence https://xyz/service.php?wsdl
I created it like this:
allegro1.servicePort service1;
service1 = new allegro1.servicePortClient("servicePort");

I have multiple IP addresses on my local machine to use...
I can change the address used by service client like this:
var localIpAddress = IPAddress.Parse("111.111.111.111");
var hasLocalAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Any(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.Equals(localIpAddress));

ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri(serviceurl));

servicePoint.BindIPEndPointDelegate = (sp, rm, retryCount) => { return new IPEndPoint(hasLocalAddress ? localIpAddress : IPAddress.Any, 0); };

But I don't know how to create multiple instances of my service client.
I tray:
allegro1.servicePort service2 = new allegro1.servicePortClient("servicePort");

But when i change my local ip address of service1 i chage it to service2 too ...
Is there any method to ask remote soap service from different IP addresses in one application ?
I need to do it because my boss wants to ask the same service from my two local IP addresses simultaneously, only method that works is creating many applications - one app one ip - i don't understand why ???


text:
Q: Flask: flask_wtf CSRFProtect yields Bad Request The CSRF session token is missing I am trying to configure CSRF protection on my web app and I cannot seem to figure out FLASK_WTF CSRFProtect
I am initializing my app with
from flask import (Flask, g, jsonify, redirect, render_template, request,
                   url_for)
from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect()

def create_app():
    ...
    ...
    csrf.init_app(app)

    app.app_context().push()

    return app

I am also setting app.config["SECRET_KEY"] and app.config["WTF_CSRF_SECRET_KEY"] within the create_app function.
All of my forms have <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />.
I have read on other posts about using Flask.Form but I am not doing this, rather just grabbing the POST data from the request.form dict.
On POST, I get the following error message:
Bad Request

The CSRF session token is missing.

Locally everything runs fine but when I run my code from my gunicorn, nginx enviornment it fails. Any ideas? Do I need to set the SERVER_NAME attribute?
EDIT:
Upon request, the CSRF_TOKEN is actually sent after inspecting the headers.
Hmm, the form csrf_token in source seems to be different than the token sent with POST
EDIT:
I added configuration variables for flask_wtf in my create_app function and it is still not working:
app.config["WTF_CSRF_SECRET_KEY"] = "same_as_secret_key"
app.config["WTF_CSRF_FIELD_NAME"] = "csrf_token"
app.config['WTF_CSRF_ENABLED'] = True
app.config["WTF_CSRF_TIME_LIMIT"] = None  # valid throughout life of session
if debug:
    app.config["SESSION_COOKIE_SECURE"] = False
else:
    app.config["SESSION_COOKIE_SECURE"] = True
app.config["REMEMBER_COOKIE_SECURE"] = True

Could this have something to do with my nginx configuration?


text:
Q: Spring Data JPA like project not dependent on Spring Does anyone know any Java frameworks that follows the repository approach with automatic implementation of query methods (e.g. findByNameAndLastName(…)) but not tied to Spring, only pure JPA. Such feature also exists in GORM. I would like to see if there is any project that can be used in Guice or pure JavaEE environment without bringing Spring as a dependency.

A: (Disclaimer: I am the author of Spring Data JPA)
There is the CDI Query Module which is very similar to what Spring Data JPA. There's also a DeltaSpike module.
Note that Spring Data JPA ships with a CDI extension that creates repository proxies as plain CDI beans and does not bootstrap a Spring container. There are APIs that allow the creationg of repository proxies programmatically such as:
EntityManager em = // … obtain EntityManager
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);

Yes, it still requires Spring libraries to be present on the classpath but it is then using them similar to how you would use Commons Collection or the like. We try not to reinvent the wheel and the Spring libraries we depend on provide a lot of useful code that we do not have to re-code.
So if it's Spring as DI container you're worrying about, feel free to give the CDI extension of Spring Data JPA a choice. If you don't want to use any Spring whatsoever (for whatever reason), have a look at the alternatives.

A: Based on Oliver's information, followed up as also interested in this topic --
CDI Query joining Deltaspike mail thread: http://apache-deltaspike-incubator-discussions.2316169.n4.nabble.com/Porting-the-CDI-Query-extension-project-to-DeltaSpike-td4329922.html
Deltaspike base link: http://deltaspike.apache.org/index.html
Getting started: http://deltaspike.apache.org/documentation.html
Just did their 0.4th release as of 5/31/2013.
However, have not done enough of a review to contrast/compare Deltaspike versus Spring-Data w/ CDI extensions (spring-data being very mature).

A: Take a look at Tomato on github!
It is a functional replacement for Spring JPA, has zero dependencies, performs better and is far easier to use.  It will reduce your data access code by 98% and deliver the results you want right out of the box.
https://rpbarbati.github.io/Tomato.
If you want free, fully functional dynamic forms and/or tables for any Tomato entity or hierarchy, that can also be customized easily, try the angular based companion project...
https://rpbarbati.github.io/Basil
Both are current, maintained projects.
Try it yourself, or contact the author at rodney.barbati@gmail.com with questions.


text:
Q: How to smash the stack? I have a little assignment of stack smashing.So what is the simplest way to smash the stack?
I just want a simple illustrative method.

A: Try reading "Smashing the Stack for Fun and Profit" by Aleph One.


text:
Q: Fluent NHibernate - Map 2 tables to one class I have a table structure something like this
table Employees
 EmployeeID
 EmployeeLogin
 EmployeeCustID

table Customers
 CustomerID
 CustomerName

What i would like is to map the structure above to one single class named:
Class Employee
 EmployeeID
 EmployeeLogin
 EmployeeName

How do i do that with fluent nhibernate ?

A: I don't know if it is possible with fluent, but in xml you use the join element:
simplified:
<class name="Employee" table="Customers" >
  <id name="CustomerID" .../>

  <property name="CustomerName"/>

  <join table="Employees">
    <key column="EmployeeCustID" />
    <property name="EmployeeLogin" />
  </join>

</class>

See this post by Ayende

A: I agree with Frans above but if you're stuck with someone else's code and have to use the existing structure, you can can use WithTable.
public class EmployeesMap : ClassMap<Employees>
{
    public EmployeesMap()
    {
        Id(x => x.EmployeeId);
        Map(x => x.EmployeeLogin);

        WithTable("Customers", join =>
            {
                join.Map(m => m.EmployeeName, "CustomerName");
                join.WithKeyColumn("EmployeeCustID");
            });
    }
}

[DataContract(IsReference = true)]
public class Employees
{
    [DataMember]
    public virtual int EmployeeId { get; set; }

    [DataMember]
    public virtual string EmployeeLogin { get; set; }

    [DataMember]
    public virtual string EmployeeName { get; set; }
}

A: I have not tried this since Fluent NHibernate went to 1.0 so my syntax may be incorrect. I'm pretty sure this will only work if Customer.CustomerId is a foreign key to Employee.
public class EmployeeMap : ClassMap<Employee>
{
  public EmployeeMap()
  {
    Id(x => x.EmployeeId);
    Map(x => x.EmployeeLogin);

    Table("Customer", m =>
    {
      m.Map(x => x.EmployeeName, "CustomerName");
    });
  }
}

A: Is EmployeeCustID unique? If not, this is never going to work, as you then try to cram two different entity types into 1. Also, with your structure, how do you want to save an instance? -> the CustomerID isn't known, so you can't save such an entity.
IMHO it's better to simply keep Customer as a related entity to Employee, as (I assume) the EmployeeCustID is used to link a Customer entity to an Employee entity if the employee is also a customer, which means 'customer' is just a role for employee and therefore optional and changeable and thus should be a separate entity.


text:
Q: Expressing Express $\lim_{n\to∞} \left(\frac1{n+1} + \frac1{n+2} + ... +\frac1{n+n}\right)$ using Riemann definite integration
Express $\lim_{n\to∞} \left(\frac{1}{n+1} + \frac{1}{n+2} + ... +\frac{1}{n+n}\right)$ as a Riemann integral.

I was able to transform it to $\lim_{n\to ∞}\sum\limits_{r=1}^n \frac1{n+r}$.
I don't know how to go about it from here.

A: When doing problems like this you want to look for a factor of $\frac{1}{n}$, as this is $\Delta x$. You also want to look for something involving $\frac{k}{n}$, or $\frac{r}{n}$ in your case as you are using $r$ as the index, because these will be the sampling points from the intervals. So I suggest dividing the numerator and denominator by $n$ to get
$$\lim _{n \to \infty} \sum_{r=1}^n \frac{1}{n+r} =\lim _{n \to \infty} \sum_{r=1}^n \frac{\frac{1}{n}}{1+\frac{r}{n}}.$$
Now you should be able to figure out the function and the limits of integration. There's actually more than one choice here. You could say $1+\frac{r}{n}$ are the sampling points, and we'll say they're the right endpoints of the intervals (since $r$ starts at $1$ and not $0$). So your sampling points are $x_1=1+\frac{1}{n},x_2=1+\frac{2}{n},\dots,x_n=1+\frac{n}{n}=2$. Thus the integral is from $1$ to $2$. The $r$th term in the sum is
$$\frac{\frac{1}{n}}{1+\frac{r}{n}}= \frac{\Delta x}{x_r}= \frac{1}{x_r} \Delta x$$
so in this case your function is $\frac{1}{x}$. Then the limit is equal to the integral $\int_1^2\frac{1}{x}dx$.
Another option is to say that the sampling points are $\frac{r}{n}$, so $x_1 = \frac{1}{n},x_2 = \frac{2}{n}, \dots,x_n = \frac{n}{n}=1$. In this case the integral goes from $0$ to $1$, and the $r$th term of the sum is
$$\frac{\frac{1}{n}}{1+\frac{r}{n}} = \frac{\Delta x}{1+x_r} = \frac{1}{1+x_r}\Delta x$$
and so the function is $\frac{1}{1+x}$, and the limit is equal to the integral $\int_0^1 \frac{1}{1+x}dx$. A $u$-substitution should convince you that you get the same answer from both choices.

A: If $1/n$ is factored out it is $[1/n](1/(1+1/n))+1/(1+2/n)+\cdots +1/(1+n/n),$ which is the right hand Riemann sum with $n$ subdivisions for integrating $1/x$ from $x=1$ to $x=2.$


text:
Q: Showing and editing .gdb layers on QWC2 I am developing a react.js based GIS website to use various map tools such as measuring distances and adding layers. One problem I have is I would like to manipulate and display .gdb layers on the said website.
Currently I use QWC2 to do such operations but seems to me that QWC2 doesn't support adding .gdb layers.
I would like to keep using QWC2 so what should I do to be able to open and edit .gdb layers on QWC2.


text:
Q: Saving image with PHP on localhost uploaded with a form i'm trying to save an image uploaded with a HTML form on my localhost server (working with Xampp), but although there are no errors, the file isn't saved anywhere.
This is the form, really simple:
<form id="form1" action="result.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="imguploaded" id="imguploaded" accept=".png, .jpg, .jpeg"></br>
    <input class="btn btn-outline-danger btn-lg" id="inputbtn" type="submit" value="Upload Image" name="submit">
  </form>

and this is the PHP code (on result.php):
<?php
    $result=false;
    $error=false;
    if (isset($_FILES['imguploaded'])){
        $nomefile = strtolower($_FILES['imguploaded']['name']);
        $path = "caricamenti/$nomefile";
        move_uploaded_file($_FILES['imguploaded']['name'], $path);
        echo($path);
    }
    ?>

the path exists and it is in the same folder of the .PHP files.

A: In move_uploaded_file($_FILES['imguploaded']['name'], $path); the first parameter isn't correct. It should be the temporary path where php stored it intermediatly, which you find in $_FILE['imguploaded']['tmp_name'].
So change that line to
move_uploaded_file($_FILES['imguploaded']['tmp_name'], $path);

relevant docs
Be sure to:

*

*sanitize filename & extention first

*check for allowed mimetypes, size, ..

Right now I could easily upload a php script and execute that.

A: Try this:
 $file_name= $_FILES['imguploaded']['name'];
 $file_tmp_name= $_FILES['imguploaded']['tmp_name'];
 $div= explode('.',$file_name );
 $file_txt= strtolower(end($div));
 $unique_image= substr(md5(time()),0,10).".".$file_txt;
 $uploaded_image= "caricamenti/".$unique_image;
 move_uploaded_file($file_tmp_name,$uploaded_image);


text:
Q: Elasticsearch always uses the default mapping Am trying to create an index using "CSV River Plugin for ElasticSearch", my csv file contains String, long and date values.
My problem is :
 - ElasticSearch always consider long values as string ( with default mapping ) and when i try to create a specific mapping to be used, it changes long type to string type.
 - So, is there a way to tell ElasticSearch Don't map everything as string ?
Any suggestion please?
Thank you


text:
Q: Azure Notifcation Hub CreateOrUpdateInstallationAsync not failing but Installation not being created I have an ASP.NET Web Api that is registering Android and iOS installations in our Azure Notification Hub. It creates a HubClient using a connection string
this.azureHub = NotificationHubClient.CreateClientFromConnectionString(
    "Endpoint=sb://OUR-HUB-NS.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=tK/SEXXXXXXXXXXX/7LUtvRoNt+HjToFmP+T++yW5g=",
    "OUR-HUB");

We then create an installation using this code
try
{
    await azureHub.CreateOrUpdateInstallationAsync(installation, token);
}
catch(Exception e)
{
    this.logger.LogError(e, "CreateOrUpdateInstallationAsync failed with" + e.Message);
    return false;
}

return true;

When I had the NoticationHubClient incorrectly configured I was getting 401 errors and if I pass in nonsense for the installation data I will get a 400. Currently the call does not throw an error so I asm going to assume what I am passing is correct and it can successfully connect to the hub. However registrations are not being created. If i try and get the installation after it is created with
GetInstallationAsync(installation.InstallationId)

I get an error saying the installation cannot be found and if I try and get all registrations i get an empty list
var registrations = await azureHub.GetAllRegistrationsAsync(0);

Further confirmation that my installations are not being created is that if I use the "Test Send" in Azure Portal I get "Message was successfully sent, but there were no matching targets." for either Apple or Android platform
What is happening to my registration?

A: I recreated the Notification Hub with a different name, in the same namespace and everything just started working.
I then recreated the non-working hub in Azure Portal and it now all works.
All I can say is that I had previously deleted the hub using the OSS Service Bus Explorer and perhaps that deleted the hub in a way that Azure didn't like.
Not the answer I was expecting.


text:
Q: Screenshot of full sized RecyclerView results in the last element being drawn on the top The problem
I have written some code to take full sized screenshots of RecyclerView
which almost work, but somehow the last list item gets drawn on top of the list.

I strongly suspect the bug occurs in this code block where the drawing of each list item happens
  int viewHolderTopPadding = 0;
  for (int i = 0; i < itemCount; i++) {
        recyclerView.getAdapter().onBindViewHolder(viewHolder, i);
        viewHolder.itemView.draw(canvas);
        canvas.drawBitmap(recyclerViewBitmap,0f, viewHolderTopPadding, null);
        viewHolderTopPadding += measuredItemHeight;
    }

But if I use the deprecated approach for saving Views to Bitmaps then It works correctly:
for (int i = 0; i < itemCount; i++) {
        recyclerView.getAdapter().onBindViewHolder(viewHolder, i);
        viewHolder.itemView.setDrawingCacheEnabled(true);
        viewHolder.itemView.buildDrawingCache();
        canvas.drawBitmap(viewHolder.itemView.getDrawingCache(), 0f, viewHolderTopPadding, null);
        viewHolderTopPadding += measuredItemHeight;
        viewHolder.itemView.setDrawingCacheEnabled(false);
        viewHolder.itemView.destroyDrawingCache();
    }

Rest of the code
private Bitmap generateLongBitmap(RecyclerView recyclerView) {

    int itemCount = recyclerView.getAdapter().getItemCount();
    RecyclerView.ViewHolder viewHolder = recyclerView.getAdapter().createViewHolder(recyclerView, 0);

    //Measure the sizes of list item views to find out how big itemView should be
    viewHolder.itemView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    // Define measured widths/heights
    int measuredItemHeight = viewHolder.itemView.getMeasuredHeight();
    int measuredItemWidth = viewHolder.itemView.getMeasuredWidth();

    //Set width/height of list item views
    viewHolder.itemView.layout(0, 0, measuredItemWidth, measuredItemHeight);

    //Create the Bitmap and Canvas to draw on
    Bitmap recyclerViewBitmap = Bitmap.createBitmap(recyclerView.getMeasuredWidth(), measuredItemHeight * itemCount, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(recyclerViewBitmap);

    //Draw RecyclerView Background:
    if(recyclerView.getBackground() !=null){
        Drawable drawable = recyclerView.getBackground().mutate();
        drawable.setBounds(measuredItemWidth,measuredItemHeight * itemCount,0,0);
        drawable.draw(canvas);
    }

    //Draw all list item views
    int viewHolderTopPadding = 0;
    for (int i = 0; i < itemCount; i++) {
        recyclerView.getAdapter().onBindViewHolder(viewHolder, i);
        viewHolder.itemView.draw(canvas);
        canvas.drawBitmap(recyclerViewBitmap,0f, viewHolderTopPadding, null);
        viewHolderTopPadding += measuredItemHeight;
    }
    return recyclerViewBitmap;
}


text:
Q: preventing the trigger of Task T2 when task T1 which calls stored procedure when an error is returned I need help with a practical scenario. I had stored procedure where it copies data from an external location into intermediate table, and returns the error message when there is no file in the external location. this is called using task T1.
after loading the data into intermediate table T1 has to trigger another task (T2) to transform the data and finally load it into the target table. when there is no file in the external location, how to prevent the task T2 from triggering.
after that it has to send an email alert about non availability of a file. any guidance is helpful.

A: Use of snowflake STREAMS feature can help you here.
You can create a STREAM based on your intermediate table.
create stream my_stream on table my_intermediate_table;

Then you can condition execution of your task T2 on the presence of unconsumed data from your stream using WHEN parameter
WHEN
   SYSTEM$STREAM_HAS_DATA('my_stream')

Your task T2 is used to transform and load date in a final table. Instead of querying data from your intermediate table make it consume the stream content with a DML statement.
INSERT INTO my_final_table SELECT * FROM my_stream;

When new data is inserted into your intermediate table, this will allow your task T2 to be triggered as your stream contains data. If your stream is empty then your task T2 execution will be skipped as your WHEN will not be fulfilled.
Snowflake will not allow you to natively send emails alerts for tasks monitoring.
You will have to scan metadatas using TASK_HISTORY to find tasks executions status and external features like ETL tools or Snowflake external functions to send emails.


text:
Q: How to add multiply annotation in mapVIew I have mapView and address from firebase. Now i can add in mapView only one annotation, but in print("Address (self.allAddresses)") i got three address:
Address Москва, Пресненская набережная д.8, квартира 195, подъезд 94
Address Москва, ул. Правды д.24 строение 3
Address Москва,ул.Электрозаводская д.21
How i can add three or more annotations?
My firebase:
{
  «Address» : {
    «AddressOne» : {
      "address" : "Москва, Пресненская набережная д.8, квартира 195, подъезд 94",
    },
    "AddressTwo» : {
      "address" : "Москва, ул. Правды д.24 строение 3",
    },
    "AddressThree» : {
      "address" : "Москва,ул.Электрозаводская д.21",
    }
  }
}

And my code:
class AddressesMapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var allAddresses: String = ""

    var count = 0

    let geocoder = CLGeocoder()

    var addressRef: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()

        addressRef = Database.database().reference(withPath: "Address")

        loadAddressFromFirebase()

    }
    func loadAddressFromFirebase() {

        addressRef.observe(.value, with: { (snapshot) in

            for address in snapshot.children.allObjects as! [DataSnapshot] {

                let value = address.value as! NSDictionary

                self.allAddresses = value["address"] as? String ?? ""

                print("Address \(self.allAddresses)")

                if self.count < self.allAddresses.count {

                    let addresses = self.allAddresses

                    self.geocoder.geocodeAddressString(addresses, completionHandler: { (placemarks, error) in

                        print("Address - \(addresses)")

                        guard error == nil else { return }

                        guard let placemarks = placemarks else { return }

                        if let placemark = placemarks.first {

                            self.mapView.addAnnotation(MKPlacemark(placemark: placemark))

                        }

                        self.count += 1
                        print("Count - \(self.count)")
                    })
                }
            }
        })
    }
}

A: *

*Try allocating geoCoder wihtin the 'for' loop.

*Call geocoder.cancelGeocode() method.
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(addresses, completionHandler: { (placemarks, error) in

            print("Address - \(addresses)")

            guard error == nil else { return }

            guard let placemarks = placemarks else { return }

            if let placemark = placemarks.first {

                self.mapView.addAnnotation(MKPlacemark(placemark: placemark))

            }

            self.count += 1
            print("Count - \(self.count)")
            geocoder.cancelGeocode()
        })


text:
Q: jQuery empty POST variables with jQuery Tools Validator I'm using jQuery Tools Validator and I'm unable to send ajax post data with it.
The strange thng is I was checking different pages using the same framework and they use the same code, I'm not sure what am I doing wrong?
form.html:
$("#form").validator({effect: 'my_custom_effect'}).submit(function(e)  {
    if (!e.isDefaultPrevented()) {
        $.post('send.php', {
            'name': 'my name', // name is always empty
            'email': 'myemail@test.com', // email is always empty
            'message': 'just message!' // message is always empty
        });
        $("#success").fadeIn();
        e.preventDefault();
    }
});

send.php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

mail('mail@mail.com','From: ' .$name, $message);

The mail is getting submitted, the "#success" div fades in, I'm getting the mail, but name/email/messsage are always empty.
Everything works fine with HTML5 validation / without any validation at all, so it's not form-related, form uses post method and send.php as action.
Is anything wrong with the code above? I guess I've missed something, probably very simple...


text:
Q: If $x_{n+1}=f(x_n)$ and $x_{n+1}-x_n\to 0$, then $\{x_n\}$ converges Let $f:[0,1] \rightarrow [0,1]$be a continuous function. Choose any point $x_0 \in [0,1]$ and define a sequence recursively by $x_{n+1}=f(x_n)$. Suppose $\lim_{n \rightarrow \infty}x_{n+1}-x_n =0$, does this sequence converge?

A: The answer is YES - I have fixed the proof of Hongyi:
Let $K$ be the set of sub-sequential limits of the sequence $\{x_n\}$. Then $K$ is compact, and since $x_{n+1}-x_n\to 0$, $K$ is also connected. (This requires some more work.) Hence $K$ is of the form
$$
K=[a,b]\subset [0,1].
$$
If $a=b$, then we are done, since this means that the sequence $\{x_n\}$ has only one sub-sequential limit, and hence converges.
We shall next show that $a<b$ implies that $f(x)=x$ on $[a,b]$, and hence the sequence is eventually constant. This contradicts the fact that its sub-sequential limits are all the points of $[a,b]$.
Assume that $f(x)\not\equiv x$ in $[a,b]$, and let $x_0\in(a,b)$ with $f(x_0)>x_0$.
(The case $f(x_0)<x_0$ is treated similarly.) Then there exist $h>0$, such that
$$
f(x)-x\ge 0\quad\text{whenever}\quad x\in [x_0-h,x_0+h]\subset (a,b).
$$
Since $b$ is a limit point of $\{x_n\}$, there exists $x_{n_0}\in (x_0+h,1]$,
and the $n_0$ can be picked so that
$$
\lvert x_{n+1}-x_{n}\rvert <h, \quad \text{when}\quad n\ge n_0.
$$
This means that, if $x_{n_0}$ is very close to $b$, then $x_n$, $n\ge n_0$, CAN NOT get smaller than $x_0$, since in the whole interval $[x-h,x+h]$, $f(x_n)\ge x_n$. Thus, $a$ can not be a limit point.

A: Yes. Let $I = \lim_{k \rightarrow \infty} I_k$ where $I_k$ is the closure of $\{x_k,x_{k+1},...\}$. Note that because $x_{k+1}-x_k \rightarrow 0$, $I$ is connected, thus either a singleton or an interval. If $I$ is a singleton, we are done. If $I$ is an interval $(x_-,x_+)$, then $f(x)=x$ on this interval. It then follows, unless $x_k$ is constant for sufficiently large $k$, that $x_k$ is strictly monotone in $k$; and thus that the sequence must converge to some point within $I$.

A: I'm fairly sure it need not converge.
Let $$H_n = \sum_{i=1}^n \frac{1}{i}$$
Define $y_n = H_n \pmod{1}$ if $\lfloor H_n \rfloor$ is even, and $1-H_n \pmod{1}$ otherwise. This sequence oscillates between 0 and 1 indefinitely, so it doesn't converge; although $y_{n+1} - y_n$ tends to $0$. It is the case that the difference between distinct harmonic numbers is never an integer, according to Wikipedia, so this sequence never duplicates any value.
We just need to show that we can define continuous $f: [0,1] \to [0,1]$ such that $f(x_n) = x_{n+1}$.
I've convinced myself of this with some rather dubious reasoning about infinitesimals.


text:
Q: $A.util.removeClass not working in some cases On init of a component, I want to hide an element lightning:buttonIcon if some condition is satisfied(see controller code). In this case it is getting satisfied and I am reaching the code where element is to be hidden(hideElement function in helper). But the element is still visible, on the other hand, if we access the same code (hideElement function) from helper itself like:
this.hideElement(component, id);

It hides the element. What is the reason behind this?

Markup:

                <lightning:buttonIcon aura:id="addFieldButtonID" iconName="utility:new" size="large" variant="bare" onclick="{! c.handleFieldDone }" alternativeText="Done!"/>

                    <lightning:icon aura:id="doneFieldIcon" iconName="action:approval" size="xx-small" alternativeText="Done" class="slds-hide"/>

                <lightning:buttonIcon iconName="utility:clear" size="large" variant="bare" alternativeText="Remove" onclick="{! c.removeEntry }"/>

Controller:

handleInit : function(component, event, helper){

        if(component.get('v.disableEntryEdit')){
            helper.HideElement(component, 'addFieldButtonID');
        }
}

Helper:

hideElement : function(component, id){
        var element=component.find(id);
        console.log('Element: ' , element.getLocalId()); //gives ID as :addFieldButtonID
        $A.util.removeClass(element, 'slds-show');
        $A.util.addClass(element, 'slds-hide');
        console.log('elementclass: ' , element.get('v.class')); //gives o/p : undefined
    },

A: Instead of doing things in init, try it in afterRenderer. Reason is that init is called long before DOM availability, which might cause a timing issue.
Incase of afterRenderer it is called only after the DOM is rendered in the view.


text:
Q: Duplicate field returned in postman using flask I am working on a simple python app which fetches the reviews from users about different businesses, in this case I am trying to return a review and view it as an individual review however the "reviews" field seems to be duplicating but I have no idea where.
Here is the code for the app
from flask import Flask, request, jsonify, make_response
from pymongo import MongoClient
from bson import ObjectId
import json

class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        return super(MyEncoder, self).default(obj)

app = Flask(__name__)

client = MongoClient("mongodb://127.0.0.1:27017")
db = client.bizDB
businesses = db.biz
app.json_encoder = MyEncoder

with app.test_request_context():
    db.mycollection.insert_one({'a': 1})
    doc = db.mycollection.find_one({'a': 1})

    print(jsonify(doc).response)

@app.route("/api/v1.0/businesses", methods=["GET"])
def show_all_businesses():
    page_num, page_size = 1, 10
    if request.args.get("pn"):
        page_num = int(request.args.get("pn"))
    if request.args.get("ps"):
        page_size = int(request.args.get("ps"))
    page_start = page_size * (page_num - 1)

    data_to_return = []
    for business in businesses.find().skip(page_start).limit(page_size):
        business["_id"] = str(business["_id"])
        for review in business["reviews"]:
            review["_id"] = str(review["_id"])
        data_to_return.append(business)

    return make_response( jsonify( data_to_return ), 200 )

@app.route("/api/v1.0/businesses/<string:id>", methods=["GET"])
def show_one_business(id):
    business = businesses.find_one({"_id":ObjectId(id)})
    if business is not None:
        business["_id"] = str(business["_id"])
        for review in business["reviews"]:
            review["_id"] = str(review["_id"])
        return make_response ( jsonify ( business ), 200)
    else:
        return make_response (jsonify({ "error" : "Invalid Business ID" } ), 404)

@app.route("/api/v1.0/businesses", methods=["POST"])
def add_business():
    if "name" in request.form and "town" in request.form and "rating" in request.form:
        new_business = { "name" : request.form["name"],
                        "town" : request.form["town"],
                        "rating" : request.form["rating"],
                        "reviews" : {}
                        }
        new_business_id = businesses.insert_one(new_business)
        new_business_link = "http://localhost:5000/api/v1.0/businesses/" + str(new_business_id.inserted_id)

        return make_response( jsonify( { "url" : new_business_link } ), 201 )
    else:
        return make_response ( jsonify( { "error" : "Missing form data" } ), 404 )

@app.route("/api/v1.0/businesses/<string:id>", methods=["PUT"])
def edit_business(id):
    if "name" in request.form and "town" in request.form and "rating" in request.form:
        result = businesses.update_one(
            {"_id" : ObjectId(id)},
            {
                "$set": {
                    "name" : request.form["name"],
                    "town" : request.form["town"],
                    "rating" : request.form["rating"]
                }
            }
        )
        if result.matched_count == 1:
            edited_business_link = "http://localhost:5000/api/v1.0/businesses/" + id
            return make_response( jsonify( { "url": edited_business_link } ), 200 )
        else:
            return make_response ( jsonify( { "error" : "Invalid business ID" } ), 404 )
    else:
        return make_response ( jsonify( { "error" : "Missing form data" } ), 404 )

@app.route("/api/v1.0/businesses/<string:id>", methods=["DELETE"])
def delete_business(id):
    result = businesses.delete_one( { "_id" : ObjectId(id) })
    if result.deleted_count == 1:
        return make_response( jsonify( {} ), 200)
    else:
        return make_response ( jsonify( { "error" : "Invalid business ID" } ), 404 )

@app.route("/api/v1.0/businesses/<string:id>/reviews", methods=["POST"])
def add_new_review(id):
    new_review = {
        "_id" : ObjectId(),
        "username" : request.form["username"],
        "comment" : request.form["comment"],
        "stars" : request.form["stars"]
    }
    businesses.update_one( { "_id" : ObjectId(id)} , {"$push" : { "reviews " : new_review}})
    new_review_link = "http://localhost:5000/api/v1.0/businesses/" + id + "/reviews/" + str(new_review["_id"])
    return make_response( jsonify( { "url" : new_review_link  } ), 201 )

@app.route("/api/v1.0/businesses/<string:id>/reviews", methods=["GET"])
def fetch_all_reviews(id):
    data_to_return = []
    business = businesses.find_one( {"_id" : ObjectId(id) }, { "reviews" : 1, "_id" : 0})
    for review in business["reviews"]:
        review["_id"] = str(review["_id"])
        data_to_return.append(review)
    return make_response( jsonify( data_to_return), 200 )

if __name__ == "__main__":
    app.run(debug=True)

Postman is returning a double review field which makes the returned field of review being empty when trying to select an individual one. double review in postman

A: You can't have a "duplicate" field in the same object in MongoDB. On closer inspection, you can see one of the reviews fields has a space after it. You will need to tidy this up in the database and also in the code.

A: There is a typo in this function:
@app.route("/api/v1.0/businesses/<string:id>/reviews", methods=["POST"])
def add_new_review(id):
    new_review = {
        "_id" : ObjectId(),
        "username" : request.form["username"],
        "comment" : request.form["comment"],
        "stars" : request.form["stars"]
    }

    // NOTE THE EXTRA SPACE AFTER 'reviews'
    businesses.update_one( { "_id" : ObjectId(id)} , {"$push" : { "reviews " : new_review}})

    new_review_link = "http://localhost:5000/api/v1.0/businesses/" + id + "/reviews/" + str(new_review["_id"])
    return make_response( jsonify( { "url" : new_review_link  } ), 201 )

I reckon what happened here is that you tested this function multiple times during development and updated an existing entry with two different versions of the code, hence the empty reviews field in the response JSON. Once you wipe your database and fix the typo, it should work as expected.


text:
Q: Changing size of a UniformGrid with a user control My main window consists of a "control panel" on the left and a UniformGrid on the right. The size of the UniformGrid (rows and columns) are set by default to a 10x10 grid. In the control panel I have a user control that includes a Slider from 10 (minimum) to 50 (maximum), as well as a Button called "Change Grid". Clicking "Change Grid" should take the current value of the slider and set it to the size of the UniformGrid on the main window.
I know how to do this if I weren't using a user control - the click handler would just set the grid's row/columns to the of the slider - but I'm new to user controls and wpf in general, so not quite sure how to get the same results?


text:
Q: Multiple IPv6 tokens on one interface For a while, Linux has had support for IP tokens, meaning, you could do the following ...
ip token set ::10 dev eth0
and no matter what IPv6 prefixes the machine receives, it will always use ::10 for the interface ID without me having to hardcode a prefix:
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 11:22:33:44:55:66 brd ff:ff:ff:ff:ff:ff
    inet6 fd00:1234:5678::10/64 scope global dynamic mngtmpaddr
       valid_lft 7173sec preferred_lft 3573sec
    inet6 2001:db8::10/64 scope global dynamic mngtmpaddr
       valid_lft 2213sec preferred_lft 2213sec
    inet6 fe80::1322:33ff:fe44:5566/64 scope link
       valid_lft forever preferred_lft forever

What I'm looking for is a way to do this with multiple tokens.
For example, if I want to run two different web servers both on port 80 on this machine, I'd like the machine to have the IPv6 addresses 2001:db8::10/64 and 2001:db8::11/64, and have that automatically update if prefixes are added, removed or changed on the router.
So basically I'm looking for a command like ip set tokens eth0 ::10 ::11 ::12 that would result in a network configuration like this:
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 11:22:33:44:55:66 brd ff:ff:ff:ff:ff:ff
    inet6 fd00:1234:5678::10/64 scope global dynamic mngtmpaddr
       valid_lft 7173sec preferred_lft 3573sec
    inet6 fd00:1234:5678::11/64 scope global dynamic mngtmpaddr
       valid_lft 7173sec preferred_lft 3573sec
    inet6 fd00:1234:5678::12/64 scope global dynamic mngtmpaddr
       valid_lft 7173sec preferred_lft 3573sec
    inet6 2001:db8::10/64 scope global dynamic mngtmpaddr
       valid_lft 2213sec preferred_lft 2213sec
    inet6 2001:db8::11/64 scope global dynamic mngtmpaddr
       valid_lft 2213sec preferred_lft 2213sec
    inet6 2001:db8::12/64 scope global dynamic mngtmpaddr
       valid_lft 2213sec preferred_lft 2213sec
    inet6 fe80::1322:33ff:fe44:5566/64 scope link
       valid_lft forever preferred_lft forever

Looking at the manpage for IP tokens, it looks like an interface can only have one IP token.
I also tried the old "IPv4 trick" of adding a subinterface like this:
auto eth0
iface eth0 inet6 auto
auto eth0:2
iface eth0:2 inet6 auto

hoping to be able to set different IP tokens for the main interface and the sub interface, but that seems to be ignored, too.
Searching through the internet I found a bunch of instructions on how to add another static IPv6 address to an interface, but nothing for dynamic IPs.
If I'd like a machine to have like 5 different IPv6 addresses for different services, what's the best way to implement that so that that works when prefixes are added or removed in the route advertisements?
I was playing around with the idea of having a script or something that would be executed upon prefix change and could automatically add and remove the necessary additional IPs, but that sounds like a terrible hack; and I'd need to find a reliable trigger for when a new prefix is announced or an old one is dropped. I could use ip monitor inside a bash script but then I'd need to make sure that script is running all the time and doesn't crash; a hook like in if-pre-up.d would be way more reliable ...
What would be the proper way to do something like that? Is there a proper way to do that?
It's a bit annoying, IPv6 has A) route advertisements to automatically make everything handle a changing prefix without issues, and B) a way to add dozens of IPs to each machine so every service can get their own IP, but it has no easy-to-configure way to have both A) and B)? Or is there, and I just can't find it?


text:
Q: Trying to find out a record that does not exists in a data extension by query So, I total 4 data extensions.
I have records in 3 data extension and I want to save result in data extension# 4.
Here is a sample of how my data extensions looks like:

Desired result: CustID is the key that exists in all data extension (just by a slightly different column name). I need to find out, ALL records from DataExtension_1 that exists in DataExtension_2 with CustType = 'Student' and Status = 'TRUE' but who do not exists in DataExtension_3 with TravelDate as 13 months or less.
According to this requirement, ID# 3 record should be in the results.
This is what I have created so far:
SELECT a.CustID, a.CustEmail, b.CustType, b.Status FROM DataExtension_1 AS a
INNER JOIN DataExtension_2  AS b
    ON a.CustID = b.Cust-ID
WHERE b.CustType = 'Student' AND b.Status='true'
INNER JOIN DataExtension_3 AS c
    ON a.CustID = c.Cust--ID
WHERE c.Cust--ID IS NULL AND c.TravelDate < DATEADD(month, -13, GETDATE()

I am getting the following error:

The query syntax is invalid
  Incorrect syntax near the keyword 'INNER'.

A: You can only have one WHERE-clause in your SQL statement, as they are per query rather than per join like in your statement.
So I suggest trying this query (from clarifications in comments and in chat this also includes all the changes necessary to fulfill the asker's requirements):
SELECT a.CustID, a.CustEmail, b.CustType, b.Status
FROM DataExtension_1 AS a
INNER JOIN DataExtension_2  AS b
    ON a.CustID = b.Cust-ID
WHERE
    b.CustType = 'Student' AND
    b.Status='true' AND
    a.CustID IN
    (
        SELECT Cust--ID
        FROM DataExtension_3
        WHERE c.TravelDate <= DATEADD(month, -13, GETDATE())
    )

Additional information:

*

*Visual Explanation of SQL joins


text:
Q: isset($_POST[] ) not working i got this file upload.html where below code resides, and everytime i browse file and submit its failing at isset($_POST). it echoes "didn't upload", its working fine with same file in another folder. all i did was move the whole website folder content to another folder, and it stopped working.

File Upload:

Select a file to upload:

<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" size="50" />

<input type="submit" name="uploadxls" value="Upload File" />
</form>

<?php

include("../include/processxls.php");

date_default_timezone_set('America/Chicago');

if (isset($_POST['uploadxls']) && !empty($_POST['uploadxls']))
{
    echo "test point";
    uploadReport();
}
else
{
    echo "didn't upload";
}

function uploadReport()
{

$report=basename($_FILES['file']['name']);
$report=str_replace(' ','|',$report);

$tmppath="uploads/".$report;

    if(move_uploaded_file($_FILES['file']['tmp_name'],$tmppath))
    {
        echo " File upload success. Please wait while report is processed....... ";

        processxls($tmppath);
    }
    else
    {
        echo "fail";
    }
}

?>

A: Different browsers ignore the value of submit buttons and do not send this data with the POST
Use a hidden input field instead, and then this will be submitted regardless of browser.
<input type='hidden' name="uploadxls" value="Upload File">

A: You should determine if it is a post using $_SERVER['REQUEST_METHOD']
if( $_SERVER['REQUEST_METHOD'] === "POST" ) {
    // Do checks and logic
}

That way you don't need to worry about the browser sending the submit button or using hidden values.  PHP has a built in variable for it, may as well use it.


text:
Q: Can't get Xcode to bundle libsteam_api.dylib with a build I've put libsteam_api.dylib in the project folder. I've dragged it into the 'frameworks' folder in the project, and added it to the target. It shows up in the list of linked libraries
When I build and run, I get a "Library not loaded" error, and libsteam_api.dylib is nowhere to be found in the application bundle.
If I then manually copy the library into the MacOS folder of the bundle alongside the executable, it runs fine, but I don't want to have to keep doing that for every build
How do I get Xcode to include the library alongside the executable?

A: Add a Copy Files build phase to your target, copying the dylib into the Frameworks folder of the app package.

A: Just banged my head against this as well. There are two pieces to the solution.
1) In your project target's General settings, add the dylib to the list of "Frameworks, Libraries, and Embedded Content", then set its option to "Embed & Sign".

2) Then, under Build Phases (where it should now appear in the "Embed Libraries" section), set its destination to "Executables". (Steam's dylib wants to live alongside the executable, not in the Frameworks directory.)


text:
Q: Using newthon method to find nth root - did wolframalpha get it wrong? I'm trying to implement the n-th root algorithm as outlined here:
http://en.wikipedia.org/wiki/Nth_root
My code however, takes a lot of iterations (more than 100) to converge. I tried to check with the wolframalpha:

However, if I look at the steps section, it claims to have done 12 steps to reach the answer:

This seemed very weird and not consistent with the output of my algorithm, so I tried to look at the particular steps:

steps details 2 http://i.snag.gy/AfTAj.jpg
This corresponds with the output of my algorithm, but not at all with the output of the wolframalpha in the previous section!
Or is there something I got wrong? Isn't x12 supposed to be the approximated solution?
My code:
def nth_root(value,n):
    x = Decimal(1.0)
    value = Decimal(value)
    n = Decimal(n)
    for i in range(12):
        print "Step %d" % i
        print "x: %s" % str(x)
        print "residual: %s" % str(pow(x,n) - value)
        print "derivative: %s" % str(n * pow(x, (n-1)))
        print
        print "x%d = %s - (%s)" % (i+1, str(x), str(((pow(x,n) - value) / (n * pow(x,(n-1))))))
        x = x - ((pow(x,n) - value) / (n * pow(x,(n-1))))
        print "x%d = %s" % (i+1, str(x))
        print
        print
    return x

A: I think (conjecture!) that Wolfram Alpha's algorithm using machine precision is :

*

*start with the initial value provided $x_0$ and repeat these operations :

*compute the next value $x_{n+1}$ using two methods :

*

*the Newton iteration $\;\quad\displaystyle x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}$

*the alternative iteration $\;x_{n+1}=11\cdot x_n +10$
(for $x_n$ positive, for $x_n$ negative $\;x_{n+1}=11\cdot x_n -10$).

*the value retained for the next iteration will be the one with the smallest 'residual' $|f(x_{n+1})|$.

To see this method at work simply replace your power of $7$ by $2$ with the following result (Alpha) :

The method used by Alpha is thus not the 'pure' Newton method but a variant with faster convergence.


text:
Q: How to track the API calls in Phalcon I need to track the APIs called from different users in Phalcon and insert user's IP address into a log file. How can I do this in Phalcon?

A: Phalcon has a class specifically for logging, combining this with route events you can elegantly log the activity of users. In your controller (I reccomend using ControllerBase as it will log all instances of a user requesting a resource):
use Phalcon\Events\Event;
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger\Adapter\File as FileAdapter;

class ControllerBase extends Controller
{
    /**
     * Executed after every found action is executed
     * Logs all requests to controllers
     *
     * @param \Phalcon\Events\Event $event
     * @param \Phalcon\Mvc\Dispatcher $dispatcher
     * @return void
     */
    public function afterExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // Set up a logger instance
        $logger = new FileAdapter("app/logs/request.log");

        // Log the message
        $logger->info(sprintf("Client %s executed %s::%s on route %s",
            $this->request->getClientAddress(),
            $dispatcher->getControllerName(),
            $dispatcher->getActionName(),
            $this->request->getURI()
        ));

        // Save the log
        $logger->save();
    }
}

A: I assume that you are using MVC.
The better way to do this, is creating a ControllerBase, with extends all your controllers. Then you add a method called "onConstruct", to do whatever you want before all controllers be executed, like so:
<?php

namespace MyProject\Api\Controllers;

use Phalcon\Mvc\Controller;
use Phalcon\Http\Response;
use Phalcon\Logger\Adapter\File;

class ControllerBase extends Controller {

    public function onConstruct(){
        // here is your code
    }

}

If you are using just one controller to handle all requests of your API, just add the onConstruct method in this controller, not need for extends.
Then in this method, you can do this to get the IP and save to a file:
public function onConstruct(){
    $ip_client = $this->request->getClientAddress(); // Here, you get the IP

    $logger = new \Phalcon\Logger\Adapter\File('../logs/requests.log', array('mode' => 'w'));
    $logger->error('['.date("H:i:s").']: '. " You are doing requests in my API: " . $ip_client);
    $logger->close();

}

I added this on the construct, but you can create a method just to do this, for saving logs in all actions in your application. There is a nice way to do this, creating a model or a helper class, with handle this logs:
$log = new \Logger();
$log->setMessage("You are doing some request in my API, funny");
$log->save();

A: You better use dispatcher and beforeExecuteRoute. Also you can create custom listener as a class for events in it. Also you can still get request(and ip, params, post, json etc from di container calling it in static way).
https://docs.phalconphp.com/pl/latest/reference/dispatching.html


text:
Q: Given a full name (First Last) as one scalar entered by the user, how can I print the first and last names individually? I'm pretty new at Perl.  I have to have the user enter their full name and then print just the first, just the last, and the in "last, first" format.
I basically just have
chomp ($name = <\STDIN>);

so far.  And a bunch of stuff that hasn't worked. Ignore the '\' in the STDIN, this is my first post and I couldn't figure out formatting.
Solved:
chomp ($name = <STDIN>);
$first = substr $name, 0, rindex($name, ' ');
$last = substr $name, (rindex($name, ' ')+1);
print "\nFirst Name: ".$first;
print "\nLast Name: ".$last;
print "\nLast, first: ".$last.", ".$first;

Got it figured out with some better google searches.

A: Assuming the name contains exactly one surname which cointains no spaces, and an arbitrary number of first names, we can do this:
use strict; use warnings; use feature 'say';

chomp(my $full_name = <>);          # read a name
my @names = split ' ', $full_name;  # split it at spaces
my $last_name = pop @names;         # remove last name from the @names
my $first_name = join ' ', @names;  # reassemble the remaining names

say "First name: $first_name";      # say is print that always appends a newline
say "Last name: $last_name";
say "Last, first: $last_name, $first_name";

Always use strict; use warnings; to get as much error reports as possible. If you ignore them you likely have a bug. It also forces you to declare all variables.
Functions like rindex and index are rarely used in Perl. Regexes are often a more expressive alternative. We could also have done:
use strict; use warnings; use feature 'say';

chomp(my $full_name = <>);
my ($first_name, $last_name) = $full_name =~ /^(.*)\s+(\S+)$/;

say "First name: $first_name";
say "Last name: $last_name";
say "Last, first: $last_name, $first_name";

That regex means: ^ anchor at the start of the string, (.*) consume and remember as many characters as possible, \s+ match one or more whitespace characters, (\S+) consume and remember one or more non-whitespace characters, $ anchor at line end.

A: Please read perl split function .
my $data = <STDIN>
my @values = split(' ', $data);
my $first = $values[0];
my $last = $values[1];

I hope this could help


text:
Q: Creating Username and password in Generic OData services We would like to know how can we create username and password in Generic Odata.
we followed links available in Google couldnt succeed and anyone can have steps please do share with us


text:
Q: UINavigationController inside a UITabBarController inside a UINavigationController My problem is that I want to have a tab bar view with its children view controllers shown first. In the children view controllers, depending on what controls are clicked, I either want to A) drill down within the tab bar view (swiping away the child view controller) or B) drill down over the tab bar view (swiping away the tab bar view controller).
I've tried solving this problem by wrapping a navigation controller within the children view controllers (so I can drill down using method A) of the tab bar controller and then wrapping another navigation controller around the tab bar controller itself (so I can drill down using method B), hence the title. So it goes:
Window -> UINavigationController -> UITabBarController -> UINavigationController -> child view controller
The problem is that I end up with two navigation bars:
two navigation bars!! http://img527.imageshack.us/img527/240/problemc.png
Has anyone else had this problem, and if so, how did you get around it?
Thanks!

A: In this case, perhaps you can simply use a UITabBar and programmatically manage its state, without nesting a tab bar controller inside another controller.

A: If you're using two nested UINavigationControllers I don't think you can work around having two nav bars.  You may be able to subclass or method swizzle UINavigationController for the controller whose bar you don't want to show, and somehow prevent it from appearing or being created.  You can probably also set the navigation bar's opaque property or hidden property accordingly which may also work, but you would probably need to do some fancy UIView rearranging to prevent empty gaps.
This is purely speculation; i don't know if either approach would work or how they would, but those ideas are what i would get started with were i trying to do this.

A: Just hide the bar you don't want, easy as this:
[navigationController setNavigationBarHidden:YES animated:NO];


text:
Q: Animating the front card to the back in a stack view of cards in flutter I have got a stack of cards and scroll wheel. I am trying to animate the front card, move it to the right, then bring it back in a way it goes to the back of the cards.
I have used a future function to specify witch part of code should be done first. But what I get is; it changes the index of the card first the animation takes place. Here is my code:
class AnimationsPractice extends StatefulWidget {
  static const String id = 'test_screen';

  @override
  _AnimationsPracticeState createState() => _AnimationsPracticeState();
}

class _AnimationsPracticeState extends State<AnimationsPractice>
    with SingleTickerProviderStateMixin {
  FixedExtentScrollController _scrollController =
      FixedExtentScrollController(initialItem: 0);
  AnimationController _controller;
  Animation<Offset> _offsetAnimation;
  int selected;
  List<Widget> sampleCard;
  Animation<Offset> _offsetAnimation2;
  bool halfWayAnimation;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(duration: const Duration(seconds: 1), vsync: this)
          ..repeat();
    _offsetAnimation = Tween<Offset>(
      begin: Offset.zero,
      end: const Offset(1.5, 0.0),
    ).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Interval(
          0.0,
          0.5,
          curve: Curves.elasticIn,
        ),
      ),
    );
    _offsetAnimation2 = Tween<Offset>(
      begin: const Offset(1.5, 0.0),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Interval(
          0.5,
          1.0,
          curve: Curves.elasticIn,
        ),
      ),
    );
    halfWayAnimation = false;
    _controller.stop();

    sampleCard = [
      Container(
        height: 60,
        width: 40,
        color: Colors.red,
      ),
      Transform.rotate(
          angle: 10 * (pi / 180),
          child: Container(
            height: 60,
            width: 40,
            color: Colors.blueGrey,
          )),
      SlideTransition(
        position: halfWayAnimation ? _offsetAnimation2 : _offsetAnimation,
        child: Container(
          height: 60,
          width: 40,
          color: Colors.yellow,
        ),
      ),
    ];
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  Future<void> _playAnimation() async {
    try {
      await _controller.forward().orCancel;
      await siftingIndex();
      await _controller.reverse().orCancel;
    } on TickerCanceled {
      // the animation got canceled, probably because it was disposed of
    }
  }

  Future<void> siftingIndex() {
    return Future.delayed(const Duration(microseconds: 200), () {
      sampleCard.insert(0, sampleCard[sampleCard.length - 1]);
      sampleCard.removeLast();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(180.0),
        child: SafeArea(
          child: TextButton(
            child: Text('back to login'),
            onPressed: () {
              Navigator.pushNamed(context, LoginScreen.id);
            },
          ),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(children: sampleCard),
          CustomScrollWheel(
            onItemChange: (x) {
              setState(() {
                _playAnimation();
                halfWayAnimation = true;
              });
            },
            scrollController: _scrollController,
          ),
        ],
      ),
    );
  }
}

enter image description here


text:
Q: System.Diagnostics.Process.Start not work from on asp.net using IIS I Have Asp.Net server, when I run it as debug on local its work fine.
But when I try to run it on IIS and get it from browser it does not work
For example line :
System.Diagnostics.Process.Start(@"c:\Program Files (x86)\Microsoft Office\Office12\excel.exe");
I have tried
System.Diagnostics.Process.Start not work from an IIS
And does not helped me
Thanks a lot

A: @Thomas is right. you shouldn't try to launch another process from an unmonitored process like w3wp.exe. This is against best practices.
There are code samples available online which provide ways to read/write excel files.

*

*Read Excel File into DataSet in ASP.NET Using C#

*Manipulate Excel File with ASP.NET

*Read Data From an Excel File (.xls) in ASP.NET

*Read and Import Excel File into DataSet or DataTable using C# and VB.Net in ASP.Net


text:
Q: How can I call a variable defined inside a function from another file in Python? I have the following file named as calculo_indice.py
import pandas as pd

def limites(df,n):
    n_sigma = n * df.valor_unitario.std()
    mean = df.valor_unitario.mean()
    lower_bound: float = mean - n_sigma
    upper_bound: float = mean + n_sigma
    return (lower_bound,upper_bound)

def indice(df):
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
    df = df[~df.isOutlier]
    df['indice'] = df['valor_unitario'].apply(lambda x: ((x-lower_bound)/(upper_bound-lower_bound))*2000)
    df = df.astype({'indice': 'int64'})

It is meant to calculate the lower and upper bounds of a column of a dataframe (the first function called limites) then calculate an index over those bounds (function called indice)
Running the calculo_indice.py file it all goes fine, but when running the original file that calls those functions, I get a NameError
I imported that file as import calculo_indice as indice and then called those functions like this:
indice.limites(df, 2)
indice.indice(df)
I also tried to print(lower_bound) thats why I tried to return
Traceback (most recent call last):
  File "C:\Users\...\Indice.py", line 19, in <module>
    indice.indice(df)
  File "C:\Users\...\calculo_indice.py", line 12, in indice
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
  File "C:\ProgramData\Anaconda3\envs\Indice\lib\site-packages\pandas\core\series.py", line 4138, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libs\lib.pyx", line 2467, in pandas._libs.lib.map_infer
  File "C:\Users\...\calculo_indice.py", line 12, in <lambda>
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
NameError: name 'lower_bound' is not defined

Process finished with exit code 1

What am I doing wrong?
Appreciate ur help

A: lower_bound and upper_bound are only defined within the local scope of your limites function. If they need to also be defined within indice then you must pass them as an argument, that way they are then in scope:
I've also modified your indice function. First you need to return the DataFrame, that way you can assign your changes to a variable and have them actually take effect. Second, most of your Series.apply calls were inefficient, and there are vectorized alternatives that will act on the entire Series.
calculo_indice.py
def limites(df,n):
    n_sigma = n * df.valor_unitario.std()
    mean = df.valor_unitario.mean()
    lower_bound: float = mean - n_sigma
    upper_bound: float = mean + n_sigma
    return (lower_bound, upper_bound)

def indice(df, lower_bound, upper_bound):
    # Vectorized check
    df['isOutlier'] = ~df['valor_unitario'].between(lower_bound, upper_bound)
    df = df[~df.isOutlier]

    # Vectorized calculation
    df['indice'] = (df['valor_unitario']-lower_bound)/(upper_bound-lower_bound)*2000
    df = df.astype({'indice': 'int64'})

    return df

You would then call limites, define the returned values to some variables (as it returns the lower and upper bounds) and pass those variabels to indice
import calculo_indice as indice

# Assign lower bound and upper bound to variables `lb` and `ub` respectively
lb,ub = indice.limites(df, 2)

df = indice.indice(df, lower_bound=lb, upper_bound=ub)


text:
Q: Application could not load requested class : com.mysql.cj.jdbc.Driver     Ιουν 10, 2020 2:57:56 ΜΜ org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate Core {5.2.0.Final}
    Ιουν 10, 2020 2:57:56 ΜΜ org.hibernate.cfg.Environment <clinit>
    INFO: HHH000206: hibernate.properties not found
    Ιουν 10, 2020 2:57:56 ΜΜ org.hibernate.cfg.Environment buildBytecodeProvider
    INFO: HHH000021: Bytecode provider name : javassist
    Ιουν 10, 2020 2:57:56 ΜΜ org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
    INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
    Ιουν 10, 2020 2:57:56 ΜΜ

    org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
    WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
    Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
        at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
        at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:723)
        at com.luv2code.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:20)
    Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.cj.jdbc.Driver]
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
        at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:161)
        at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:117)
        at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:73)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
        ... 14 more
    Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.cj.jdbc.Driver
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:217)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:348)
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
        ... 25 more

Anyone could help me with these errors?
I am trying to write data on database through hibernate, I add the jar files to my project (Right click->properties->Libraries
I use my-sql-coonector-java-5.1.49 and hibernate 5.2.

A: Look at this.

The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. The old class name has been deprecated.

It looks like you should use the old class name com.mysql.jdbc.Driver with my-sql-coonector-java-5.1.49 or as a better alternative I would suggest to use a 8.0 version of mysql jdbc driver.


text:
Q: mysql trigger not working on insert Table: items
Create Table:
CREATE TABLE `items` (
  `ite_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `itemName` varchar(40) DEFAULT NULL,
  `itemNumber` int(10) unsigned NOT NULL,
  PRIMARY KEY (`ite_id`),
  UNIQUE KEY `itemName` (`itemName`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

delimiter |

create trigger item_beforeinsert before insert on items
    for each row begin
    if new.itemNumber < 50 then
        set new.ite_id = null;
    end if;
end;
|

now the following command doesn't cause a trigger
insert items( itemname, itemnumber) values ( 'xyz', 1 );

any help would be very much appreciated, thanks!

A: It'd be
insert INTO items( itemname, itemnumber) values ( 'xyz', 1 );

also, since you have set ite_id as NOT NULL, you can't use a set new.ite_id = null;

A: For auto incremented primary key fields you can pass NULL value while inserting. MySQL automatically assigns auto generated value. It is not an error setting up NULL to it BEFORE insert. And hence trigger didn't fire an error.
Example:
insert into items( ite_id, ... ) values ( null, ... );

The above statement is valid and works, since ite_id field is primary key with auto increment.

A: Your ite_ID is not null and you want to set it null with your trigger, beside that it's auto increment, so you wont be able to 'control' all the values to assign to that field, I.E it wont overwrite values


text:
Q: How do I create a C# array using Reflection and only type info? I can't figure out how to make this work:
object x = new Int32[7];
Type t = x.GetType();

// now forget about x, and just use t from here.

// attempt1
object y1 = Activator.CreateInstance(t); // fails with exception

// attempt2
object y2 = Array.CreateInstance(t, 7);  // creates an array of type Int32[][] ! wrong

What's the secret sauce?  I can make the second one work if I can get the type of the elements of the array, but I haven't figured that one out either.

A: You need Type.GetElementType() to get the non-array type:
object x = new Int32[7];
Type t = x.GetType();
object y = Array.CreateInstance(t.GetElementType(), 7);

Alternatively, if you can get the type of the element directly, use that:
Type t = typeof(int);
object y = Array.CreateInstance(t, 7);

Basically, Array.CreateInstance needs the element type of the array to create, not the final array type.

A: Just to add to Jon's answer. The reason attempt 1 fails is because there's no default constructor for Int32[]. You need to supply a length. If you use the overload, which takes an array of arguments it will work:
// attempt1
object y1 = Activator.CreateInstance(t, new object[] { 1 }); // Length 1


text:
Q: How to check the float decimal point is not longer than 0.00001? C# I am trying to limit the user input a number within 5 decimal points(e.g. 0.00007, 1.23456), if user input more than 5 decimal points, it will show a error message.
How can I check it that is it longer than 5 dc?
Thanks
public boolean isDc(float userInput)
{
    if(/** if userinput is within 5 dc**/)
         return true;
    else
         MessageBox.show("You should input within 5dc(E.g. 0.00001, 1.12345)");

    return false;
}

A: This might do the trick for you but the userInput should be decimal
if(BitConverter.GetBytes(decimal.GetBits(userInput)[3])[2] == 5)
{
   //Show the error message
}

This will only check that if you have 5 decimal places or not. You can have a look at Find number of decimal places in decimal value regardless of culture and thus
First way could be
public boolean isDc(decimal userInput)
{
    if(BitConverter.GetBytes(decimal.GetBits(userInput)[3])[2] == 5)
         return true;
    else
         MessageBox.show("You should input within 5dc(E.g. 0.00001, 1.12345)");

    return false;
}

or
public boolean isDc(float userInput)
{
    decimal outdc;
    if(decimal.TryParse(userInput.ToString(), out outdc))
    {
        if(BitConverter.GetBytes(decimal.GetBits(outdc)[3])[2] == 5)
             return true;
        else
             MessageBox.show("You should input within 5dc(E.g. 0.00001, 1.12345)");
    }
    return false;
}

A:  private Boolean isDc(string userInput)
        {
            var num = Decimal.Parse(userInput); //Use tryParse here for safety
            if (decimal.Round(num, 5) == num)
                return true;
            else
                MessageBox.Show("You should input within 5dc(E.g. 0.00001, 1.12345)");

            return false;
        }


text:
Q: Get rid of import in Groovy Unit Test in IntelliJ Is it possible to get rid of from import statements in JUnit tests written in Groovy? I know you could do it in groovy scripts  in GroovyShell by changing compiler configuration or import customizer.
I like to do same thing but:

*

*IntelliJ should still provide code highlight and auto complete (I think I could do this
with gdsl file feature of IntelliJ)

*I could still use IntelliJ's JUnit window to see which tests failed and which are passed.


text:
Q: batch script to capture all elements whose child element having CDATA and output to xml file I am looking for a batch script that can copy all parent elements whose child elements having <![CDATA[....]]>in an xml file and output to a new xml file.
Here is my xml file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books xmlns:jndi="urn:jboss:jndi-binding-service:1.0">
    <jndi:bindings>
        <jndi:binding name="property/category/books/book1">
            <jndi:value type="java.lang.String">
                <![CDATA[
                  <?xml version="1.0" encoding="ISO-8859-1"?>
                  <urlConfig>
                    <defaults catID="1983" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book2">
            <jndi:value type="java.lang.String">
                abc.com
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book3">
            <jndi:value type="java.lang.String">
                <![CDATA[
                    <?xml version="1.0" encoding="ISO-8859-1"?>
                    <urlConfig>
                      <defaults catID="1989" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book4">
            <jndi:value type="java.lang.String">
                <![CDATA[
                <?xml version="1.0" encoding="ISO-8859-1"?>
                <urlConfig>
                      <defaults catID="1990" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book5">
            <jndi:value type="java.lang.String">
                abc.com
            </jndi:value>
        </jndi:binding>
    </jndi:bindings>
</books>

So the expected output has to capture all the parent elements whose child elements having <![CDATA[...]]>. In this example the parent elements are <jndi:binding name="property/category/books/book#">.
Expected output is: output.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books xmlns:jndi="urn:jboss:jndi-binding-service:1.0">
    <jndi:bindings>
        <jndi:binding name="property/category/books/book1">
            <jndi:value type="java.lang.String">
                <![CDATA[
                  <?xml version="1.0" encoding="ISO-8859-1"?>
                  <urlConfig>
                    <defaults catID="1983" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book3">
            <jndi:value type="java.lang.String">
                <![CDATA[
                    <?xml version="1.0" encoding="ISO-8859-1"?>
                    <urlConfig>
                      <defaults catID="1989" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
        <jndi:binding name="property/category/books/book4">
            <jndi:value type="java.lang.String">
                <![CDATA[
                <?xml version="1.0" encoding="ISO-8859-1"?>
                <urlConfig>
                      <defaults catID="1990" subcatID="1987" method="get" onError="keep"/>
                    <urlKey name="logo" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                    <urlKey name="logo1" altURL="def.com">
                      <address>abc.com</address>
                    </urlKey>
                  </urlConfig>
                ]]>
            </jndi:value>
        </jndi:binding>
    </jndi:bindings>
</books>

I treid to use xml processor, xslt to process the xml file but somehow xslt processors are not easy to process xml file if the file contains CDATA sections in it.

A: this might help you:
@ECHO OFF &SETLOCAL
set "infile=file.xml"
set "outfile=file.new"
rem IMPORTANT! Put a [tab] and a [space] behind the colon to the delims.
for /f "tokens=1-3delims=<>:     " %%a in ('findstr /nc:"jndi:binding" /c:"![CDATA[" /c:"/jndi:binding" "%infile%"') do (
    if "%%~b:%%~c"=="jndi:binding" set "start=%%a"
    if "%%~b"=="![CDATA[" set "found=%%a"
    if "%%~b:%%~c"=="/jndi:binding" (
        if defined found call set "line=%%line%%%%start%%,%%ap;"
        set "start="
        set "found="
    )
)
sed -n "%line%" "%infile%">"%outfile%"
type "%outfile%"

sed for Windows