text:
Q: Keep connection open and read data till it is forcefully closed When my activity loads, I am connecting to a web service. As and when I get the response from service, I again call then service and so on.
@Override
protected void onCreate(Bundle savedInstanceState) {
….
callWebMethod();
}

// Called on getting response
@Override
public void run(String value) {
….
callWebMethod();
}

This is how I am connecting to service
HttpGet request = new HttpGet(url + combinedParams);
HttpClient client = new DefaultHttpClient(httpParameters);

    HttpResponse httpResponse;

        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);
            response = StringUtils.remove(response, "\n");
            response = StringUtils.remove(response, '"');
        }

Is it possible that I connect to the service only once at the start, then the connection remains open and application keeps on reading data from service till connection is forcefully closed.
Please let me know if more code is required.
Update: I then tried with ClientConnectionManager but still connection is again and again initialising. Though it is getting data. What I want is that connection remains open, and keeps on reading data from service.
HttpParams httpParameters = new BasicHttpParams();
    SharedPreferences preferences = context.getSharedPreferences(
            "MyPreferences", Context.MODE_PRIVATE);

    int timeoutConnection = Integer.parseInt(preferences.getString(
            "timeout", "60")) * 1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);

    HttpConnectionParams.setSoTimeout(httpParameters, 2000);
    System.setProperty("http.keepAlive", "true");
    HttpClient client = new DefaultHttpClient(httpParameters);

    ClientConnectionManager mgr = client.getConnectionManager();
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(
            client.getParams(), mgr.getSchemeRegistry()),
            client.getParams());
    while (true) {

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                response = StringUtils.remove(response, "\n");
                response = StringUtils.remove(response, '"');
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        callback.run(response);  // This calls activity callback function.
                    }
                });

                // Closing the input stream will trigger connection release
                // instream.close();
            }

        } catch (ConnectTimeoutException e) {
         ….
         }

A: you just need to close the InputStream you get from HttpResponse.getEntity().getContent() after you are done using/reading-it. This will officially indicate the end of your current request.
You can then proceed to execute another request, the same HttpClient connection will be used.
Add a close
        InputStream instream = entity.getContent();
        response = convertStreamToString(instream);
        // close the InputSream
        instream.close()

        // you can now reuse the same `HttpClient` and execute another request
        // using same connection
        httpResponse = client.execute(request);

A:
Is it possible that I connect to the service only once at the start,
  then the connection remains open...

The web server has a role to play in this. If the server "ends" the HTTP response, there is no further communication going to happen on same HTTP call.
It is possible to keep an HTTP connection open, with help of server. In this case, server never really ends the response but keeps writing data to response stream after some time intervals, so client can keep listening.
The new replacement for the above technique is a duplex socket connection. Both client and server can send and receive messages over a socket. Again, both client and server have to support it properly, and necessary handling for connection drops etc has to be there.
There are android specific client implementations available like https://github.com/nkzawa/socket.io-client.java  that take care of most of connection management for you.

A: I think you could try to use the AsyncTask class to try to keep your thread open and do what you want, like this:
public class ConnectToWebService extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) { ... }

    @Override
    protected void onPostExecute(final Boolean success) { ... }

    @Override
    protected void onCancelled() { ... }
}

Check the API documentation for more information ;)

A: It sounds like what you really need is a socket connection (see here). A socket will stay connected and allow you to stream data back and forth with the socket server until you are finished.


text:
Q: Call Child class method from Parent class method Consider the following case
class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}

If I create an object of the class B, and i try to use function X as it is extended from A, is it possible that the function X can access the function Y of the calling object of class B.

A: you could but this must be met

*

*A class is abstract

*Y method is abstract too

Example:
abstract class A {
    void X() {
        Y();
    }

    abstract void Y();
}

class B extends A {
    @Override
    void Y() {
        System.out.println("Hello from B class");
    }
}

in that form every time class A calls Y, it will actually invoke an implememted method of the abstract method Y

A: only if A have a method with the same signature (or a super class has one), otherwise it can't find/use a method that is not defined in his context.
This could be done

*

*with an implementation of the method in A

*by using an abstract method in A(see ΦXocę 웃 Пepeúpa ツ answer).

The first solution is not always the best, as you could have a method that do nothing in A like :
class A{
    void Y(){}
}

Note : if you have Y() in both class, the polymorphism assure you that an instance of B will use his own implementation.
The second solution can be problematic if you want to be able to create instance of A as it will be abstract.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Committing an insert with Transactional decorator I have the following save method which inserts and commits the object into my database:
 public void save() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    session.save(this);
    session.getTransaction().commit();

}

However, if I use the decorator, it never actually commits to the database:
@Transactional
public void save() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.save(this);

}

Is there something additional I need to do in order for connection to commit it?

A: The @Transactional annotation will already create a transaction using a proxy.
So you don't need to open a new session from your sessionFactory, you just need to get the current one.
This should work for you:
Session session = HibernateUtil.getSessionFactory().getCurrenstSession();
session.save(this);

Please let me know if it worked :)


text:
Q: Run a web scraper most efficient in React / Node I'm running a web scraper in my React (MERN STACK) web app. I'm using request-promise (rp) and cheerio library to fetch url/html.
I have this method to run in componentWillMount() every times a user goes to the X page. The array it fetches are around 80-150 elements long with 4-5 objects. But it doesn't seem very efficient to run it every time a user enters that X page. So is there a better way to do it? Sometimes it takes a while before the array "loads" / from 5 seconds and up to 30-40 seconds at most.
One option I wondered if was possible is a fetch method running every 15 minutes (for the whole server) or so and posting it to my MongoDB, then retrieving when user enters that X page instead. Is that possible in any way? Like a extern method without having anyone on the page?
Or is there any script you could run on your desktop to run every 15 minutes to push data to database?

A: Ended up using Heroku Scheduler to set up a cron job, works great.


text:
Q: Rails 4 and Turbolinks - Meta Tags not changing I have a Rails 4 app with turbo-links enabled, but I can't get the meta tags to refresh when changing the page ( not a full refresh ) . I read that the meta-tags need to be included before the javascript that loads the turbo-links but it has no effect. A full refresh does the job, but unfortunately this is not what i search for.
layout/application.html.haml
%html
  %head
    %title= "Title"
    - if content_for?(:meta_description)
      %meta{content: (yield :meta_description), name: "description"}/
      %meta{content: (yield :meta_keywords), name: "keywords"}/
    = stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true
    = javascript_include_tag "application", "data-turbolinks-track" => true

    = csrf_meta_tags
  %body{class: params[:controller].gsub("/", "-"), id: 'top'}
    = render "shared/header"
    .body-content
      = render "shared/flash"
      = yield
    = render "shared/footer"
    = render "shared/analytics"

helpers/application_helper.rb

def meta_tag(title, description)
content_for :meta_keywords do
  title
end

content_for :meta_description do
  description
end

end

And this is how I call them
= meta_tag('here s my title', 'and the keywords')

Thanks

A: How Turbolinks works
Turbolinks is designed to keep the <head> tag the same and merely replaces the <body> tag with the contents of the requested page via an AJAX request. Since your <meta> tags are located in the <head>, they won't be changed via a Turbolinks request.
What about SEO?
From an SEO perspective, you don't need to worry about the <meta> tags being updated on a Turbolinks request because the search engine crawlers will always do a full page request and won't execute the Turbolinks javascript.
From a user's perspective, the only tag in the <head> that needs to change for each request is the <title> tag, so special handling for that was built-in to Turbolinks itself.
Will this behavior ever change?
This "issue" has been raised and shot down a couple times, each time being declared a non-issue by DHH himself, so I wouldn't count on this behavior changing any time soon.
See:

*

*https://github.com/rails/turbolinks/issues/81

*https://github.com/rails/turbolinks/pull/165

A: It's a TurboLinks Problem
By design, Turbolinks basically keeps the <head> of your page the same & calls the <body> of your document via ajax if it's going to remain the same (you're using the same controller / action). It's some crazy thing to maintain application performance
Here is a good explanation of Turbolinks

I've had a similar problem to this with Javascript, and was able to use the Jquery-Turbolinks gem to keep JS rendering
For your meta tags, although I don't know a solution off hand, I managed to find a decent gem you might benefit from: MetaMagic. It allows you to define meta tags in the view, kind of like how the content_block facility works. This should be loaded on every http request

A: I extend the current turbolinks js ;)
It will replace meta tags and canonical link!
https://github.com/philklei/turbolinks

A: Have a look on meta-tags gem
"Using with pjax" section


text:
Q: Umbraco Form - Remove time from Datepicker date in email I have a form that contains a Datepicker and in the email that is sent on submission the date is formatted with a time.
How do I remove the time from the date?
Thanks

A: You can either change the property to just Date, without the time element, or you can use ToString() method for the DateTime within C#:
https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
The format without time would look something like this:
yourDate.ToString("DD/MM/YYYY");


text:
Q: Binary to Ascii I want to convert a binary string into ASCII. The string contains 588 token {0, 1}.
I've tried it with binascii: https://docs.python.org/3/library/binascii.html
Or like this: Convert binary to ASCII and vice versa
Sample-Code:
sentence ="0b0101010101..."
n = int(sentence, 2)
print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())

Output:
Error: print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 1: invalid start byte

Edit: this is now my solution any ideas to optimize the code?
 sentence ="0b0101010101..."
 length=(int(len(sentence)/8)*8)+2
 n = int(sentence[:length:1], 2)
 print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode("utf_8", "ignore"))

SOLVED!


text:
Q: How can i make widgets overflow to make a scrollbar appear in Qt? The structure of my widgets is :
QWidget customized to be a panel with rounded borders.
To contain an area with scrollbar inside the borders with a margin, then I put this inside:
QScrollArea with a QVBoxLayout  (vertically adding content)
Then I add inside of it a series of :
QGroupBox with title with spacing 0, and a QFormLayout
The formlayout doesn´t work as I thought it would. The widgets inside are the labels + spinboxes, all of them.
Here's an image:

First. They are not centered. I don´t know why.
Second. They are all given the same fixed size, as I told them, but they are piled anyway, not squashed, so they hide each other. Why doesn´t it stay that size and the parent QScrollArea shows the scrollbar outside?. That´s what i want.
I don´t want the contents to be squashed or stretched. I want them to be on the top. If the screen is very big, the panel will be long, but the contents will be on the top, allways with the same size.

Somebody requested the code, so i copy it here, but the code it really big... I think it's more confusing. But well, ill remove the lines with no meaning. Here is the part you see in that box:
  // THE PANEL OUTSIDE (A QWIDGET) is mainParametersLayout_. This particular scroll bar inside
  // is cameraModeParametersPanel_

  cameraModeParametersPanel_ = new QScrollArea();
  cameraModeParametersPanel_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  cameraModeParametersPanel_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  mainParametersLayout_->addWidget( cameraModeParametersPanel_ );

  // HERE THERE ARE TWO MORE QGROUP BOXES. THE ONE THAT DOESN´T STAY THE WAY I SHOWED IS THIS.

  QVBoxLayout* mainCameraLayout = new QVBoxLayout(cameraModeParametersPanel_);
  mainCameraLayout->setSpacing(5);

  // GROUP BOX
  QGroupBox* activeCameraParametersGroup = new QGroupBox();
  activeCameraParametersGroup->setObjectName( parametersContainerName );
  activeCameraParametersGroup->setTitle(strings->cameraModeCameraParamsTitle);
  mainCameraLayout->addWidget( activeCameraParametersGroup );

  // LAYOUT
  QFormLayout* paramLayout = new QFormLayout( activeCameraParametersGroup );
  paramLayout->setRowWrapPolicy(QFormLayout::DontWrapRows);
  paramLayout->setFormAlignment( Qt::AlignHCenter | Qt::AlignTop );
  paramLayout->setLabelAlignment(Qt::AlignRight);

  // Iso : Spin Integer
  isoSpin = new SmartIntSpinButtons( control->getMinISO(), control->getMaxISO() );
  isoSpin->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  paramLayout->addRow(strings->cameraISOCapString, isoSpin);

  // FStop: Spin Double
  fstopSpin = new SmartDoubleSpinButtons( control->getMinFStop(), control->getMaxFStop(), 2);
  fstopSpin->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  paramLayout->addRow(strings->cameraFStopString, fstopSpin);

  // some other spins here...

  // Camera position: 3 Spin Double (X,Y,Z)
  camPosSpinX = new SmartDoubleSpinButtons( control->getMinCamPos(), control->getMaxCamPos(), 1);
  camPosSpinY = new SmartDoubleSpinButtons( control->getMinCamPos(), control->getMaxCamPos(), 1);
  camPosSpinZ = new SmartDoubleSpinButtons( control->getMinCamPos(), control->getMaxCamPos(), 1);

  camPosSpinX->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  camPosSpinY->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  camPosSpinZ->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

  paramLayout->addRow( new QLabel( strings->cameraPositionString ) );
  QHBoxLayout* positionLy = new QHBoxLayout();
  positionLy->addWidget( camPosSpinX );
  positionLy->addWidget( camPosSpinY );
  positionLy->addWidget( camPosSpinZ );
  paramLayout->addRow( positionLy );

  // Target Position: 3 Spin Double( X,Y,Z )
  camTargetPosSpinX = new SmartDoubleSpinButtons( control->getMinCamTarget(), control->getMaxCamTarget(), 1);
  camTargetPosSpinY = new SmartDoubleSpinButtons( control->getMinCamTarget(), control->getMaxCamTarget(), 1);
  camTargetPosSpinZ = new SmartDoubleSpinButtons( control->getMinCamTarget(), control->getMaxCamTarget(), 1);

  camTargetPosSpinX->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  camTargetPosSpinY->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  camTargetPosSpinZ->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

  paramLayout->addRow( new QLabel( strings->cameraTargetPositionString ));
  QHBoxLayout* targetLy = new QHBoxLayout();
  targetLy->addWidget( camTargetPosSpinX );
  targetLy->addWidget( camTargetPosSpinY );
  targetLy->addWidget( camTargetPosSpinZ );
  paramLayout->addRow( targetLy );

  // and the resoultion spins, which are the same style like the last one (but only X and Y).

Now comes the stylesheet of all:
/* THE PANEL THAT CONTAINS THE QSCROLLBAR OUTSIDE */

SmartPanel
{
    background-image: url(:/resources/images/containers/panel_bg.png);
    background-repeat: repeat-y;
    background-position: left top;
    background-color: white;
    border: 1px solid #aaa;
    border-radius: 10;
    min-width: 20px;
    padding: 5px;

}

QScrollArea#parametersPanelScrollArea
{
    background: transparent;
    border: none;
}

/* the qgroupbox */

QGroupBox#parametersContainer
{
  background-color: white;
  padding-top: 25px;
  border-style: solid;
  border-width: 1px;
  border-color: #aaa;
  border-radius: 10px;
}

QGroupBox#parametersContainer::title  {
    subcontrol-origin: margin;
    subcontrol-position: top center;
    border: 1px solid #aaa;
    margin-top: -5px;
    padding: 8px 5px 5px 5px;
    font-size: 18px;
    border-radius: 5px;
}

/* ------------------ SPINBOX WIDGET ------------------------------------------*/

QWidget#intSpin, QWidget#doubleSpin
{
    min-height: 20px;
    border: 1px solid #ccc;
    padding: 0px;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #ddd, stop:1 #fff);
}

QPushButton#upSpinBtn,
QPushButton#downSpinBtn
{
    border-radius: 0px;
    /*background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #ddd, stop:1 #fff);*/
    background-repeat: no-repeat;
    background-position: center;
    border: none;
}

QPushButton#upSpinBtn
{
    background-image: url(:/resources/images/buttons/up_sm_arrow.png);
}

QPushButton#downSpinBtn
{
    background-image: url(:/resources/images/buttons/down_sm_arrow.png);
}

A: QScrollArea is not a container. QScrollArea is a "scrolling view" for another widget. You shouldn't set up layout on QScrollArea. You should create widget, fill it with proper layout and then use QScrollArea::setWidget(QWidget *) to make it scrollable.


text:
Q: Wildcard SSL certificate with subdomain redirect in Kubernetes I've configured my Kubernetes to use one wildcard SSL certificate to all my apps using cert-manager and letsencrypt, now the problem is that I can't configure subdomain redirects cause Ingress is kinda "stiff". Here's how I'm trying to achieve this:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: my-wildcard-ingress
  namespace: mynamespace
  annotations:
    kubernetes.io/ingress.class: nginx
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod
    certmanager.k8s.io/acme-challenge-type: dns01
    certmanager.k8s.io/acme-dns01-provider: azuredns
    ingress.kubernetes.io/force-ssl-redirect: "true"
    ingress.kubernetes.io/ssl-redirect: "true"
spec:
  rules:
  - host: "domain.com"
    http:
      paths:
      - path: /
        backend:
          serviceName: some-service
          servicePort: 3000
  - host: somesub.domain.com
    http:
      paths:
      - path: /
        backend:
          serviceName: some-other-service
          servicePort: 80
  - host: othersub.domain.com
    http:
      paths:
      - path: /
        backend:
          serviceName: one-more-service
          servicePort: 8080
  - host: "*.domain.com"
    http:
      paths:
      - path: /
        backend:
          serviceName: default-service-to-all-other-non-mapped-subdomains
          servicePort: 8000

  tls:
  - secretName: domain-com-tls
    hosts:
     - "*.domain.com.br"

The problem is that Ingress ignores the declared subdomain redirects just because they're not listed in the "tls:hosts" section. And if I do put them there, it tries to issue the SSL certificate using the wildcard and the other subdomains as well in the same cert, which causes the issuer to refuse the order, saying the obvious: "subdomain.domain.com and *.domain.com are redundant"
Is there any other way that I can declare those redirects and force them to use my SSL wildcard certificate?

A: Well, for anyone who's having this kind of trouble, I've managed to solve it (not the best solution, but it's a start). For this, I'll be using cert-manager and letsencrypt.
First, I've created a ClusterIssuer to issue for my certs with letsencrypt:
apiVersion: certmanager.k8s.io/v1alpha1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod-dns
spec:
  acme:
    dns01:
      providers:
      - azuredns:
          clientID: MY_AZURE_CLIENT_ID
          clientSecretSecretRef:
            key: client-secret
            name: azure-secret
          hostedZoneName: mydomain.com
          resourceGroupName: MY_AZURE_RESOURCE_GROUP_NAME
          subscriptionID: MY_AZURE_SUBSCRIPTION_ID
          tenantID: MY_AZURE_TENANT_ID
        name: azuredns
    email: somemail@mydomain.com
    privateKeySecretRef:
      key: ""
      name: letsencrypt-prod-dns
    server: https://acme-v02.api.letsencrypt.org/directory

Then I've created a fallback ingress to all my subdomains (this one will be the cert generator):
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    certmanager.k8s.io/acme-challenge-type: dns01
    certmanager.k8s.io/acme-dns01-provider: azuredns
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod-dns
    ingress.kubernetes.io/force-ssl-redirect: "true"
    ingress.kubernetes.io/ssl-redirect: "true"
    kubernetes.io/ingress.class: nginx
  name: wildcard-ingress
  namespace: some-namespace
spec:
  rules:
  - host: '*.mydomain.com'
    http:
      paths:
      - backend:
          serviceName: some-default-service
          servicePort: 80
        path: /
  tls:
  - hosts:
    - '*.mydomain.com'
    - mydomain.com
    secretName: wildcard-mydomain-com-tls

Notice that I've declared at the TLS section the wildcard AND the absolute paths, so the cert will be valid for the URLs without subdomains too.
At this point, any requests to your domain, will be redirected to "some-default-service" with SSL(cert-manager will issue for a new cert as soon as you create the fallback ingress. This can take a while once cert-manager dns01 issuer is not mature yet), great!!!
But, what if you need to redirect some specific subdomain to another service? No problem (since they're running on the same namespace), all you have to do is to create a new ingress to your subdomain, pointing it to your existing wildcard-mydomain-com-tls cert secret:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ingress.kubernetes.io/force-ssl-redirect: "false"
    ingress.kubernetes.io/ssl-redirect: "true"
    kubernetes.io/ingress.class: nginx
  name: somesubdomain-ingress
  namespace: some-namespace
spec:
  rules:
  - host: somesubdomain.mydomain.com
    http:
      paths:
      - backend:
          serviceName: some-other-service
          servicePort: 8080
        path: /
  tls:
  - hosts:
    - somesubdomain.mydomain.com
    secretName: wildcard-mydomain-com-tls

Easy peasy lemon squeezy!!! Now your somesubdomain.mydomain.com overrides your fallback rule and sends the user to another app. The only thing you should notice here is that the secret is valid only for "some-namespace" namespace, if you need to use this cert in another namespace, you could:

*

*Copy the secret from namespace "some-namespace" to "other-namespace". If you do this, remember that cert-manager will NOT renew this cert automatically for "other-namespace", so, you'd have to copy the secret again, every time your cert expires.

*Recreate the fallback ingress to every namespace you have, so you'd have a new cert for each of them. This approach is more ingress verbose, but, it's fully automatic.

I guess that's it. Hope someone out there can benefit from this info.
Cheers

A: So the best course of action here is probably to just not use ingress-shim to manage your Certificate resource.
Instead, you can manually create a Certificate resource and then reference the secret it produces in all of your ingresses.
We are exploring options to workaround this limitation in ingresses at the moment, however there has so far not been any progress!


text:
Q: how do i select all tags in my twig template in grav? I have the following code in my default.html.twig file to display all the titles of the blog pages with the tag : dog:

        {% for post in taxonomy.findTaxonomy({'tag':'dog'}) %}

{{ post.title }}(0)

        {% endfor %}

What i would really like to do is find all the tags and not just the dog tag, so i did the following:

        {% for post in taxonomy.findTaxonomy({'tag':'all'}) %}

{{ post.title }}(0)

        {% endfor %}

I changed the dog to all , but this does't really give me any results. I checked the documentation here for findTaxonomy , but it does't help much , also in the  inside the
 , I would like to show how many articles for this perticular tag have been posted , eg. if there are five articles for the tag popcorn the html spitedd out should be:

popcorn (5)
. How do i achieve this ?

A: What about not using findTaxonomy and just iterate on all elements like this:
    {% for post in yourCollection %}

{{ post.title }}(0)

    {% endfor %}

Eventually using an "if" statement on post.tag in case you want to check something (defined value, not '', etc).


text:
Q: Give simple HTTP 401 when trying to access some part of the web instead of redirect to login page I've made a spring page using Spring Security. When I try to access any url inside this page, if the session is not set, it will redirect you to the login page: /login. This is fine, but now I've made a simple http rest api inside this web. What I want if I try to access any url inside /api/** just drop the 401, instead of sending a HTTP redirect to login.
I have made a Filter with preHandle:
public class BusinessKeyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.isAuthenticated()
            &&
            // when Anonymous Authentication is enabled
            !(auth instanceof AnonymousAuthenticationToken)) {
       // other stuf ....
        }
    } else {
        if (request.getRequestURI().startsWith("/api")) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
    return true;
}
}

But in this case request URI is already /login
My configuration:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .invalidSessionUrl("/login?invalid")
                .and().csrf().disable().formLogin()
                .loginPage("/login")
                .failureHandler(customAuthenticationFailureHandler)
                .defaultSuccessUrl("/loggedIn")
                .usernameParameter("email")
                .passwordParameter("password")
                .successHandler(authenticationSuccessHandler)
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied")
        ;
    }

A: I would recommend not mixing your previous security configuration with your new REST api config. You could do the following:
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Configuration
    @Order(1)
    public static class WebConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatchers("/web")
            ...
           /* Your previous config would go here */
        }
    }

    @Configuration
    @Order(2)
    public static class ApiConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatchers("/web")

            ... /* Your /api configuration goes here */

                .exceptionHandling()
                  .authenticationEntryPoint(customAuthenticationEntryPoint)

        }

        @Bean
        AuthenticationEntryPoint customAuthenticationEntryPoint() {
            return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
        }
    }
}

This way, you could configure your rest api separately. Now you can have different a authentication entry point for your rest api. The fact is that you're most likely going to want to also provide a custom failure handler and success handler, which you can now do easily, and which will remain separate from the rest of your web application.


text:
Q: Difference between /(a|b)/ and /[ab]/ in JavaScript split() using regex I just got in a situation where I wanted to split a string at each occurrence of ; or a newline. I wanted to make sure this would not leave any empty array elements in, so I decided to use regex to include a string as long as possible.
I first tried using foo.split(/(\n|\r|;)+/), but this strangely did not work as expected with double enters. Using the (for what I know) identical syntax foo.split(/[\n\r;]+/) did work as expected though.
Here's an example:

var foo = "test;\nexample;\n\ndouble enters;\nand without semicolon\nend;\n";
console.log(foo.split(/[\n\r;]+/));
console.log(foo.split(/(\n|\r|;)+/));
//and to show that the matching strings are indeed equal:
console.log(foo.match(/[\n\r;]+/g));
console.log(foo.match(/(\n|\r|;)+/g));

document.write('<pre>'+foo+'</pre>'); //demonstrating what the string looks like.

So as you can see in your console if you run that snippet, the regexes should be identical here, since they match() the exact same characters. The output when splitting the string is completely different though.
The same goes wrong when replacing the matched characters with A and B for example (replacing all newlines with A, semicolons with B). Even then, these 2 regex splits have different outcome.
So my question is: does anyone know what causes this mysterious behaviour?

A: It's because when you use a capturing group with the .split() method, the matched contents of the capturing group are included in the resulting array.
From MDN:

If separator contains capturing parentheses, matched results are returned in the array.

If you use a non-capturing group, the results will be the same:
foo.split(/(?:\n|\r|;)+/)

Example:

var foo = "test;\nexample;\n\ndouble enters;\nand without semicolon\nend;\n";
console.log(foo.split(/[\n\r;]+/));
console.log(foo.split(/(?:\n|\r|;)+/));
//and to show that the matching strings are indeed equal:
console.log(foo.match(/[\n\r;]+/g));
console.log(foo.match(/(\n|\r|;)+/g));


text:
Q: Choose Stylesheet on Browser's side or on Server's side? my problem is that I have to use different stylesheets for different browsers and I have to choose between 2 methods:

*

*Choose with javascript on browser's side

*Choose on server's side based on HTTP request.
Which is better and why?
(It is a university project not a public site)

A: In favor of client side: You can serve static pages instead of having to run a script, so it's less server overhead.
In favor of server side: Will work if the user has Javascript disabled.


text:
Q: Replacing multiple values in a structure I have a structure with sample being a numeric vector. I would like to replace the numbers in sample by sample/2. However, I do not know how to overcome the following error:

Scalar structure required for this assignment.

Any suggestions are more than welcome.
Example:
field1 = 'event';
value1 = {'A', 'B', 'C', 'D'};
field2 = 'sample';
value2 = 22;

A = struct(field1, value1, field2, value2);

What I want to do:
A.sample = round([A.sample]/2,0);

A: You should use the deal function to distribute your calculated matrix to the elements of your structure:
sampleCell = num2cell(round([A.sample]/2,0)); % first convert result to cell, to comply with the `deal` syntax
[A.sample] = deal(sampleCell{:});


text:
Q: Reusing an Asio connection I am working on a project currently where I have a web-server.  I have to add the ability so that for each request, I need to send multiple requests to other servers, get responses, and send back results to the original client.  These servers are high throughput, so I was getting worried about the number of sockets as well as the speeds of setting up new threads/sockets for sending out many requests over many sockets.  So I started thinking that have a single(or a few connections), open to each client would help solve this problem.  I wasn't sure how persistent connections and boost ASIO worked though.  Some questions I had:
-How can I set keep alive times using ASIO tcp sockets.
-Can I send out multiple concurrent requests over the same socket? Would I run into an issue with the order of the results(Each result should have an Id, so I don't mean order as in results being sent out of order, but more packet order, if a response is more than one packet, will I have a problem with the order of the packets).
All requests are HTTP GET/POST requests if that matters too.
Any information in this subject would be appreciated.  Thanks.

A: A TCP socket acts as a data stream, the data you write on one end will be received in the same  order in the other end. You can send multiple requests over the same socket if your protocol can handle it.
You mention concurrent requests, therefore you need to be very careful to not interleave the write calls of two different requests. If you can ensure that each result is written atomically, then I see no problem in using a socket for multiple requests (you can do that with a reply queue).
You can set the standard socket keep alive here.


text:
Q: Using Javascript to Create Window Off the Screen? I was reading this article where it talks about hackers using Javascript to load windows off the screen:
https://blog.malwarebytes.com/cybercrime/2017/11/persistent-drive-by-cryptomining-coming-to-a-browser-near-you/
Here's a screenshot of what I'm talking about:
https://blog.malwarebytes.com/wp-content/uploads/2017/11/os_compare.png
I don't have a need for it anymore, but was trying to load windows like this for a project I was previously working on.
This was the closest I could get to it:
window.open("https://example.com/", "Example","width=10,height=10,left=10000,top=10000,status=no,toolbar=no,scrollbars=no,resizable=no,directories=no,location=no,menubar=no,fullscreen=no,visible=none");

What exactly was I missing when I tried doing it?


text:
Q: Thermal parameters for the LM1117 Looking at the datasheet for the LM1117 regulator, on page 18 to 20 there's a table of various layouts for copper cooling planes for the LM1117 in SOT-223 and TO-252 packages. Comparing figures 30 and 31 to table 2, I see a number of discrepancies:

*

*for layout 6, the one with the lowest thermal resistance, the table gives upper copper area \$1\textrm{in}^2\$, and 0 for bottom. However, the figures show no copper on top, only on the bottom.

*layout 2 has top copper area \$0.066\textrm{in}^2\$, 0 on bottom, and has thermal resistance of \$87 ^\circ \textrm{C}/\textrm{W}\$ for the TO-252. Layout 12 has the same pattern repeated on top and bottom, giving a thermal resistance \$89 ^\circ \textrm{C}/\textrm{W}\$. How can the thermal resistance increase when adding more copper to cool?

*On page 4, section 6.4., the table Thermal Information gives a junction-to-ambient thermal resistance \$45.1 ^\circ \textrm{C}/\textrm{W}\$, which is smaller than that reported for any of the layouts on pages 18 to 20. While this table doesn't specify for what layout/heatsinking this is, the footnote on the immediately preceding table says "All numbers apply for packages soldered directly into a PCB." Isn't this a contradiction?

So, my question is: am I seriously misreading/misinterpreting/confusing something here, or is the section in the end of the datasheet full of errors? If it's the latter, where can I find more reliable data to make sure I have enough cooling for my regulator?

A: I would take the lack of copper on the drawing for figure 6 as just being an error.
For layout 2 vs 12 there are two possibilities

*

*One is that measuring high thermal resistances is a bit of a pain and great accuracy is not to be expected.

*Copper is rather reflective in the far IR (and by reciprocity can be expected to have low emissivity), if they were running the thing hot enough to have significant cooling by radiation (Goes as the 4th power of absolute temperature) then it is quite likely that the bare FR4 is actually better then bare copper.
Junction to ambient often really means junction to heat transfer tab or pad (In other words, junction to infinite heatsink), you can probably confirm this from the derating curve and the junction temperature limit.

A:
So, my question is: am I seriously
  misreading/misinterpreting/confusing something

It is a very confusing datasheet.  The following is my interpretation.

for layout 6, the one with the lowest thermal resistance, the table
  gives upper copper area 1in2, and 0 for bottom. However, the figures
  show no copper on top, only on the bottom.

The patterns are confusing. The bottom view is of the component side, top view is of the opposite side.

How can the thermal resistance increase when adding more copper to
  cool?

There is copper on the component side and none on the opposite side. All patterns show copper on the component side even if it is not exposed (zero).

On page 4, section 6.4., the table Thermal Information gives a
  junction-to-ambient thermal resistance 45.1°C/W, which is smaller than
  that reported for any of the layouts on pages 18 to 20.

45.1°C/W is a different metric. It's the resistance for the package only.  In their App Note they say:

The junction-to-ambient thermal resistance, RθJA , is the most
  commonly reported thermal metric and is the most often misused. RθJA
  is a measure of the thermal performance of an IC package mounted on a
  specific test coupon. The intent of RθJA is to give a metric by
  which the relative thermal performance of a package can be compared.

Source: Semiconductor and IC Package Thermal Metrics
When the package is soldered to the board the thermal resistance of the  thermal pad, FR4, and copper is added the package resistance.


text:
Q: PostgreSQL - GROUP BY 10 minutes based in each row I have a problem difficult to solve, I think you can help.
I have a table with millions of records in which precise group every 10 minutes, based on the registry value, for example:

Record "01 | 2011/01/03 19:18:00.300" the time it needs to count the
  records is 19:18:00.300 to 19:28:00.299. With this process it will
  group records 01,02,03.
Record "04 | 2011/01/03 19:29:54.289" the time it needs to count the
  records is 19:29:54.289 to 19:39:54.288. With this process it will
  group records only the record 04.
Record "05 | 2011/01/04 14:43:43.067", the time he needs to count the
  records is 14:43:43.067 to 14:43:53.066. With this process it will
  group records 05,06,07.
Record "08 | 2011/01/04 14:57:55.608;" the time it needs to count the
  records is 14:57:55.608 to 15:07:55.607. With this process it will
  group records 08,09,10,11,12,13,14,15.

Input data:
ID   TS
01   2011/01/03 19:18:00.300
02   2011/01/03 19:18:00.503
03   2011/01/03 19:20:26.335
04   2011/01/03 19:29:54.289
05   2011/01/04 14:43:43.067
06   2011/01/04 14:50:10.727
07   2011/01/04 14:52:26.827
08   2011/01/04 14:57:55.608
09   2011/01/04 14:57:55.718
10   2011/01/04 14:59:13.603
11   2011/01/04 15:00:34.260
12   2011/01/04 15:02:55.687
13   2011/01/04 15:04:51.917
14   2011/01/04 15:06:24.760
15   2011/01/04 15:07:15.378

Output data:
ID  TS   Count
01   2011/01/03 19:18:00.300    3
02   2011/01/03 19:29:54.289    1
03   2011/01/04 14:43:43.067    3
04   2011/01/04 14:57:55.608    8

Does anyone have a solution to this problem?
Already, grateful for the attention.

A:
I have a table with millions of records in which precise group every
  10 minutes

tl;dr: for the impatient ones, see the last query in the answer, which is the real solution, the others are step by step on how to get there. Also, all queries + schemas are available at SQLFiddle, for those who want to play with.
The best solution for such problem, in my opinion, is to truncate each timestamp into the start of its 10 minutes, for instance, let's try to make the following conversion (original -> 10 minutes truncated):
13:10 -> 13:10
13:15 -> 13:10
13:18 -> 13:10
13:20 -> 13:20
...

If any one want to try the following queries, you can create the schema as:
CREATE TABLE your_table(tscol timestamptz);
INSERT INTO your_table VALUES
('2011/01/03 19:18:00.300'),
('2011/01/03 19:18:00.503'),
('2011/01/03 19:20:26.335'),
('2011/01/03 19:29:54.289'),
('2011/01/04 14:43:43.067'),
('2011/01/04 14:50:10.727'),
('2011/01/04 14:52:26.827'),
('2011/01/04 14:57:55.608'),
('2011/01/04 14:57:55.718'),
('2011/01/04 14:59:13.603'),
('2011/01/04 15:00:34.260'),
('2011/01/04 15:02:55.687'),
('2011/01/04 15:07:15.378');

So, in order to do that, we need to understand date_trunc and date_part functions (the latter can be invoked by the standard EXTRACT) and interval data type. Let's build the solution step by step, the final idea is to have something like this (now a pseudo-code):
SELECT truncate_the_time_by_10_minutes(tscol) AS trunc10, count(*)
FROM your_table
GROUP BY trunc10
ORDER BY trunc10;

Now, if the problem was "aggregate by minute", then we could simple truncate the timestamp to the minute, which simple means zeroing seconds and microsseconds, which is exactly what date_trunc('minute', ...) does, so:
SELECT date_trunc('minute', tscol) AS trunc_minute, count(*)
FROM your_table
GROUP BY trunc_minute
ORDER BY trunc_minute;

Works, but it is not what you want, the next capability of date_trun is with 'hour', which would already loose the information we need, so we need something between 'minute' and 'hour'. Let's see how the above query works with some examples:
SELECT tscol, date_trunc('minute', tscol) AS trunc_minute
FROM your_table
ORDER BY tscol;

Which returns:
           tscol            |      trunc_minute
----------------------------+------------------------
 2011-01-03 19:18:00.3-02   | 2011-01-03 19:18:00-02
 2011-01-03 19:18:00.503-02 | 2011-01-03 19:18:00-02
 2011-01-03 19:20:26.335-02 | 2011-01-03 19:20:00-02
 2011-01-03 19:29:54.289-02 | 2011-01-03 19:29:00-02
...

If you see 2011-01-03 19:18:00-02, now we just need to subtract 8 minutes, to do that we can:

*

*EXTRACT(MINUTE FROM tscol) will return 18

*As we want to truncate by 10 minutes, let's take the modulo of 18 and 10, so 18 % 10 which give us 8

*Now, we have the 8 minutes that we want to subtract, but as an integer, and to subtract from timestamp[tz] we need an interval, as the integer is representing minute, we can do: 8 * interval '1 minute', which will give us 00:08:00
Getting the 3 steps above in the last query, we have (I'll show each column to better understanding):
SELECT
    tscol,
    date_trunc('minute', tscol) AS trunc_minute,
    CAST(EXTRACT(MINUTE FROM tscol) AS integer) % 10 AS min_to_subtract,
    (CAST(EXTRACT(MINUTE FROM tscol) AS integer) % 10) * interval '1 minute' AS interval_to_subtract,
    date_trunc('minute', tscol) - (CAST(EXTRACT(MINUTE FROM tscol) AS integer) % 10) * interval '1 minute' AS solution
FROM your_table
ORDER BY tscol;

Which returns:
           tscol            |      trunc_minute      | min_to_subtract | interval_to_subtract |        solution
----------------------------+------------------------+-----------------+----------------------+------------------------
 2011-01-03 19:18:00.3-02   | 2011-01-03 19:18:00-02 |               8 | 00:08:00             | 2011-01-03 19:10:00-02
 2011-01-03 19:18:00.503-02 | 2011-01-03 19:18:00-02 |               8 | 00:08:00             | 2011-01-03 19:10:00-02
 2011-01-03 19:20:26.335-02 | 2011-01-03 19:20:00-02 |               0 | 00:00:00             | 2011-01-03 19:20:00-02
 2011-01-03 19:29:54.289-02 | 2011-01-03 19:29:00-02 |               9 | 00:09:00             | 2011-01-03 19:20:00-02
...

Now, the last column is the solution we want, the timestamp truncated to its 10 minutes group, now we can simple aggregate and have our final solution:
SELECT
    date_trunc('minute', tscol) - (CAST(EXTRACT(MINUTE FROM tscol) AS integer) % 10) * interval '1 minute' AS trunc_10_minute,
    count(*)
FROM your_table
GROUP BY trunc_10_minute
ORDER BY trunc_10_minute;

Which returns:
    trunc_10_minute     | count
------------------------+-------
 2011-01-03 19:10:00-02 |     2
 2011-01-03 19:20:00-02 |     2
 2011-01-04 14:40:00-02 |     1
 2011-01-04 14:50:00-02 |     5
 2011-01-04 15:00:00-02 |     5
(5 rows)

That is the exactly output you gave, but I believe it is what you actually expect, if not it is just a matter of small adjustment.

A: This may be a bit sub-optimal, but it works. The recursive query detects the start- and stop- times of the intervals; the count(*) scalar subquery counts the number of original records within each interval.
WITH RECURSIVE rr AS (
        SELECT 1::integer AS num
                , MIN(tscol) AS starter
                , MIN(tscol) + '10 min'::INTERVAL AS stopper
        FROM your_table
        UNION ALL
        SELECT
                1+rr.num AS num
                , tscol AS starter
                , tscol + '10 min'::INTERVAL AS stopper
        FROM your_table yt
        JOIN rr ON yt.tscol > rr.stopper
                AND NOT EXISTS ( SELECT *
                  FROM your_table nx
                  WHERE nx.tscol > rr.stopper
                  AND nx.tscol < yt.tscol
                )
        )
SELECT num,starter,stopper
        , (SELECT COUNT(*) FROM your_table yt
                WHERE yt.tscol BETWEEN rr.starter AND rr.stopper
        ) AS cnt
FROM rr
        ;


text:
Q: Activiti workflow: setting value of an aspect from StartTask I need to set a value from a text field on my start form and then pull this information on several other tasks. To do this, I'm using an aspect and trying to send the data up to the execution variable, and then pull it down.
The problem is that I cannot send the value from the start form to the execution variable. As it is now, Share will just say that the workflow cannot be started.
I am using Alfresco 4.2.f Community edition.
The start event is defined in the BPMN as follows:
<startEvent id="start" name="Start Delivery Ticket Workflow" activiti:initiator="initiatorUserName" activiti:formKey="deliveryTicketWorkflow:start">
  <documentation>Project Manager initiates workflow. A customer purchase order is provided, along with the specific line items for the delivery ticket.</documentation>
  <extensionElements>
    <activiti:executionListener class="org.alfresco.repo.workflow.activiti.listener.ExecutionListener" event="start">
      <activiti:field name="script">
        <activiti:string><![CDATA[
             execution.setVariable('deliveryTicketWorkflow_requestdetailstext', task.getVariable('deliveryTicketWorkflow_requestdetailstext'));;
         ]]></activiti:string>
      </activiti:field>
    </activiti:executionListener>
  </extensionElements>
</startEvent>

The relevant parts of my model are:
<type name="deliveryTicketWorkflow:start">
  <parent>bpm:startTask</parent>
  <properties />
  <associations />
  <overrides />
  <mandatory-aspects>
    <aspect>deliveryTicketWorkflow:requestdetails</aspect>
  </mandatory-aspects>
</type>
[...]
 <aspect name="deliveryTicketWorkflow:requestdetails">
  <properties>
    <property name="deliveryTicketWorkflow:requestdetailstext">
      <title>Specific Details</title>
      <type>d:text</type>
      <mandatory>true</mandatory>
      <multiple>false</multiple>
    </property>
  </properties>
</aspect>

In the config:
<config condition="deliveryTicketWorkflow:start" evaluator="task-type">
    <forms>
        <form>
            <field-visibility>
                <show id="packageItems"/>
                <show id="deliveryTicketWorkflow:requestdetailstext"/>
                <show id="transitions"/>
            </field-visibility>
            <appearance>
                <set appearance="title" label-id="Prepare Delivery Ticket" id="info"/>
                <field set="info" id="packageItems"/>
                <field set="info" label-id="Request Details" id="deliveryTicketWorkflow:requestdetailstext">
                    <control template="/org/alfresco/components/form/controls/info.ftl"/>
                </field>
                <set id="response"/>
                <field set="response" id="transitions"/>
            </appearance>
        </form>
    </forms>
</config>
[...]
<config condition="activiti$deliveryTicketWorkflow" evaluator="string-compare">
    <forms>
        <form>
            <field-visibility>
                <show id="bpm:workflowPriority"/>
                <show id="packageItems"/>
                <show id="deliveryTicketWorkflow:requestdetails"/>
                <show id="transitions"/>
                <show id="deliveryTicketWorkflow:approveRejectOutcome"/>
            </field-visibility>
            <appearance>
                <set appearance="title" label-id="Request Delivery Ticket" id="info"/>
                <field set="info" label-id="workflow.field.priority" id="bpm:workflowPriority">
                    <control template="/org/alfresco/components/form/controls/workflow/priority.ftl"/>
                </field>
                <field set="info" id="packageItems"/>
                <field set="info" label-id="Request Details" id="deliveryTicketWorkflow:requestdetails">
                    <control template="/org/alfresco/components/form/controls/textarea.ftl"/>
                </field>
                <set id="response"/>
                <field set="response" id="approveRejectOutcome">
                    <control template="/org/alfresco/components/form/controls/workflow/activiti-transitions.ftl"/>
                </field>
                <field set="response" id="transitions"/>
            </appearance>
        </form>
    </forms>
</config>

I have seen at least one question here that was similar, but the answers were stating to use task listeners for the start form. I'm not sure at all how that is intended to function, because it seems like a start task isn't a "true" task and can only use ExecutionListeners. The difference should be small, but it seems that any reference to "task" in the start task will either cause a failure or just have no affect at all. Becasue I can't use task.getVariableLocal() to get the value, I don't see what to give to execution.setVariable() as the value.

A: In my experience, all values of aspects and properties in a start task are automatically copied to the executionContext and are already available for future tasks.
Try removing the executionlistener in your BPMN, you shouldnt need that. Then try making a starttasklistener on your subsequent task that copyies the value from your execeutioncontext into this task. It should work fine.
Getting the var back from your executioncontext in your subsequent task should work like this:
<activiti:taskListener event="create" class="org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener">
   <activiti:field name="language" stringValue="groovy" /
   <activiti:field name="script">
   <activiti:string><![CDATA[
   System.out.println(execution.getVariable("deliveryTicketWorkflow_requestdetailstext"));
   if (execution.getVariable("deliveryTicketWorkflow_requestdetailstext") != null){
     task.setVariableLocal('deliveryTicketWorkflow_requestdetailstext', execution.getVariable("deliveryTicketWorkflow_requestdetailstext"));
    }]]>
   </activiti:string>
</activiti:field>
</activiti:taskListener>

A: This is a long shot but in your share form, your custom field is using the info control:

I believe you need there to be a regular field there, the info field is to display text, AFAIK, it doesn't include an input field and won't send anything to the workflow start.


text:
Q: How to delay an action inside the INIT in XCODE? BELOW INIT
yellowbg = [CCSprite spriteWithFile:@"yellowxlixk.png"];
[yellowbg setPosition:ccp(509, 671.75)];
      yellowbg.scale = .75;
[self addChild:yellowbg z: 1];

How would I go about delaying this object? I am very new to this, please be basic in your explanation.

A: if you want to add this object on the layer after 2 or 3 sec, then you can use this one..
[self performSelector:@selector(addImageToLayer) withObject:nil afterDelay:2.0]; // specify delay time

Here is your function :
-(void) addImageToLayer
{
   yellowbg = [CCSprite spriteWithFile:@"yellowxlixk.png"];
   [yellowbg setPosition:ccp(509, 671.75)];
   yellowbg.scale = .75;
   [self addChild:yellowbg z: 1];
}

another option is, you can use this one also :
[self schedule:@selector(addImageToLayer) interval:2];

function :
but in the function you have to stop scheduler to calling this method., by the above code of line it call function after every 2 seconds., that's why you have to stop that.
-(void) addImageToLayer
{
   yellowbg = [CCSprite spriteWithFile:@"yellowxlixk.png"];
   [yellowbg setPosition:ccp(509, 671.75)];
   yellowbg.scale = .75;
   [self addChild:yellowbg z: 1];
   [self unschedule:@selector(addImageToLayer)];  //to stop scheduler to calling function repeatedly
}

You can use either of this ways to delaying. hope this helps..


text:
Q: Truncating canvas labels in ChartJS while keeping the full label value in the tooltips I have some bar charts that have really long labels and they affect the size of the charts.
Example: http://jsfiddle.net/norbiu/aqa8w19d/4/
I'm trying to truncate the labels that show up under the chart while keeping the label that shows up in the tooltips when hovering over a bar. The problem is that the tooltips and the canvas labels both get their values from the labels array in the data structure. Truncating the value will show the shortened version in both locations.
sales: ko.observable({
    labels: ['A really really long label', 'Another long labe', 'A third label that is long', 'Q4', 'Q5', 'Q6'],
    datasets: [{
        label: 'Helados',
        fillColor: '#152491',
        data: [70, 32, 6, 23, 63, 43]
    }]
}),

The documentation has nothing on this. Any ideas?

A: In Chart JS V2 you can truncate labels passing the options object.
Also you can customize the tooltips.
options:{
    scales: {
        xAxes: [{
            ticks: {
                callback: function(value) {
                    return value.substr(0, 10);//truncate
                },
            }
        }],
        yAxes: [{}]
    },
    tooltips: {
        enabled: true,
        mode: 'label',
        callbacks: {
            title: function(tooltipItems, data) {
                var idx = tooltipItems[0].index;
                return 'Title:' + data.labels[idx];//do something with title
            },
            label: function(tooltipItems, data) {
                //var idx = tooltipItems.index;
                //return data.labels[idx] + ' €';
                return tooltipItems.xLabel + ' €';
            }
        }
    },
}

A: So the way i went about this was to add a new option called labelLength which, if passed a number greater than 0, will trim the labels on the x axis to that length.
It happens in the scale class of the chart and will only apply to the axis label and not the tool tip.
If you wanted you could extract the relevant bits and just override the scale class and also the build scale function in the bar chart to include the new option.
In the scale class here is what was added
 Chart.Scale = Chart.Element.extend({
        initialize: function() {
            //truncate the labels if option is grater than 0
            this.xLabels = this.labelLength > 0 ? this.xLabels.map(this.truncateLabel, this) : this.xLabels;
            this.fit();
        },
        truncateLabel: function(label) {
            return label.substring(0, this.labelLength);
        },

        addXLabel: function(label) {
            //also added here for when adding single items of data to a graph
            this.xLabels.push(this.labelLength > 0 ? this.truncateLabel(label) : label);
            this.valuesCount++;
            this.fit();
        },

}
then in the bar buildscale function you would need to pass the option to the scale.
Or i have included this in my fork of chart js (https://github.com/leighquince/Chart.js) to use just pass the option labelLength with your desired labels length, example below

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100)
};

var barChartData = {
  labels: ["January a really long label", "February a really long label", "March a really long label", "April a really long label", "May a really long label", "June a really long label", "July a really long label"],
  datasets: [{
    fillColor: "rgba(220,220,220,0.5)",
    strokeColor: "rgba(220,220,220,0.8)",
    highlightFill: "rgba(220,220,220,0.75)",
    highlightStroke: "rgba(220,220,220,1)",
    data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  }, {
    fillColor: "rgba(151,187,205,0.5)",
    strokeColor: "rgba(151,187,205,0.8)",
    highlightFill: "rgba(151,187,205,0.75)",
    highlightStroke: "rgba(151,187,205,1)",
    data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  }, {
    fillColor: "rgba(15,18,20,0.5)",
    strokeColor: "rgba(15,18,20,0.8)",
    highlightFill: "rgba(15,18,20,0.75)",
    highlightStroke: "rgba(15,18,20,1)",
    data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  }]

}
window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myBar = new Chart(ctx).Bar(barChartData, {
    labelLength: 10,
  });
}
<script src="http://www.quincewebdesign.com/cdn/Chart.js"></script>
<div style="width: 50%">
  <canvas id="canvas" height="450" width="600"></canvas>
</div>

A: Just some additional info (can't comment, but thought this would be helpful) I added a small bit of code to the answer above to get "..." to show if labels are truncated.
truncateLabel: function(label) {
    var xSubstring = label.substring(0, this.labelLength);
    if(xSubstring.length < this.labelLength) {
        return xSubstring;
    } else {
        // Check if a word is cut off
        if ( ' ' != label.charAt( (this.labelLength-1) ) && ' ' != label.charAt( this.labelLength ) ) {
            // If so, cut the label off at the last space instead of mid-word
            var last_space_pos = label.lastIndexOf(" ", this.labelLength);
            last_space_pos = (0 > last_space_pos)? this.labelLength: last_space_pos;
            xSubstring = label.substring(0, last_space_pos);
        }
        return xSubstring+"...";
    }
},

A: This can be achieved without modifying the plugin code with customTooltips:function(tooltip) option documented here.
A sample code is also provided here to modifying tooltips for line graph. Using that snippet its fairly easy to achieve the desired behavior.
 - Create a div for custom tooltip.
 - Truncate the labels for x-axis but keep the mapping to original text in an array.
 - In customTooltip function, populate tooltip div with original text by using tooltip.text as key in mapping array.


text:
Q: Separating SQL reporting layer and presentation layer? I'm using SQL Server Reporting Services. Most of my queries run as reports which are simply exported as PDF.
I'd like to know which type of calculations, if any, should done in the actual SQL query and which should be calculated using the SSRS IDE (Business Intelligence Studio).
For example, if I have a 12 month sales report (12 months) which requires a sales average of the 3 most recent months, where should that average be calculated?
Should most calculations/aggregations be done in the presentation layer? Any exceptions?

A: This could be looked at in 2 ways:

*

*where do you put business logic

*given time is needed for calculations, where is more efficient

The answer to either of these is "it depends". For your example of a 12-month report that also displayed trends, if you have a couple of parameters that change the logic used to get the data, I'd be tempted to do as much as possible in the SQL stored procedure (even the averages) and make the report pretty "dumb" to just display the results. If the report is very simple or the logic is specific to that report only, then in the report might work.
For re-usability I favor doing things in SQL. For complex display stuff (heatmapping, graphs, etc.), in the report is probably better.

A: Keep the logic of the report with the report.  SQL Server will give you the data but it is best to keep customized logic with the report.

A: I would stay away from having the report make roundtrips to the database for calculations. If your stored procedure(s) grouping and ordering matches your report layout then SSRS is pretty efficient at making aggregated calculations.


text:
Q: Hiding the products with quantity 0 from view django rest framework How can I hide the products from view with quantity == 0?
This is my models.py
class Product(models.Model):
    title = models.CharField(max_length=255, db_index=True)
    description = models.TextField()
    price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    quantity = models.PositiveIntegerField()
    color = models.CharField(choices=COLOR_CHOICES, default='BLACK', max_length=100)
    category = models.ManyToManyField(Category, related_name='products')

    class Meta:
        ordering = ('-id',)

    def __str__(self):
        return self.title

    @property
    def instock(self):
        return self.quantity > 0

and my views.py
class ProductsList(generics.ListAPIView):
    queryset = Product.objects.all().order_by('-id')
    serializer_class = ProductSerializer
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    filter_class = ProductFilter

A: You can exclude objects with exclude(field_name=value_to_exclude), so:
 class ProductsList(generics.ListAPIView):
        queryset = Product.objects.all().exclude(quantity=0).order_by('-id')
        serializer_class = ProductSerializer
        filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
        filter_class = ProductFilter


text:
Q: OAuth2 error invalid client I'm getting an invalid client error. Client works for auth_code.authorize_url, but not for auth_code.get token
relevant code:
CLIENT_ID = "$$$.apps.googleusercontent.com"
CLIENT_SECRET = "secret"

REDIRECT_URI = 'http://localhost:3000'
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET,
                                   site:     'https://accounts.google.com',
                                   token_url: '/o/oauth2/token',
                                   authorize_url: '/o/oauth2/auth')

url = client.auth_code.authorize_url(scope: "https://www.google.com/m8/feeds",
                                            redirect_uri: REDIRECT_URI)
puts url

code = "taken from url"  #line 20
token = client.auth_code.get_token(code, :redirect_uri => REDIRECT_URI)

Error message:
/.rvm/gems/ruby-2.2.1/gems/oauth2-1.0.0/lib/oauth2/client.rb:113:in `request': invalid_client:  (OAuth2::Error)
{
  "error" : "invalid_client"
}
from /.rvm/gems/ruby-2.2.1/gems/oauth2-1.0.0/lib/oauth2/client.rb:138:in `get_token'
from /.rvm/gems/ruby-2.2.1/gems/oauth2-1.0.0/lib/oauth2/strategy/auth_code.rb:29:in `get_token'
from oauth.rb:20:in `<main>'

One clarification I think I need is that say the code given from the url is /?code=$code$ do I use just the $code$?(currently doing this) or code=$code$
Thanks in advance for the help

A: Fixed:
The answer was the allow offline mode when initializing the client. I was also using a code I had previously used.
changed this:
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET,
                               site:     'https://accounts.google.com',
                               token_url: '/o/oauth2/token',
                               authorize_url: '/o/oauth2/auth')

to this:
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET,
                                   site: 'https://accounts.google.com',
                                   token_url: '/o/oauth2/token',
                                   authorize_url: '/o/oauth2/auth',
                                   additional_parameters: {"access_type" => "offline"} ) #new line


text:
Q: JavaScript and Livewire Laravel code is not working in live server cPanel My code is working fine in the Xampp server But when I upload my code in cPanel Livewire Login and Register are not working in cPanel my design of login and register page is broken.
login in xampp server
login in cpalel
I have created a color picker in my laravel project using JavaScript which working fine in the xampp server but when I upload it into cpanel codes are not working. please help me
JavaScript and Html code are here
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    {{-- <title>Document</title> --}}

    <title>Bootstrap Colorpicker Example - nicesnippets.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.1/css/bootstrap-colorpicker.min.css" rel="stylesheet">

@extends('products.layout')

@section('content')

Add New Data

             Back

@if ($errors->any())

        Whoops! There were some problems with your input.

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

<form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
    @csrf

                Name:
                <input type="text" name="name" class="form-control" placeholder="Name">

                Detail:
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>

            Color picker

              <input type="text" value="#00AABB" class="form-control" name="color" placeholder="Color" />

                Logo:
                <input type="file" name="logo" class="form-control" placeholder="logo">

                Image:
                <input type="file" name="image" class="form-control" placeholder="image">

                <button type="submit" class="btn btn-primary">Submit</button>

</form>

@endsection

This code is working in xampp server

This code is not working in cpanal


text:
Q: LINQ Trouble with nested subquery in select statement I have the following query I want to replicate in LINQ:
SELECT A.id,C.quotas, C.fundingid, C.date
,(SELECT value FROM public.fundingsharevalue WHERE fundingid = C.fundingid AND date = C.date) as sharevalue
FROM public.goal A
INNER JOIN public.goaltransactionfunding C ON A.id = C.goalid
where A.userid = 25

Code in LINQ:
var balance = from goal in _context.Goals
                      join goaltransactionfunding in _context.Goaltransactionfundings on goal.Id equals goaltransactionfunding.Goalid
                      join user in _context.Users on goal.Userid equals user.Id
                      where goal.Userid == userid
                      select new BalanceViewModel
                      {
                          FundingId = goaltransactionfunding.Fundingid,
                          ShareValue =  (from fundingsharevalue in _context.Fundingsharevalues
                                        where fundingsharevalue.Id == goaltransactionfunding.Fundingid && fundingsharevalue.Date.Equals(goaltransactionfunding.Date)
                                        select fundingsharevalue.Value).FirstOrDefault(),
                          Quotas = (double)goaltransactionfunding.Quotas,
                          Fecha = goaltransactionfunding.Date,
                          GoalId = goal.Id
                      };

The problem is with Sharevalue subquery, it doesn't show values when actually it has.
It seems that the query does not fetch anything when it should fetch as it does in SQL.
I'm attaching images for both outputs.
QueryShareValues Image
LINQ sharevalues Image


text:
Q: DNS query appending parent suffix twice We're having an issue with DNS clients not being able to resolve certain FQDNs.  Within the same domain in which the problem occurs, doing an nslookup against a host name works.  However, an nslookup against the hostname.domain.parentdomain1.parentdomain2.net doesn't work.  Weird, from outside that domain, the same FQDN query works.  Clients in both domains are using the same DNS servers, which are in the "parentdomain1" example.
The nslookup comes back with:
Non-authoritative answer:
Name:    hostname.domain.parentdomain1.parentdomain2.net.parentdomain2.net
Address:  209.62.20.188
So, the client is appending the "parentdomain2.net" twice.
Would appreciate any assistance.

A: This is NXDOMAIN hijacking, revealing to you a harmless aspect of how DNS search suffixes work.
I'm going to guess that your DNS resolution is to a local device, which contains copies of your zones, then does recursive lookups for other zones off of an internet server (which is doing NXDOMAIN hijacking).

A client with a DNS search suffix will issue additional queries with the chunks of the suffix appended.  If my system has a suffix list of, for instance, foo.domain.com then domain.com, and I do a lookup against a single-name host server, it'll execute the following queries, in order, until it finds something:
server.
server.foo.domain.com.
server.domain.com.

(the . at the end is to specify, in DNS terms, that it's relative to the root and nothing else)
Which is great, and makes perfect sense.  If server doesn't exist at server., it'll be looked for at server.foo.domain.com. - if it doesn't exist, it keeps going; if it finds an answer, it'll stop.
Where it starts to look a little less normal is when you search for something that you're thinking is the FQDN - but DNS doesn't know that (unless you're doing an nslookup with the . at the end).  So, if I search for server2.domain.com, it'll search like this:
server2.domain.com.
server2.domain.com.foo.domain.com.
server2.domain.com.domain.com.

Those last 2 make very little sense to you and me, but the resolver doesn't know any better, and needs to check.

Which brings us to what you're seeing.  Your search suffix list probably looks something like this:
domain.parentdomain1.parentdomain2.net
parentdomain1.parentdomain2.net
parentdomain2.net

And, your recursive DNS servers probably contain a zone for parentdomain1.parentdomain2.net, but not for parentdomain2.net.
So, the query happens like this:
hostname.domain.parentdomain1.parentdomain2.net.
(NXDOMAIN response - you'll want to look into why that is happening if this is where this record is supposed to be)
hostname.domain.parentdomain1.parentdomain2.net.domain.parentdomain1.parentdomain2.net.
(Your name server likely has a zone for parentdomain1.parentdomain2.net, and throws another NXDOMAIN)
hostname.domain.parentdomain1.parentdomain2.net.parentdomain1.parentdomain2.net.
(same result as previous)
hostname.domain.parentdomain1.parentdomain2.net.parentdomain2.net.
(Now, your DNS server forwards the query to your upstream forwarders for lack of an authoritative zone.  Your upstreams dutifully send back a false response, in a misguided attempt at getting some extra advertising revenue)
So!  This is likely a simple issue with a record, which got a lot more confusion because of abusive practices by your ISP or whoever else runs that upstream DNS server.  There's a lot of variables that I've made assumptions on above, but do some checking on how things are resolving for specific queries (with . on the end to eliminate the search suffix) and it should track pretty closely with how I've outlined it.

A: If you have windows users and they are in domains  or somehow they are associated with fomain (example in wimax network  nsp id or like this)  when they send  dns quesry they append their domain name  to back of quesry. In linux /etc/resolv.conf if you have  search directove this is same effect. So do not worry this is normal.


text:
Q: Can not get any hear any audio from Android SDK emulator launched from eclipse I am starting to develop for Android, and I am using Eclipse with the Android plugin and Android SDK.
No matter what I do, I can not get the emulator to make any sound.
I have tried turning on audio in the virtual device setup.
I have also tried various command lines in the run configuration such as:

*

*-audio oss ==== this gets a error message that there is no oss backend defined.

*-useaudio  === comes up as not a valid option

*-audion -winaudio === starts w/o error but still no sound

If I open my windows7 audio controller on my laptop, I see that the android virtual machine gets its own volume slider, but nothing sounds when I move or click on that audio slider.  (The other volume sliders produce the normal beep sound.)
I've been searching for "Android emulator no sound" for hours but no luck.
Any ideas?

A: The issue was not with the emulator not making sound ( as verified by the fact it would not work on my device either ), but a unaccounted problem with the SoundPool class.
I looked in the logcat and found references like "sample 1 not ready".  Researching this I finally found a obscure thread in which it was mentioned that it takes some time before sound pool is ready to be used ( and therefore all sounds should be loaded well before they are used ).
I modified my playSound method to monitor the return value of the soundPool.play(...) method call.  It returns the id of the running sound stream, or 0 if it failed ( i.e. "sample 1 not ready" ).
What I did was to put it into a loop, and when the return value of the
soundPool.play(...) method call was 0, I had the thread sleep for 1
millisecond, then try again.  With this method in place, I now always
get a sound.
As a side note I have also been running tutorials with my SDK set up for Android 2.2 instead of Android 2.3.1, because Android 2.2 is what is installed on my device, a Sprint LG optimus S LS670.
I have ran my modified code on both a Android 2.2 and a Android 2.3.1 Virtual device.
When I run the code on the older Android 2.2 VD, it typically took about 10 to 15 loops ( so a 10 to 15 ms delay ) before the sounspool was ready to play the sound.
When I ran the same code on a Android 2.3.1 VD, the delay was MUCH worse, taking around a 350 ms delay before it would play - yes almost 35 times slower!
When I ran the same code deplyed to my device running Android 2.2, the time delap was about identical to running it on the emulator.


text:
Q: How to start browser in WebDriver with custom localStorage set I want to speed up my Selenium tests and noticed that a lot of time is being spent on login procedure.
Login on web application is implemented via localStorage session token (probably OAuth 2.0). I know how to set it once a browser starts and login page loads:
localStorage.setItem(key, value)

It works great. But is it possible to make the browser to pick up custom localStorage using Selenium (Java).
Is it profile?

A: Well this works for me in python
driver.excute_script('javascript:localStorage.(funtion of localStorage)')

so I suppose well you can set up a validation token like I use for test, and of course I get my auth_token from the database first, but it works like this
driver.excuteScript('javascript:localStorage.token="your validation token";');

should work


text:
Q: Android Client -> SSL --> Java Server Error: no cipher suites in common I'm trying to connect from my Android Client to my Java Server.
I can connect to my SSH Server from my own Java Client (Both with Java 1.11)
If I'm connecting from Android (mimimum SDK 24) I get an  error:

no cipher suites in common

I created the keystores by myself with an DSA algorithm.
I tried different cipher suits. This one is running on my  Local Java Client / Server Test:
setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" })

None of the available Android Cipher Suits (https://developer.android.com/reference/javax/net/ssl/SSLEngine) is working in my local Server/Client test.
Do I have to use another SSLSocketFactory library (I'm using  javax.net.ssl.*)?!?

A: I found the solution. On Java 1.11 I had to change the Keytore algorithm to RSA.


text:
Q: How do i add a new column to new .xlsx file when i combine 2 of them Priority : I would like to create a new column when i combine 2 .xlsx files, im pretty new to python, please help.
Secondly : i would also like to know how can i loop through the file in a folder? i am doing this hard coded but i would like to improve and loops thru every .xlsx files to create the result i want.
i tried to look for resources online, but couldnt find any
excel1 = '1.xlsx'
excel2 = '2.xlsx'
excel3 = '3.xlsx'

df1 = pd.read_excel(excel1)
df2 = pd.read_excel(excel2)
df3 = pd.read_excel(excel3)

values1 = df1[['Purchasing Document','Material','Quantity
Received','Still to be delivered (qty)','invoice','cancel']]
values2 = df2[['Purchasing Document','Material','Quantity
Received','Still to be delivered (qty)','invoice','cancel']]
values3 = df3[['Purchasing Document','Material','Quantity
Received','Still to be delivered (qty)','invoice','cancel']]
dataframes = [values1, values2, values3]

join = pd.concat(dataframes)
join.to_excel("testing123.xlsx")

Actual result right now is only showing 4 columns, Purchasing document to Qty, invoice and cancel gives me error.
I expect the result to be showing 6 columns, 4 of them filled with documents and invoice and cancel will be blank.

A: For reading mutiple files from a folder and storing there data in a excel with multiple sheets, you can try below code :
import os
import pandas as pd
dirpath = "C:\\Users\\Path\\TO\\Your XLS folder\\data\\"
fileNames = os.listdir(dirpath)

writer = pd.ExcelWriter(dirpath+'combined.xlsx', engine='xlsxwriter')
for fname in fileNames:
    df = pd.read_excel(dirpath+fname)
    print(df)
    df.to_excel(writer, sheet_name=fname)
writer.save()

i hope this would help in your second point.


text:
Q: C initialize array within structure I want to have an variable-length array contained within a structure, but am having trouble initializing it correctly.
struct Grid {
  int rows;
  int cols;
  int grid[];
}

int main() {
  struct Grid testgrid = {1, 3, {4, 5, 6}};
}

Everything I try gives me an 'error: non-static initialization of a flexible array member' error.

A: You don't have a variable length array (VLA) in your structure. What you have in your structure is called a flexible array member. Flexible array member has absolutely nothing to do with VLA. Flexible array members in C exist to legalize and support the good-old "struct hack" idiom, which is based on dynamic allocation of memory for struct objects with trailing arrays of different size.
Flexible array members cannot be initialized with aggregate initializers, which is what you seem to attempt in your code. What you are trying to do here is simply impossible. There's no such feature in C.
Meanwhile, the text of the error message generated by your compiler seems to suggest that it supports something like this as an extension. This might be true, but keep in mind that this is in no way a standard C feature.

A: Here is my version:
#include <stdio.h>

struct matrix {
  int rows;
  int cols;
  int **val;
} a = {        .rows=3,  .cols=1,
        .val = (int*[3]){ (int[1]){1},
                          (int[1]){2},
                          (int[1]){3} } },

  b = {        .rows=3,  .cols=4,
        .val = (int*[3]){ (int[4]){1, 2, 3, 4},
                          (int[4]){5, 6, 7, 8},
                          (int[4]){9,10,11,12} } };

void print_matrix( char *name, struct matrix *m ){
  for( int row=0;row<m->rows;row++ )
    for( int col=0;col<m->cols;col++ )
      printf( "%s[%i][%i]: %i\n", name, row, col, m->val[row][col] );
  puts("");
}

int main(){
  print_matrix( "a", &a );
  print_matrix( "b", &b );
}

A: You can make that work in gcc by making the struct either static or global, but it turns out that initializing flexible array members is non-conforming and so it is likely to not work except with gcc.  Here is a way to do it that just uses C99-conforming features...
#include <stdlib.h>
#include <stdarg.h>

typedef struct Grid {
  int rows;
  int cols;
  int grid[];
} *Grid;

Grid newGrid(int, int, ...);

Grid newGrid(int rows, int cols, ...)
{
Grid g;
va_list ap;
int i, n = rows * cols;

  if((g = malloc(sizeof(struct Grid) + rows * cols * sizeof(int))) == NULL)
    return NULL;
  g->rows = rows;
  g->cols = cols;
  va_start(ap, cols);
  for(i = 0; i < n; ++i)
    g->grid[i] = va_arg(ap, int);
  va_end(ap);
  return g;
}
.
.
.
Grid g1, g2, g3;
g1 = newGrid(1, 1, 123);
g2 = newGrid(2, 3, 1, 1, 1,
                   2, 2, 2);
g3 = newGrid(4, 5, 1,  2,  3,  4,  5,
                   6,  7,  8,  9, 10,
                  11, 12, 13, 14, 15,
                  16, 17, 18, 19, 20);

A: I do not believe that this is possible or supported.  As DigitalRoss points out, you can initialize from a literal in the case of static arrays... though I'm still not sure if this is included in the Standard or just a common extension.  I can't seem to find a clause in the Standard that supports literal initialization of flexible arrays though I can see that gcc explicitly supports it.

A: A version using malloc:
#include <stdio.h>
#include <stdlib.h>

typedef struct Grid {
  int rows;
  int cols;
  int *grid;
} Grid;

/* Should validate params */
Grid
buildGrid(int rows, int cols, int vec[]) {

    Grid grid;
    grid.rows = rows;
    grid.cols = cols;
    int i;

    if ( (grid.grid = malloc(sizeof(vec))) == NULL ) {
        /* do something.*/
    }

    for(i = 0; i < sizeof(vec) ; i++ ) {
        grid.grid[i] = vec[i];
    }

    return grid;
}


text:
Q: Force new install instead of upgrade in Android The previous version of my Android app was a beta version and soon I will be releasing the final version. The amount of changes that have taken place between the old and new version is significant. While the new version does take provide upgrading the sqlite database from the older version, it is still possible that upgrading from the beta to the final may result in the newer version not running correctly. There are too many changes to know whether the upgrade will run smoothly.
I would prefer to have the user uninstall the older version before installing the newer version. While I can request that in the docs, in reality, Android detects the newer version automatically and suggests to the user to upgrade. If there is a way to avoid that, I would like to. I really don't want to mess with my signed key and still wish to maintain my ratings in the Google Play store without creating a "new" app. Is there some way to mark my app in a way that forces a new install on all previous versions instead of upgrading it?

A: No, there is no way to do this. You should be able to perform the test by installing the original version on the emulator, putting in some data that your app uses, i.e. set it up how a user of the app might use it. Then run adb install -r . This will update the app retaining the app data.
You would have to put some logic in to cope with the upgrade, i.e. checking preferences, upgrade databases, etc. Getting the user to uninstall and then re-install and will likely annoy users as they will have to enter in all the details again.
But what you're asking, there is no way to do this. An alternative, although I still wouldn't suggest this method, is when the user launches the app for the first time after the upgrade, the app, clears the shared preferences and deletes the database, and then you re-create the database again and the app will be like first use.
Hope this helps


text:
Q: Need to group by column while ignoring some text format I have the following data.
Sport
--------------
Baseball
Football
Baseball [a]
Football [a] [b]
Basketball

How can I group this to ignore the data in the brackets?

A: The expression
regexp_replace(the_column, ' +.*$', '')

will remove everything starting with the first space character up until the end of the string. So you just need to group by that expression:
with test_data (sport) as
(
  values
    ('Baseball'),
    ('Football'),
    ('Baseball [a]'),
    ('Football [a] [b]'),
    ('Basketball')
)
select regexp_replace(sport, ' .*$', ''), count(*)
from test_data
group by regexp_replace(sport, ' .*$', '')

This will return:

regexp_replace | count
---------------+------
Baseball       |     2
Basketball     |     1
Football       |     2

SQLFiddle: http://sqlfiddle.com/#!15/d41d8/3379
Edit
To deal with legitimate multi-word sports there are two options:

*

*remove everything after the first [: regexp_replace(sport, ' \[.*$', '')

*remove all characters that occur between [..] and then trim the result: trim(regexp_replace(sport, '\[.*\]', '', 'g'))

A: USE tempdb
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP    TABLE #temp
GO
SELECT  Sport
INTO    #temp
FROM    (
            SELECT 'Baseball' Sport
            UNION ALL
            SELECT 'Football'
            UNION ALL
            SELECT 'Baseball [a]'
            UNION ALL
            SELECT 'Football [a] [b]'
            UNION ALL
            SELECT 'Basketball'
            )a

--Using CTE To Strip SpecialText
;WITH AvoidCertainText
AS
(
    SELECT  Sport
            , CASE
                WHEN CHARINDEX('[',Sport) <> 0 THEN RTRIM(LTRIM(LEFT(Sport,CHARINDEX('[',Sport)-1)))
                ELSE Sport
            END FormatedSport
    FROM    #temp
)
SELECT   FormatedSport Sport
        , COUNT(FormatedSport)SportCount
FROM    AvoidCertainText
GROUP BY FormatedSport


text:
Q: Use of "auto" in place of std::vector* I am using a function like
void TestAnalyzer::AddBranch(std::vector<double>* vec, std::string name){
tree->Branch(name.c_str(),vec);
}

But in place of vector<double> sometimes I have int vectors also so how can I use "auto" or something else so that with the same argument it read int as well as double.

A: What you're looking for is a template. You will get a new, different function for each kind of vector.
template< typename element_type >
void TestAnalyzer::AddBranch(std::vector<element_type>* vec, std::string name){
tree->Branch(name.c_str(),vec);
}

element_type will be deduced from the function argument, just as auto is deduced from an initializer. This kind of usage is more primitive and works with C++98 (or many pre-standard compilers).

A: It sounds like you want a templated function.
template<typename T> void TestAnalyzer::AddBranch(std::vector<T>* vec, std::string name){
   tree->Branch(name.c_str(),vec);
}


text:
Q: Are "to be unselfconscious" and "to lack self-consciousness" completely synonymous? As an expert non-native speaker, I can sense a slight difference in the two expressions, in that "being unselfconscious" can be used in a positive sense, whereas "lacking self-consciousness" is definitely negative.
Is that so also for native speakers?

A: I generally agree with TaliesinMerlin's comment. When applied to a person (rather than say a text), "lacking self-consciousness" suggests not having the capacity for it, which may well be a negative, since self-consciousness is often a desirable trait. e.g. "Steven completely lacked self-consciousness at the party and ended up really upsetting Guilia".
"Being unselfconscious" is more of a temporary state, and I generally hear it as a more positive thing: e.g. "When speaking in public, being unselfconscious is often helpful." Negation with "not" rather than "un-" might be more natural in some cases: "Guilia really put Sam at ease, so he was not self conscious when he had to perform.". Note also the meaning "without affectation or pretence" at https://www.wordreference.com/definition/unselfconscious : this is generally positive.
The negative sense in "lacking self-consciousness" perhaps comes from "lacking", which often points up something that might be desirable. In any case, I generally understand it in the sense of second meaning at https://www.wordreference.com/definition/self-consciousness : "conscious[ness] of oneself or one's own being.", which is a often positive, unless forthright, confident or brazen behaviour is desired!
In short, I don't think they're completely synonymous, but the meanings are close.


text:
Q: Time.sleep value dynamic - Python I am taking backup of different network devices daily using paramiko. Each device takes different time interval to login in to the device and also take different time to complete each command. So if I keep time.sleep() with a static time value sometimes it is more time to wait and sometimes it is very less to wait. So how I can I write a program to wait until the first command execute and go for next one, irrespective time.sleep value.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port='22', username=usr_name, password=pwd)
connection = ssh.invoke_shell()
connection.send("\n")
time.sleep(14)
connection.send("enable\n")
time.sleep(3)
connection.send("%s\n" %(pwd))
time.sleep(1)
connection.send("terminal length 0\n")
time.sleep(1)
connection.send("sh int status | ex (trunk|routed)\n")


text:
Q: Why is the output volume lower on a 1 transistor preamp I built the simple common emitter 1 transistor preamp with a 2n3904 from hackaweek (http://hackaweek.com/hacks/?p=327) and hooked it up to my iPod as a test. When I had the small earbuds on my iPods output, the volume was louder than the preamps output. Why is this and why is it called an amp if it attenuates?

A: The schematic shows that this is a voltage amplification stage with poor current sourcing ability (that is, not a power amplifier by any stretch). Its output impedance is essentially that of the load resistor R3, and that is 10K. (That is a property of common-emitter amplifier circuits: the load resistor determines the output impedance.)  So it is not going to work well into loads whose impedance is a three digit figure, let alone two digit or single.
The author of the circuit knows this, which is why he calls it a preamp.
If you hook it up to headphones, it will not compete with the amplifier in your portable device, which is properly designed to drive their low (typically 32 ohm) impedance.
The earbuds may be "small", but they are hard to drive due to their low impedance: as a load, they are "big".
When an amplifier that has a high output impedance is asked to drive a low impedance load, then most of the signal voltage is dropped across its own output impedance, and only a small part of the voltage is bridged to the load. The output and input impedance essentially form a voltage divider.
Explore using different loads with this circuit. For instance compare the iPod going directly into a PC's audio input, versus through this circuit.

A: Simplistic explanation: -
It's a bit more complex than this but think about the output being from a potentiometer. The junction of collector and 10k resistor is the wiper; the 10k being the upper part of the pot and the transistor being the lower half of the pot.
To potentially get a large signal out, you want the no-signal mid point of the junction of collector and 10k resistor to be at mid-rail i.e. half Vcc. This is achieved by the transistor acting also like a 10k resistor.
Now, when you apply an input signal, only the transistor can "modify" its resistance - it can go to almost zero resistance and the voltage out will be close to 0V; or it can go to very high resistance (like maybe 1Mohm) and the voltage will rise close to Vcc. But, on average your transistor will "behave" like a 10k resistor with fluctuations up and fluctuations down as the input signal falls and rises.
If you wired your input signal across a 20k potentiometer, set the pot wiper half way and, connected your headphones to the wiper, how much signal would you get into your headphones?
Well, you would get nearly 50% signal if your pot were (say) 5ohms and your headphones were (say) 100ohms. But they aren't.
Does this make sense?

A:
why is it called an amp if it attenuates?

This requires a response even if it is only indirectly related to your question.
An amplifier can, in fact, attenuate voltage.  This is a good question and goes to the heart of the notion of "amplifier".  From wiki:

An electronic amplifier, amplifier, or (informally) amp is an
  electronic device that increases the power of a signal.

Note that is the power of a signal that is increased.  But power is the product of voltage and current.  Thus, it is entirely possible to have an amplifier that has, for example, a voltage gain less than 1 (the output voltage is less than the input voltage) but a power gain greater than 1.
An example is the common collector (drain, anode, ...) amplifier, also known as an emitter (source, cathode...) follower.
The voltage gain of this amplifier is 1 than one but the current gain can be much greater than 1 so the power gain is greater than 1.
As a contrast, consider the ideal transformer.  We wouldn't think of calling an ideal transformer an amplifier but, in fact,  a transformer can provide voltage gain or current gain.  But, it cannot provide both.  In fact, for an ideal transformer, the input power and output power are equal; the power is neither increased or decreased; it is neither an amplifier or an attenuator.


text:
Q: Influence of KRC and SASL on Haskell? While learning Haskell I took a side road (so to speak) in researching the Kent Recursive Calculator and SASL functional languages.  I was immediately struck by the similarities between them and Haskell and since they predate it I wonder if/how they provided influence.
Any information regarding the influence (or lack thereof) of KRC and SASL on Haskell would be much appreciated.

A: The connection you're probably looking for here is that David Turner, who was largely responsible for SASL and KRC, was also involved with Miranda, a non-strict, purely functional language. Miranda was relatively popular in its time, but was a proprietary language; an open standard alternative to Miranda was a major motivation for the creation of Haskell.
For further details, see also A History Of Haskell: Being Lazy With Class, by Hudak, Hughes, SPJ, and Wadler, which mentions Turner's work as well as other influences on Haskell.


text:
Q: If $\varphi(a) = \varphi(b)$ and $K=\ker \varphi$ why does $aK = bK$? If $\varphi(a) = \varphi(b)$ and $K = \ker \varphi$
then $a^{-1}b \in K$ and $b^{-1}a \in K$
where $aK$ is left coset such that $aK = \{ ak | k \in K \}$
then $b \in aK$ and $a \in bK$
I follow that so far. Then, my textbook says
$aK=bK$
Why is this so? Can someone do a simple proof?

A: Note that
$$
\begin{align*}
x \in aK &\iff a^{-1}x \in K \iff \varphi(a^{-1}x) = e \\&\iff \varphi(a)^{-1}\varphi(x) = e \iff \varphi(x) = \varphi(a) \\
&\iff \varphi(x) = \varphi(b) \iff \varphi(b)^{-1}\varphi(x) = e \\ &\iff \varphi(b^{-1}x) = e \iff b^{-1}x \in K \\
&\iff x \in bK,
\end{align*}
$$
so $aK=bK$.

A: Hint: For any subgroup $H$ and $h\in H$, $H=\{hh': h'\in H\}$.  So, $K=\{a^{-1}bk: k\in K\}$.


text:
Q: Pandas transformation: one-to-many relationship into one-to-one I have a pandas dataframe such that
               APP_ID               SETTING_ID
0                 7              [1009, 962, 430]
1                 8              [103, 914, 890, 218]

I need to transform it such that each SETTING_ID in the list has one-to-one relationship with the APP_ID
               APP_ID          SETTING_ID
0                 7              1009
1                 7              962
2                 8              103
3                 8              914
4                 8              890

A: This is so called unnest
pd.DataFrame({'APP_ID':df.APP_ID.repeat(df.SETTING_ID.str.len()),'SETTING_ID':sum(df.SETTING_ID.tolist(),[])})
Out[367]:
   APP_ID  SETTING_ID
0       7        1009
0       7         962
0       7         430
1       8         103
1       8         914
1       8         890
1       8         218