text:
Q: HTML5 banner, rich media sample I want to find a sample of rich media with added Enabler to look how should I do it properly. As soon as I add Enabler script to my head> tag, will it gather all the metrics that google anlytics need? Or should I add other modules or call some methods?
Can you please send me a sample of rich media banner (or whatever) where I can see proper work with studio HTML5 SDK and Enabler?

A: You can download samples from http://www.richmediagallery.com/create/templates


text:
Q: Multiple people sharing a single unlimited web hosting account: why not? Me and my friends have seen a few of web hosts (ipower, bluehost, etc) which offer unlimited bandwidth + unlimited space + unlimited domains. What's the catch with these hosting plans? I mean, multiple people can buy one account and share the unlimited perks?

A: The catches are limited CPU or compute time, and an actual limit to the actual bandwidth allocation and space allocation. Once you're using N% of the shared hosting on a machine of theirs they're going to explain that while unlimited you've run out of space or bandwidth on a shared server, and need to upgrade to a private, or virtual private server. Also you'll often find that the database load and or count is limited. And personally, I find that's all fine for an individual, and less so for a company or group of people.
There's also dreamhost they allow me to make multiple user accounts and put different domains or subdomains onto different users' accounts, and so they basically support what you're supposing you might do. Not sure how much longer they'll be offering unlimited accounts, but it's been about a year now that I've seen.

A: Occasionally these hosts will shut you down without warning, too, if you exceed some invisible threshold. There was a high-profile case of this with the Maccast website and Godaddy a few years ago. Shared hosting was exceeded, and Godaddy just killed the site without even warning the owner.
Don't rely on the kindness of these companies; they have hundreds (if not thousands) of other users, and have no problem shutting you down if you're a drain on their resources. They will let go of your $5/month if you're costing them $5.50.

A: "Unlimited" is an outright fabrication.
Once you get past a certain point, most hosts will simply start throttling your traffic, and in some cases charge you for overuse(!).
If all of your friends are using it for, say, low profile development sites, then sharing should be fine, but keep in mind unlimited is anything but.
(Did you ever wonder why big blogs often talk about saving bandwidth? Why would they do that if it were unlimited? Because it's not - the better packages have a bandwidth limit, just a very high one)

A: I have a blog at LunarPages. They say that everything is unlimited but I got some warning for high CPU usage and they requested me to install a cache plugin.
Also the space is unlimited but you cannot keep backup copies on the server :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add style to element from user input I have a basic Generator for border radius, where the user types in the number of their choice and it inserts the number into the preview code. However I want to have a preview box that changes according to the number they have inserted. I am half way there but can't seem to figure out the last bit.
HTML:
Border Radius:
<input name="border-radius" id="jj_input" class="jj_input" type="text" size="2" value='' onkeyup='changeRadius()' />
px

border-radius: px;

webkit-border-radius: px;

    Preview Text

Javascript:
function changeRadius(){
    var jj_input = document.getElementById('jj_input').value;
    document.getElementById('radius').innerHTML = jj_input;
    document.getElementById('radius2').innerHTML = jj_input;

    document.getElementById('preview').style.borderRadius = 'WHAT_GOES_HERE?' ;
}

Where is says "WHAT_GOES_HERE?", I want this value to be the same as jj_input.
Any ideas?

A: document.getElementById('preview').style.borderRadius = jj_input + 'px';

We're simply assigning the value of element.style.borderRadius to that of jj_input and concatenating in px.


text:
Q: Angular 6 two dependant asynchronous call in for loop I've a problem with two asynchronous call in a for loop.
This is the scenario: I've an array of ids and for each of them I need to call a rest service. With the response of this service I need to do various operations and then call a second rest service. I use the response of the second service to do stuff. Finally I need to do operations only when all element of the array are processed.
I found a solution like this:
let i = 0;
of(...this.idsArray).pipe(
    map(id => {
        return this.myService.getItemById(id).subscribe()
    }),
    tap(data => this.item = data; //How get first response here??? ),
    map(resp => {
        return this.myService.getCatInfo(this.item.cat).subscribe()
    }),
    tap(res => this.cat = res; //How get second response here???)
).subscribe();

I'm not sure the code is correct but the problem is how I can get the responses of services and use them in tap functions?
Thanks
EDIT:
I'm trying to use concatMap and I get a better behaviour but it still doesn't work:
let i = 0;
of(...this.idsArray).pipe(
    concatMap(id => {
        console.log('first step');
        return this.myService.getItemById(id).subscribe()
    }),
    tap(data => {this.item = data; console.log('second step')}),
    concatMap(resp => {
        return this.myService.getCatInfo(this.item.cat)
    }),
    tap(res => {this.cat = res; console.log('third step')})
).subscribe();

The output is:
first step
second step
first step
third step
second step
first step
third step
second step
...

A: You can look at using the mergeMap operator. This will add the new subscriptions you need to http observables behind the scenes.
Here is a rough idea of what it could look like with your code:
of(...this.idsArray).pipe(
    mergeMap(id => {
        return this.myService.getItemById(id);
    }),
    tap(data => this.item = data; //How get first response here??? ),
    mergeMap(resp => {
        return this.myService.getCatInfo(this.item.cat);
    }),
    tap(res => this.cat = res; //How get second response here???)
).subscribe();

Inside of tap, you can also use the debugger to see what you have at that point.
tap(data => {
  debugger;
  this.item = data;
}),

A: you can use switchMap to avoid subscribe inside subscribe
of(...this.idsArray).pipe(
 switchMap(id => {
     return this.myService.getItemById(id);
 }),
switchMap(data => this.myService.getCatInfo(data.cat)),
tap(res => this.cat = res; //How get second response here???)
).subscribe();


text:
Q: How to interact with two matplotlib.axes.Axes together I made a 3 D animation with two different sets of axes declared as follows:
    fig=plt.figure()
    ax2 = fig.add_subplot(111, projection="3d");
    ax = fig.add_axes(ax2.get_position(), projection="3d", frame_on=False, sharex=ax2, sharey=ax2)
    ax.patch.set_visible(False)
    ax.axis("off")
    ax2.axis("off")

However, if I drag over the animation to change the perspective I'm looking at it from, only one set of axes moves and not both. How can I interact with the entire figure, so that when I drag my mouse both the sets of axes move?
Thanks!

A: You could create a callback function that listens for mouse dragging and keeps the viewpoint of both axes in sync:
def on_move(event):
    ax2.view_init(elev=ax.elev, azim=ax.azim)

fig=plt.figure()
ax2 = fig.add_subplot(111, projection="3d");
ax = fig.add_axes(ax2.get_position(), projection="3d", frame_on=False, sharex=ax2, sharey=ax2)
ax.patch.set_visible(False)

cid = fig.canvas.mpl_connect('motion_notify_event', on_move)


text:
Q: how to disallow insecure connection to http-server npm? I am using below command to create secure http-server,
http-server -a :: -p 8081 --cors -c-1 -S -C cert.pem -K key.pem -r

But with below command I can able to access content,
curl -k https://localhost:8081/

How can I restrict user to not allow insecure connection to http-server ?
I just want to allow connections who verified certificate, no other connection would be allow.
PS: Here I have installed http-server using npm install http-server.

A: It depends on what you mean by "insecure".
curl -k https://localhost:8081/ will open a secure HTTPS connection, the traffic is encrypted. The only thing -k does is to allow a connection to a certificate that you do not trust by default (usually this means that it is not signed by a CA recognized by your system/browser).
There is nothing wrong with self-signed certificates.
The trust you put on the CA is one extra layer, a layer that can help you to realize that something is wrong but that's all.
Since this is a correct HTTPS connection, you cannot restrict anything (I am not even sure what you would like to restrict? Which element would reject the connection? curl already does it by default and the server is happy with its certificate)

EDIT following comment
If you want to make sure that the client that is connecting is the right one then you need to take the other way round and request from your client a certificate.
In this setup, you will (usually) have mutual authentication: the client checks the certificate of the server (which in your case fails because the CA is not recognized but it does not matter) and the server asks the client to provide a certificate the server trusts.
Try searching for "SSL client certificate" (despite TLS replacing SSL, a lot of articles still use SSL wording), an example of one is https://medium.com/@sevcsik/authentication-using-https-client-certificates-3c9d270e8326


text:
Q: I need to add some form validation for telephone field on admin side for magento I need to add some form validation for telephone field on admin side for magento. I am looking for correct file to work on
There's already some validation for required fields on the admin sales_order_create I am trying to find the right file that I can work on for the page sales_order_create. I did some search but still I had no luck on my code base.

A: You can use the following to class method for validating
'validate-phoneStrict'          => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-phoneLax'             => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'

And this can be use as follow:
$fieldset->addField('phone', 'text', array(
            'label'     => Mage::helper('foundation')->__('Phone'),
            'class'     => 'required-entry validate-phoneStrict',
            'required'  => true,
            'name'      => 'phone',
            ));


text:
Q: show singular matrix map interior and surface of a unit sphere into an ellipse The original question image
A $k$-dimensional ellipse, surface and interior, with axes along the standard coordinates is algebraically defined as the set of points $z = (z_1, \ldots , z_k)^T$ satisfying $(z_1/\alpha_1)^2 + \cdots + (z_k/\alpha_k)^2 \leq 1$.
We can have a $k$-dimensional ellipse embedded inside $\mathbb{R}^n$ even in the case $n > k$ by allowing some of the $z_j$ to be identically zero. Using these definitions, show that the matrix $\Sigma = \text{diag}(\sigma_1,...,\sigma_{\min(m,n)}) \in \mathbb{R}^{m \times n}$, where $\sigma_1 \geq \ldots \geq \sigma_{\min (m,n)} \geq 0$, maps the unit sphere $\{x \in \mathbb{R}^n : ||x||_2 \leq 1\}$, surface and interior, to an ellipse.
Under what conditions is the surface of the unit sphere mapped to the surface of the ellipse? (Suggestion: Consider the cases $m \geq n$ and $n > m$ separately. Also, some of the axes of the ellipse may be zero, so it may be convenient to introduce $r \leq \min(m,n)$ such that $\sigma_1 \geq \ldots \geq \sigma_r > 0$.)
I think this is like a SVD question and I found the page here that might be useful: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.3603&rep=rep1&type=pdf
But I still do not quite understand the exact process of mapping the interior and surface of a unit sphere into an ellipse, maybe SVD is doing what I am asking?
Any help will be greatly appreciated.

A: just take an arbitrary point on the surface of the unit sphere, and apply the transformation to it. There will be a condition that results in the transformed point taking on a form of a k-dimensional ellipse.
-Ivo


text:
Q: How does one convert an image to grayscale in OpenGL? This might seem like a simple question but Id like to know the fastest technique for converting an RGBA image to a grayscale image in OpenGL WITHOUT using GLSL. I.e. How do I take an RGBA texture and convert it to a plain single channel texture using the following formula:
output=0.3*RED  +  0.59*GREEN  +  0.11*Blue

A: You might be able to convince GL_DOT3_RGB to do what you want.

A: Well I don't know about "fastest", but you should be able to do the opposite of this tutorial and get the greyscale image you're looking for.  The techniques are the same just backwards.
http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=37


text:
Q: Angular Material Select md-on-close Pass Parameter I would like to pass a parameter to a function with Angular Material Select md-on-close.
With my current code I get undefined returned when I do a console log.
What I have so far.
html
<md-input-container>
    <label>Season</label>
    <md-select  name="season"
                ng-model="cteam.season"
                md-on-close="cteam.getid(season.$id)">

        <md-option ng-repeat="season in cteam.seasons | orderBy: 'name'" value="{{season.name}}">
            {{season.name}}
        </md-option>

    </md-select>
</md-input-container>

controller
(function() {

    angular
        .module('app')
        .controller('CreateTeamController', function() {

            var vm = this;

            vm.getid = function(id) {
                console.log(id);
            };

        });
})();

Update (add app.js code)
app.js
(function() {

    angular
        .module('app', [
            'ngRoute',
            'ngMaterial',
            'ngMessages',
            'firebase'
        ])
        .config(function($routeProvider, $mdThemingProvider){

            $mdThemingProvider
                .theme('default')
                .primaryPalette('deep-purple');

            $routeProvider
                .when('/', {
                    templateUrl: 'views/main.html',
                })
                .when('/create/team', {
                    templateUrl: 'views/create-team.html',
                    controller: 'CreateTeamController',
                    controllerAs: 'cteam',
                })
                .otherwise({
                    redirectTo: '/',
                });
        });

})();

A: See in md-on-close="cteam.getid(season.$id)" season does not refer to season that you use in your ng-repeat. ng-repeat creates a new scope and you are calling that function in it's parent scope.
But you are telling md-select that you want to bind 'selected' season to cteam.season in ng-model="cteam.season".
All you have to do is to change your md-on-close attribute to md-on-close="cteam.getId(cteam.season.$id)" or whatever property you're referencing in your ng-model.


text:
Q: Scanner(JTextfield) rather than Scanner(System.in) I wan to have an inputStream that takes the value of a JTextbox and passes it into the Scanner object.
       Scanner scan = new Scanner (System.in);
        String input = scan.nextLine();
        if (input.equalsIgnoreCase("New Match")) {
            try {
                newMatch(scan);
            } catch (FileNotFoundException e) {
                System.out.println("failed to load");
            } catch (ArithmeticException e) {

            }
        }
        if (input.equalsIgnoreCase("Load Match 1") || input.matches("1")){
            try {
                loadMatch(scan, "One");
            } catch (FileNotFoundException e) {
                System.out.println("failed to load");
            } catch (ArithmeticException e) {

            }
        }
    }

A: You can use a PipedOutputStream (doc) and a PipedInputStream (doc) to create a one-way pipeline which you can then use to route input from a text field into a Scanner.  But you'll still have to figure out how to capture all the output that's going to System.out and display it to your GUI, nicely interwoven with the "echoed" input that came from your text field.
For what it's worth, though, I'll share a little proof-of-concept of half the solution.  This program reads "commands" from a JTextField through a Scanner and produces simulated "responses" to them; a JTextArea keeps a record of the simulated "conversation".  The input "commands" are logged automatically to the JTextArea, much as input from System.in would automatically echo to System.out, and I also explicitly echo them to System.out.  However, my simulated "responses" go not to System.out but directly to the JTextArea`.
package test;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;
import javax.swing.JTextField;

public class PipeTest extends javax.swing.JFrame {

    public PipedInputStream pi;
    private PipedOutputStream po;

    public PipeTest()
    {
        try {
            pi = new PipedInputStream();      // You write data into this end...
            po = new PipedOutputStream(pi);   // ,,, and read it back out at this end.
        } catch (IOException ioe) {
            System.out.println("Failed to initialize pipe: " + ioe.toString());
        }
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents()
    {

        jScrollPane1 = new javax.swing.JScrollPane();
        historyText = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        historyText.setColumns(20);
        historyText.setRows(5);
        jScrollPane1.setViewportView(historyText);

        jTextField1.setText("jTextField1");
        jTextField1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jTextField1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
    {
        JTextField tf = (JTextField) evt.getSource();
        String text = tf.getText();
        byte[] ca = (text + System.getProperty("line.separator")).getBytes();
        try {
            po.write(ca, 0, ca.length);
        } catch (IOException ex) {
            System.out.println("Failed to write to pipe: " + ex.toString());
        }
        historyText.append(text + "\n");
        tf.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException
    {
        PipeTest pt = new PipeTest();
        java.awt.EventQueue.invokeLater(() -> {
            pt.setVisible(true);
        });
        Scanner scn = new Scanner(pt.pi);
        while (scn.hasNextLine()) {
            String line = scn.nextLine();
            System.out.println(line);
            java.awt.EventQueue.invokeLater(() ->
            {
                pt.historyText.append("Response to " + line + "\n");
            });
        }
    }
    // Variables declaration - do not modify
    private javax.swing.JTextArea historyText;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

A: The way I interpret your question is that you have some existing code that is built on reading user input through an instance of Scanner. I think you're asking whether you can pull the text from a JTextField and push that into the instance of Scanner that is already used.
If the above understanding is correct and your Scanner instance is reading from System.in as it is in the code sample then my answer is no, you can't do exactly what you want.
However, you can get somewhat close to what you want.
Here is some code that creates a new Scanner each time the actionPerformed method is called and pushes data from a JTextField into that Scanner by simply passing the text from the text field into the scanner's constructor.
public void actionPerformed(java.awt.event.ActionEvent evt) {
    scanner.close(); //Don't forget to close your scanner before you reassign it
    String data = jTextField1.getText();
    scanner = new Scanner(data);
    //Just to illustrate the results I added a println here
    System.out.println(scanner.nextLine());
}


text:
Q: git commit -a did not work I am kind of a newbie with Git, and I encounter some problems already...
I did clone a repository (on BitBucket) to my machine, and modified a file 'Makefile' and created 3 new ones (c_file, gma.txt and ded_mpi.dat).
Then, I typed to commit these add/changes to the master repository: commit -a and I wrote a message in the text editor)
I have 2 issues here. First, I thought this would commit my changes to the master rep, but it doesn't (I checked it by cloning the master version: my changes are not included).
However, in the rep on my machine, git log contains my message...
I think I missed something with the way Git works :)
git diff prints nothing.
2nd issue:
git status prints:
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
#   c_file
#   gma.txt
#   ded_mpi.dat
nothing added to commit but untracked files present (use "git add" to track)

Files c_file, gma.txt et ded_mpi.dat were committed but not added...I thought commit -a did both 'commit' and 'add'... ??
On the other, nothing in the status about the pre-existing Makefile that I modified...
As you can see, I would need a hand :)
If anyone could help me understand what's going on, it would be great!
Cheers

A: 1.I think you forgot push your commit, like "git push origin master"
2."git commit -a" don't add new file, just commit modified and delete files, you need use "git add ." to prepare commit.

A: First, pay attention to the status message, it's telling you there are untracked files that haven't been added yet and can be done so with
git add .

now, to fix your commit so you don't push 2 commit objects, you can "amend" the current commit object with your newly added files like this:
git commit --amend

now if you do git status you'll have a single commit object ready to push to the remote.
I would strongly advise getting some basics under your belt. Go see Git Immersion for a good starter.

A: first go with : git add .
then : git commit -m"commet message here"
done


text:
Q: fabric.js make active object on top of others when dragging my question is, fabric.js makes active object on top of others when dragging.
I know a property can do this, can't remind.
Thanks.

A: You can do it like this:
canvas.add(red, blue); // add youre objects..

function myDrag(e) {   // funciton on drag (moving)
  e.target.bringToFront();
}

canvas.on({
  'object:moving': myDrag,
});

Want to add more events? Use the Event inspector @ fabricjs
I made a working Fiddle. Hopes it helps...

A: I know it's been a long time since you asked this but I want to answer it if anyone would stuck for that.
This behavior is default in fabric js right know but if you want to change it just set preserveObjectStacking to false when initializing the canvas. See more in documentation.


text:
Q: iPhone SDK measure frequency over iphone mic I need a way to get the frequency from the microphone and determine the average frequency. Is there a library or something to handle this?
Thanks

A: If you're targeting iOS 4 and above, Apple now includes the Accelerate framework.  From Apple's "What's new" page:
http://developer.apple.com/technologies/iphone/whats-new.html#api

Accelerate
Accelerate provides hundreds of mathematical functions optimized for iPhone and iPod touch, including signal-processing routines, fast Fourier transforms, basic vector and matrix operations, and industry-standard functions for factoring matrices and solving systems of linear equations.

A: You'll want to use an FFT, so I'd recommend looking at this Q&A:
Do you know a good and efficient FFT?

A: You can use the EZAudio Class to get the Frequency
Download the Demo Here
and use this method to get Frequency
- (void) fft:(EZAudioFFT *)fft updatedWithFFTData:(float *)fftData bufferSize:(vDSP_Length)bufferSize
 {
     float maxFrequency = [fft maxFrequency];

       NSString *noteName = [EZAudioUtilities noteNameStringForFrequency:maxFrequency
                                                                includeOctave:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [audioPlotFreq updateBuffer:fftData withBufferSize:(UInt32)bufferSize];
            NSLog(@"Frequncy : %f Highest Note : %@",maxFrequency,noteName);
      });
 }


text:
Q: Chrome Devtools says there's issues, but the Issues tab is empty?
In the screenshot above, it indicates that there are 2 issues: 1 orange and 1 blue. However, the Issues tab is empty. These issues have been present on my website for several days, even after restarting Devtools and Chrome. I also disabled the "Enable experimental hide issues menu" experiment.
How can I see these issues?


text:
Q: Inequality $\frac{1}{a+b}+\frac{1}{a+2b}+...+\frac{1}{a+nb}<\frac{n}{\sqrt{a\left( a+nb \right)}}$
Let $a,b\in \mathbb{R+}$ and $n\in \mathbb{N}$. Prove that:
  $$\frac{1}{a+b}+\frac{1}{a+2b}+...+\frac{1}{a+nb}<\frac{n}{\sqrt{a\left( a+nb \right)}}$$

I have a solution using induction, but without induction I can not think of any way to prove this.

A: Here is a proof that is an alternative to and perhaps more straightforward than the ingenious one of Michael Rozenberg.
WOLOG, let $a = 1$.
Since
$$1+t<\Big(1+\frac t2\Big)^2,$$
$$\sum_{i=1}^n \frac b{1+bi}< \int_0^{bn}\frac1{1+t}\,dt<\int_0^{bn}\frac{1+\frac t2}{(1+t)^\frac32}\,dt =\frac{t}{\sqrt{1+t}}\bigg|_{t=0}^{bn}.$$
QED
Indeed, from the derivation above, the left hand side of the original inequality has a tighter upper bound of $\frac1b\ln\big(1+\frac ba n\big)$.

A: For positives $a$ and $b$ By C-S we obtain:
$$\left(\frac{1}{a+b}+\frac{1}{a+2b}+\cdots+\frac{1}{a+nb}\right)^2$$
$$\leq n\left(\frac{1}{(a+b)^2}+\frac{1}{(a+2b)^2}+\cdots+\frac{1}{(a+nb)^2}\right)$$
$$<n\left(\frac{1}{(a+\frac{b}{2})(a+\frac{3b}{2})}+\frac{1}{(a+\frac{3b}{2})(a+\frac{5b}{2})}+\cdots+\frac{1}{(a+\frac{(2n-1)b}{2})(a+\frac{(2n+1)b}{2})}\right)$$
$$=\frac{n}{b}\left(\frac{1}{a+\frac{b}{2}}-\frac{1}{a+\frac{3b}{2}}+\frac{1}{a+\frac{3b}{2}}-\frac{1}{a+\frac{5b}{2}}+\cdots+\frac{1}{a+\frac{(2n-1)b}{2}}-\frac{1}{a+\frac{(2n+1)b}{2}}\right)$$
$$=\frac{n}{b}\left(\frac{1}{a+\frac{b}{2}}-\frac{1}{a+\frac{(2n+1)b}{2}}\right)=\frac{n^2}{(a+\frac{b}{2})(a+\frac{(2n+1)b}{2})}<\frac{n^2}{a(a+nb)}.$$
Done!


text:
Q: height 100% not working in CSS I am learning CSS and while practicing I was trying to copy this page.
Here is my screenshot. I want the left column (the one with white background and blue border-bottom) to fill up 100% in height. The whole middle portion is divided into three boxes(div). First there is a "columns" div which contain two divs "left_column" and "right_column". The border of "columns" div can be seen in yellow color. I tried setting "height:100%" for "left_column" but its not working. Can anyone please suggest me what I am doing wrong?
Here is my css file:
#left_column {
    width: 65%;
    height: 100%;
    float: left;
    font-size: 80%;
    color: #414342;
    background-color: white;
    border-bottom: 1px solid blue;
    text-align: justify;
    overflow: hidden;
}

#left_column h2 {
    color: #3399FF;
    padding: 0 15px;
}

#left_column p {
    padding: 0 15px;
}

#right_column {
    width: 35%;
    float: right;
    font-size: 80%;
    background-color: #424D47;
    color: #8BC7D3;
}

#right_column h2,h3,h4 {
    color: #3399FF;
    padding: 0 15px;
}

#right_column p {
    padding: 0 15px;
}

#columns {
    border: 1px solid yellow;
    overflow: hidden;
    margin: 0;
}

#columns p {
    font-family: "sans serif";
    line-height: 1.5em;
}

Here is my HTML file:
<!DOCTYPE html>

    <title>Cloudy Water Sports</title>
    <link rel="stylesheet" href="main.css" />

CLOUDY WATER SPORTS

HOME

NEWS

BLOG

GALLERY

ABOUT CWS

CONTACT

Hello!

                    Free Cloudy Water Sports template is yours to use.

                    Ulysses, Ulysses - Soaring through all the galaxies. In search of Earth, flying in to the night. Ulysses, Ulysses - Fighting evil and tyranny, with all his power, and with all of his might. Ulysses - no-one else can do the things you do. Ulysses - like a bolt of thunder from the blue. Ulysses - always fighting all the evil forces bringing peace and justice to all.

One for all and all for one.

I never spend much time in School.

Soaring through all the galaxies.

                    One for all and all for one, Muskehounds are always ready. One for all and all for one, helping everybody. One for all and all for one, it's a pretty story. Sharing everything with fun, that's the way to be. One for all and all for one, Muskehounds are always ready. One for all and all for one, helping everybody. One for all and all for one, can sound pretty corny. If you've got a problem chum, think how it could be.

What's New?

There's a voice

There's a voice that keeps on calling me. Down the road, that's where I'll always be. More…

Every stop I make

Every stop I make, I make a new friend. Can't stay for long, just turn around and I'm gone again. Maybe tomorrow, I'll want to settle down, Until tomorrow, I'll just keep moving on. More...

Hong Kong Phooey

Hong Kong Phooey, number one super guy. Hong Kong Phooey, quicker than the human eye. He's got style, a groovy style, and a car that just won't stop. More…

Archive

One for all

Can't stay for long

Muskehounds

Hong Kong Phooey

Copyright © 2006 YOUR SITE NAME.

Design by 360guide.info

A: Right.
The way this is working is, you have a parent element with no height. So any child that goes in the parent cannot have a percentage height because:
20% of nothing = nothing
100% of nothing = nothing

If the child has content it will default to the size that the content is.
If you have the parent a height in px:
20% of 100px = 20px
100% of 100px = 100px

So thats how that works.

Solution to your code, as its the right column that is bigger we could use display: table; this will allow us to get the cells to be equal height (whatever the bigger height is).
Change CSS:
#columns {
    display: table;
    border: 1px solid yellow;
    overflow: hidden;
    margin: 0;
    height: 800px;
}
#left_column {
    width: 65%;
    height: 100%;
    display: table-cell;
    font-size: 80%;
    color: #414342;
    background-color: white;
    border-bottom: 1px solid red;
    text-align: justify;
    overflow: hidden;
}
#right_column {
    display: table-cell;
    width: 35%;
    font-size: 80%;
    background-color: #424D47;
    color: #8BC7D3;
}

DEMO
Any question feel free to ask.

A: I suggest option emulation of equal height columns CODEPEN

        Header: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tortor. Praesent dictum, libero ut tempus dictum, neque eros elementum mauris, quis mollis arcu velit ac diam. Etiam neque. Quisque nec turpis. Aliquam arcu nulla, dictum et, lacinia a, mollis in, ante. Sed eu felis in elit tempor venenatis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut ultricies porttitor purus. Proin non tellus at ligula fringilla tristique. Fusce vehicula quam. Curabitur vel tortor vitae pede imperdiet ultrices. Sed tortor.

                Content: Sed placerat accumsan ligula. Aliquam felis magna, congue quis, tempus eu, aliquam vitae, ante. Cras neque justo, ultrices at, rhoncus a, facilisis eget, nisl. Quisque vitae pede. Nam et augue. Sed a elit. Ut vel massa. Suspendisse nibh pede, ultrices vitae, ultrices nec, mollis non, nibh. In sit amet pede quis leo vulputate hendrerit. Cras laoreet leo et justo auctor condimentum. Integer id enim. Suspendisse egestas, dui ac egestas mollis, libero orci hendrerit lacus, et malesuada lorem neque ac libero. Morbi tempor pulvinar pede. Donec vel elit.
Expand column

            Right Sidebar: Integer velit. Vestibulum nisi nunc, accumsan ut, vehicula sit amet, porta a, mi. Nam nisl tellus, placerat eget, posuere eget, egestas eget, dui. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In elementum urna a eros. Integer iaculis. Maecenas vel elit.
Expand column

        Footer: Mus elit Morbi mus enim lacus at quis Nam eget morbi. Et semper urna urna non at cursus dolor vestibulum neque enim. Tellus interdum at laoreet laoreet lacinia lacinia sed Quisque justo quis. Hendrerit scelerisque lorem elit orci tempor tincidunt enim Phasellus dignissim tincidunt. Nunc vel et Sed nisl Vestibulum odio montes Aliquam volutpat pellentesque. Ut pede sagittis et quis nunc gravida porttitor ligula.

body {
    font: 12px/18px Arial, sans-serif;
    width: 100%;
}
/* Begin of styles for the demo (you can remove them) */
a.expand {
    width: 90px;
    display: block;
    margin: 10px 0 0;
}
a.expand:hover {
    height: 500px;
}
/* End of of styles for the demo */
.wrapper {
    width: 960px;
    margin: 0 auto;
}

/* Header
-----------------------------------------------------------------------------*/
.header {
    height: 150px;
    background: #FFE680;
}

/* Middle
-----------------------------------------------------------------------------*/
.middle {
    border-right: 250px solid #FFACAA;
    position: relative;
}
.middle:after {
    display: table;
    clear: both;
    content: '';
}
.container {
    width: 100%;
    float: left;
    overflow: hidden;
    margin-right: -100%;
}
.content {
    padding: 0 20px;
}

/* Right Sidebar
-----------------------------------------------------------------------------*/
.right-sidebar {
    float: right;
    margin-right: -250px;
    width: 250px;
    position: relative;
    background: #FFACAA;
}

/* Footer
-----------------------------------------------------------------------------*/
.footer {
    height: 100px;
    background: #BFF08E;
}

A: try this code:
#columns{
    position:relative;
    background-color:#fff;
}
#left_column{
     width: 65%;
    float: left;
    font-size: 80%;
    color: #414342;
    text-align: justify;
    position:relative;
    z-index:1;
}
#right_column {
    width: 35%;
    float: right;
    font-size: 80%;
    background-color: #424D47;
    color: #8BC7D3;
    position:relative;
    z-index:1;
}
.right_dummy{
    position:absolute;
    width: 35%;
    height:100%;
    background-color: #424D47;
    z-index:0'
    right:0;
    top:0;
}

  .clearB{
     clear:both;
   }

html:

TEXT HERE.....

TEXT HERE.....

A: add this css's:
#columns, #outer_frame, html, body, form {
height:100%;

}
For height:100% to work propely all container parents must also have the height set to 100%


text:
Q: Finding second largest item in array not working as expected My program to find the second smallest number works as expected, but when running the code to find the second largest number, the second largest output is not correct. I did the second function in a similar way, but flipped the greater than sign. What is the best way to fix the code?
def second_smallest():
    num_list = [1,5,6,44,5,7,2,444,3]
    smallest_num = num_list[0]
    second_smallest_num = num_list[1]
    for i in num_list:
        if i < smallest_num:
            smallest_num = i
        elif smallest_num < i < second_smallest_num:
            second_smallest_num = i
    print("Smallest Number:", smallest_num)
    print("Second smallest number:", second_smallest_num)

def second_largest():
    num_list = [1,5,6,44,5,7,2,444,3]
    largest_num = num_list[0]
    second_largest_num = num_list[1]
    for i in num_list:
        if i > largest_num:
            largest_num = i
        elif second_largest_num < i < largest_num:
            second_largest_num = i
    print("Largest:", largest_num)
    print("Second largest:", second_largest_num)

A: When you assign the new highest number, you need to assign the second highest to the old highest number.
def second_smallest():
     num_list = [1,5,6,44,5,7,2,444,3]
     smallest_num = num_list[0]
     second_smallest_num = num_list[1]
     for i in num_list:
         if i < smallest_num:
            smallest_num = i
         elif smallest_num < i < second_smallest_num:
         second_smallest_num = i
     print("Smallest Number:", smallest_num)
     print("Second smallest number:", second_smallest_num)

    def second_largest():
    num_list = [1,5,6,44,5,7,2,444,3]
    largest_num = num_list[0]
    second_largest_num = num_list[1]
    for i in num_list:
        if i > largest_num:
            second_largest_num = largest_num
            largest_num = i
        elif second_largest_num < i < largest_num:
            second_largest_num = i
    print("Largest:", largest_num)
    print("Second largest:", second_largest_num)

    second_smallest()
    second_largest()

A: You did not set a variable to hold the largest value. It would work if it you create a tmp variable to hold the largest value and assigned it to the second largest afterwards
def second_largest():
num_list = [1,5,6,44,5,7,2,444,3]
largest_num = num_list[0]
second_largest_num = num_list[1]
for i in num_list:
    if i > largest_num:
        tmp = largest_num
        largest_num = i
        second_largest_num = tmp
    elif second_largest_num < i < largest_num:
        second_largest_num = i
print("Largest:", largest_num)
print("Second largest:", second_largest_num)

Also, if would be better if you start the iteration from index 2 of the array as first and second is already assigned.

A: at the top, where you declare
    num_list = [1,5,6,44,5,7,2,444,3]
    smallest_num = num_list[0]
    second_smallest_num = num_list[1]

Do you realise that you are accessing the zeroth and first elements in the list, that is
smallest_num = 1
second_smallest_num = 5

And incidentally the zeroth element (ie = 1) just happens to be the smallest element in that list, which is why it works for one of the functions but not the other.
What should work, is
def second_largest():
num_list = [1,5,6,44,5,7,2,444,3]
largest_num = max(num_list)
### SOME FUNCTION THAT TAKES IN THAT LIST, REMOVES THE LARGEST NUM ELEMENT, AND THEN FINDS AND RETURNS THE NEXT LARGEST ELEMENT - I'll leave this to you ##
for i in num_list:
    if i > largest_num:
        largest_num = i
    elif second_largest_num < i < largest_num:
        second_largest_num = i
print("Largest:", largest_num)
print("Second largest:", second_largest_num)

A: Why not use heapq?
>>> import heapq
>>> heapq.nlargest(2, num)
[10, 8]
>>> heapq.nsmallest(2, num)
[1, 2]
>>>

More information on https://docs.python.org/2/library/heapq.html

A: The simplest approach here is simply using the python builtins max() and min(). Note that we're making a copy of the incoming list, so that the original num_list sn't affected by the remove():
num_list = [1,5,6,44,5,7,2,444,3]

def second_smallest(list):
    temp_num_list = list.copy()
    temp_num_list.remove(min(temp_num_list))
    smallest_num = min(list)
    second_smallest_num = min(temp_num_list)
    return smallest_num, second_smallest_num

def second_largest(list):
    temp_num_list = list.copy()
    temp_num_list.remove(max(temp_num_list))
    largest_num = max(list)
    second_largest_num = max(temp_num_list)
    return largest_num, second_largest_num

largest_num, second_largest_num = second_largest(num_list)
smallest_num, second_smallest_num = second_smallest(num_list)

print("Largest:", largest_num)
print("Second largest:", second_largest_num)

print("Smallest:", smallest_num)
print("Second smallest:", second_smallest_num)

Output:
Largest: 444
Second largest: 44
Smallest: 1
Second smallest: 2

There's no nead to do any comparisons. We're simply finding the max and min, then removing them from a copy, and subsequently taking the max and min from the remainders.
Note that I've abstracted num_list from the functions, but leaving them in the functions would work. This approach allows you to reuse the functions with different lists in your code.
Alternatively, as mentioned in another answer here, from @andercruzbr, you can import the heapq module, and simply do:
import heapq

num_list = [1,5,6,44,5,7,2,444,3]

def smallest_nums(list):
    return heapq.nsmallest(2, num_list)

def largest_nums(list):
    return heapq.nlargest(2, list)

print("Largest:", largest_nums(num_list)[0])
print("Second largest:", largest_nums(num_list)[1])

print("Smallest:", smallest_nums(num_list)[0])
print("Second smallest:", smallest_nums(num_list)[1])

Output:
Largest: 444
Second largest: 44
Smallest: 1
Second smallest: 2


text:
Q: In a semigroup $S=\{a_1, \ldots, a_n\}$, any product $a_1 * \ldots * a_i, 1 \le i \le n$ is unique
Possible Duplicate:
How does one actually show from associativity that one can drop parentheses?

Claim: Let $(S, *)$ be a semigroup and $a_1, \ldots, a_n \in S$. Then $a_1 * \ldots * a_n$ is unique.
I'm having trouble proving this claim, because I'm a beginner, I'm sure, and would like some guidance if you please. Here's my attempt so far:
Edit: Following AndréNicolas advice, here's my second attempt.
Proof: My strategy is the following. Given a set S of elements:

*

*Define the set of all products;

*Define the set of all normalized products;

*Show how we can normalize all products;

*Show that all products are equal to their normalized version.

Step 1: Define the set of all products:
Let $*_S$, the set of all products over $S$, be defined inductively as follows:

*

*$a \in *_S$, if $a \in S$;

*$(a * x) \in *_S$, if $a \in S$ and $x \in *_S$;

*$(x * a) \in *_S$, if $a \in S$ and $x \in *_S$

Step 2: Define the set of all normalized products:
Let $\star_S$, the set of all normalized products over $S$, be defined inductively as follows:

*

*$a \in \star_S$, if $a \in S$;

*$(a * x) \in \star_S$, if $a \in S$ and $x \in \star_S$

Step 3: Show how we can normalize all products:
Let $\searrow_S: *_S \to \star_S$ be the following application, also defined inductively:
$\begin{array}{rcl}
a & \mapsto & a
\\ (a * x) & \mapsto & (a * \searrow_S(x))
\\ (x * a) & \mapsto & \begin{cases}
(a\prime * a) &, \searrow_S(x) = a\prime
\\
(a\prime * \searrow_S(y * a)) & , \searrow_S(x) = (a\prime * y)
\end{cases}
\end{array}$

Step 4: Show that all products are equal to their normalized version:
This proceeds by strong induction over $*_S$. Let $\Phi(x) \equiv x = \searrow_S(x)$.

*

*$a = \searrow_S(a) \equiv a = a$;

*Suppose $x = \searrow_S(x)$. It's left to show that $(a * x) = \searrow_S(a * x) \equiv (a * x) = (a * \searrow_S(x)) \equiv (a * x) = (a * x)$.

*Suppose $x = \searrow_S(x)$. It's left to show that $(x * a) = \searrow_S(x * a)$. There are two cases:

*

*$\searrow_S(x) = a\prime$. Then $(x * a) = \searrow_S(x * a) \equiv (a\prime * a) = (a\prime * a)$.

*$\searrow_S(x) = (a\prime * y)$. Then $(x * a) = \searrow_S(x * a) \equiv ((a\prime * y) * a) = (a\prime * \searrow_S(y * a))$. and this where I am stuck now. I am not sure how strong induction plays, in order to develop this further. Can you please criticise what I've done so far?

Thanks for taking the time to read this question of mine.
Best wishes,


text:
Q: Obtain approximate Hessian using FindMinimum According to the documentation, when FindMinimum is told to use the method "QuasiNewton" on a unconstrained problem, it uses the BFGS approximation to the Hessian matrix of the function being optimized. How can I recover the Hessian matrix computed by Mathematica using StepMonitor, EvaluationMonitor or any other devious trick?

A: Unfortunately, this requires a lot more devious trickery than I would have preferred. As noted in the documentation at tutorial/UnconstrainedOptimizationQuasiNewtonMethods, the Hessian is not formed directly in the BFGS method, so we have to recover it from the Cholesky factors. However, all of this is done inside the kernel where we cannot access it using ordinary methods, and the only way I can see to obtain these factors is to hook calls to the BLAS function *TRSV (called as LinearAlgebra`BLAS`TRSV in Mathematica) and extract its arguments directly. Needless to say, this is hardly likely to be particularly robust, but it hopefully it will work well enough for your needs.
Let us define:
approximateHessianList[f_, vars_, start_] :=
  With[{fmarg2 = Thread[{vars, start}]},
   Module[{steps, lowerTriangles, upperTriangles},
    Internal`InheritedBlock[{LinearAlgebra`BLAS`TRSV},
     Unprotect[LinearAlgebra`BLAS`TRSV];
     trsv : LinearAlgebra`BLAS`TRSV[uplo_, trans_, diag_, a_, x_] /; (
       Switch[
        trans,
        "N", Sow[LowerTriangularize[a], "LowerTriangle"],
        "T", Sow[UpperTriangularize[a], "UpperTriangle"]
       ]; True
      ) := trsv;
     Protect[LinearAlgebra`BLAS`TRSV];
     {steps, lowerTriangles, upperTriangles} =
      Reap[
       FindMinimum[
        f, fmarg2,
        Method -> {"QuasiNewton", "StepMemory" -> Infinity},
        StepMonitor :> Sow[vars, "Step"]
       ], {"Step", "LowerTriangle", "UpperTriangle"}
      ][[2, {1, 2, 3}, 1]];
     Transpose[{steps, MapThread[Dot, {lowerTriangles, upperTriangles}]}]
    ]
   ]
  ];
SetAttributes[approximateHessianList, HoldAll];

We may now write:
approximateHessianList[Cos[x^2 - 3 y] + Sin[x^2 + y^2], {x, y}, {1, 1}]

which gives a list of steps in the BFGS optimization along with the approximate Hessians evaluated at those points. For the sake of brevity (and because it is obviously the most accurate), let us take only the last of these:

{{1.37638, 1.67868}, {{15.1553, 0.986982}, {0.986982, 20.2017}}}

which we may compare to the exact Hessian evaluated at this point:
D[Cos[x^2 - 3 y] + Sin[x^2 + y^2], {{x, y}, 2}] /. {
  x -> 1.376384972443001`, y -> 1.6786760817546214`
 }

{{15.1555, 0.983708}, {0.983708, 20.2718}}

Clearly, it is not a bad approximation.
Now, some caveats. Since the logic of the code inside the kernel is completely opaque, I am not sure whether this business with the upper and lower triangles is really necessary, since the argument a of LinearAlgebra`BLAS`TRSV appears to be the same for successive calls, firstly with trans == "N" and then with trans == "T". However, this represents at most an inefficiency. A more serious problem is that I am not sure whether the first Hessian obtained using this method corresponds to the initial point, $(x,y)=(1,1)$ , or the point at the end of the first step, which here is $(x,y)=(0.811216, 1.68144)$ . While this does not really matter if the approximation has converged, it does influence the interpretation of the earlier approximations substantially, so hopefully someone with access to the kernel code will be able to clarify this aspect of FindMinimum`QuasiNewton's behaviour.

A: Using Experimental`NumericalFunction framework directly (FindMinimum uses it under the hood) it is straightforward to get the numerical approximation of the Hessian:
f = Experimental`CreateNumericalFunction[{x, y},
   Cos[x^2 - 3 y] + Sin[x^2 + y^2], {1}, Hessian -> FiniteDifference];

f["Hessian"[{1.376384972443001`, 1.6786760817546214`}]]

{{{15.1555, 0.983708}, {0.983708, 20.2718}}}


text:
Q: How do i add an Object to end of an array in javascript. array.push seams not working for object here let address_book = [];
    function myFunction() {
        let contact_name, contact_email, contact_phone;
        contact_name = document.getElementById("contact_name").value;
        contact_email = document.getElementById("contact_email").value;
        contact_phone = document.getElementById("contact_phone").value;

        address_book.push({
            name: contact_name,
            email: contact_email,
            phone: contact_phone
        })
            alert(address_book)
            console.log(tempObj)
    }

</script>

it works if i push any of the input to the array, but not working when i push the object

A: This code has some problems:

*

*You aren't calling the function.

*address_book.push is working, but transforming objects to strings result in something like [object Object]. If you want a representation of the object use something like alert(JSON.stringify(address_book)).

*tempObj is not defined.

A: Do it like below:
let address_book = [];
    function myFunction() {

        var tempObj = {};
        tempObj.contact_name = document.getElementById("contact_name").value;
        tempObj.contact_email = document.getElementById("contact_email").value;
        tempObj.contact_phone = document.getElementById("contact_phone").value;

        address_book.push(tempObj)
        console.log(tempObj)
    }
            alert(address_book)

</script>

Explanation:
You were not creating any object to push into the array. First you need to create a tempObj every time you want to push a new object into your address_book. Above code will perfectly fine.

A: I'd do it this way:
var address_book = [];
var i = 0;

function myFunction() {
        let contact_name, contact_email, contact_phone;
        contact_name = document.getElementById("contact_name").value;
        contact_email = document.getElementById("contact_email").value;
        contact_phone = document.getElementById("contact_phone").value;
        var user = {
            name: contact_name,
            email: contact_email,
            phone: contact_phone
        }
        address_book[i] = user;
        i++;
            alert(address_book)
    }


text:
Q: C# WebAPI Garbage Collection I just delivered my first C# WebAPI application to the first customer. Under normal load, performance initially is even better than I expected. Initially.
Everything worked fine until, at some point, memory was up and garbage collection started running riot (as in "It collects objects that are not yet garbage"). At that point, there were multiple W3WP threads with some ten gigs of ram altogether, and single-digit gigs per worker. After a restart of the IIS everything was back to normal, but of course the memory usage is rising again.
Please correct me if I am wrong, but

*

*Shouldn't C# have automatic garbage collection?

*Shouldn't it be easy for GC to collect the garbage of a WebAPI application?

And please help me out:

*

*How can I explicitly state what GC should collect, thus preventing memory leaks? Is someBigList = null; the way to go?

*How can I detect where the memory leaks are?

EDIT: Let me clarify some things.
My .NET WebAPI application is mostly a bunch of
public class MyApiController:ApiController
{
    [HttpGet]
    public MyObjectClass[] MyApi(string someParam) {
        List<MyObjectClass> list = new List<MyObjectClass>();
        ...
        for/while/foreach {
            MyObjectClass obj = new MyObjectClass();
            obj.firstStringAttribute = xyz;
            ...
            list.Add(obj);
        }
        return list.ToArray();
    }
}

Under such conditions, GC should be easy: after "return", all local variables should be garbage. Yet with every single call the used memory increases.
I initially thought that C# WebAPI programs behave similar to (pre-compiled) PHP: IIS calls the program, it is executed, returns the value and is then completely disposed off.
But this is not the case. For instance, I found static variables to keep their data between runs, and now I disposed of all static variables.
Because I found static variables to be a problem for GC:
 internal class Helper
 {
     private static List<string> someVar = new List<string>();
     internal Helper() {
         someVar=new List<string>();
     }
     internal void someFunc(string str) {
         someVar.Add(str);
     }
     internal string[] someOtherFunc(string str) {
         string[] s = someVar.ToArray();
         someVar=new List<string>();
         return s;
     }
 }

Here, under low-memory conditions, someVar threw a null pointer error, which in my opinion can only be caused by GC, since I did not find any code where someVar is actively nullified by me.
I think the memory increase slowed down since I actively set the biggest array variables in the most often used Controllers to null, but this is only a gut feeling and not even nearly a complete solution.
I will now do some profiling using the link you provided, and get back with some results.

A:
Shouldn't C# have automatic garbage collection?

C# is a programming language for the .NET runtime, and .NET brings the automatic garbage collection to the table. So, yes, although technically C# isn't the piece that brings it.

Shouldn't it be easy for GC to collect the garbage of a WebAPI application?

Sure, it should be just as easy as for any other type of .NET application.
The common theme here is garbage. How does .NET determine that something is garbage? By verifying that there are no more live references to the object. To be honest I think it is far more likely that you have verified one of your assumptions wrongly, compared to there being a serious bug in the garbage collector in such a way that "It collects objects that are not yet garbage".
To find leaks, you need to figure out what objects are currently held in memory, make a determination whether that is correct or not, and if not, figure out what is holding them there. A memory profiler application would help with that, there are numerous available, such as the Red-Gate ANTS Memory Profiler.
For your other questions, how to make something eligible for garbage collection? By turning it into garbage (see definition above). Note that setting a local variable to null may not necessarily help or be needed. Setting a static variable to null, however, might. But the correct way to determine that is to use a profiler.
Here are some shot-in-the-dark type of tips you might look into:

*

*Look at static classes, static fields, and static properties. Are you storing data there that is accumulating?

*How about static events? Do you have this? Do you remember to unsubscribe the event when you no longer need it?

*And by "static fields, properties, and events", I also mean normal instance fields, properties and events that are held in objects that directly or indirectly are stored in static fields or properties. Basically, anything that will keep the objects in memory.

*Are you remembering to Dispose of all your IDisposable objects? If not, then the memory being used could be unmanaged. Typically, however, when the garbage collector collects the managed object, the finalizer of that object should clean up the unmanaged memory as well, however you might allocate memory that the GC algorithm isn't aware of, and thus thinks it isn't a big problem to wait with collection. See the GC.AddMemoryPressure method for more on this.


text:
Q: How do I stop MutationObserver from inserting my Chrome Extension multiple times on a SPA website? For my Chrome Extension,
I'm searching multiple classes/id's to then include their text with some HTML I'm inserting into the website.
When I run the extension,
the HTML widget I'm inserting is inserted multiple times but should only be done once.
I realize MutationObserver is intended to check for every DOM change and seemingly inserts my widget every time that happens I presume. However, I'm not sure how best to approach making sure the widget is only inserted once.
I tried using observer.disconnect(); which helps on initial load to insert the widget once but then it won't re-insert the widget on return to the page – will only on refresh. Couldn't figure out a way to turn observe back on.
Not sure if disconnect and reconnect is even a smart path but it's what I came up with.
In the attached screenshot, you can see it keeps adding the widget with DOM changes.
How should I approach fixing this?
Thank you!
Link to download the extension
manifest.json
{
  "manifest_version": 3,
  "name": "Test SO Mutation Answer",
  "description": "Example for StackOverflow",
  "version": "0.0.1",

  "host_permissions": ["<all_urls>"],
  "permissions": ["storage", "activeTab", "scripting", "tabs", "webNavigation"],

  "content_scripts": [
    {
      "matches": ["https://www.zillow.com/*"],
      "js": ["ballpark.js"],
      "css": ["main.css"]
    }
  ],

  "web_accessible_resources": [
    {
      "resources": ["/images/*"],
      "matches": ["<all_urls>"]
    }
  ]
}

ballpark.js
const observer = new MutationObserver(function() {
  if (document.getElementsByClassName('ds-action-bar')[0]) {
    if (document.querySelector('[data-testid="price"] span') && document.querySelector('.ds-expandable-card .eUxMDw')) {
      console.log("All data found");
      startWidget();

      if (document.getElementById('ballpark-container')) {
        console.log("Do nothing, BP exists");
      } else {
        console.log("Adding BP...");
        insertWidget();
      }
    } else {
      console.log("Cannot find all data");
    }

  } else {
    offerPrice = undefined;
    monthlyPITI = undefined;
  }
})

const target = document.querySelector('body');
const config = { childList: true };
observer.observe(target, config);

var offerPrice;
var monthlyPITI;

function startWidget() {
  getAskingPrice();
  getExpenses();
}

// Get Price from Zillow
function getAskingPrice() {
  var askingPrice = document.querySelector('[data-testid="price"] span');
  if(askingPrice !== null) {
    offerPrice = parseFloat(askingPrice.innerText.replace(/\$|,/g, ''));
    console.log(offerPrice + " Offer Price");
  } else {
    console.log("Null Asking Price Div");
  }
}

function getExpenses() {
  var monthlyPITIZillow = document.querySelector('.ds-expandable-card .eUxMDw');
  if (monthlyPITIZillow !== null) {
    monthlyPITI = parseFloat(monthlyPITIZillow.innerText.replace(/\$|,/g, ''));
    console.log(monthlyPITI + " PITI");
  } else {
    console.log("Null Monthly PITI Div");
  }
}

// Find Zillow widget to insert the extension widget
function insertWidget() {
  const select_div_for_bpd = document.querySelector('div.Spacer-c11n-8-65-2__sc-17suqs2-0');
  if(select_div_for_bpd !== null) {
    const ballpark_container = document.createElement("div");
    ballpark_container.setAttribute("id", "ballpark-container");
    select_div_for_bpd.appendChild(ballpark_container);

    ballpark_container.innerHTML = `

${offerPrice}
 Offer Price

${monthlyPITI}
 Monthly PITI

    `;
  } else {
    console.log("Cannot insert your widget");
  }
}


text:
Q: Issue with MLRun Spark service start and impact all Jupyter notebooks I reconfigured Spark infrastructure in K8s (as part of MLRun/Iguazio platform) and after that, I got a lot of issues in level of services:

*

*Spark service (with information Failed)

*All jupyter notebooks (with information Failed dependencies)

and also general error/message:
Some services have not been successfully deployed. Check the services status as shown below.

See the print screen
I changed only amount of RAM (1-30 GB RAM), vCPU (1-14) and Replicas (3).
Did you get the similar issue and how to avoid the situation?

A: It was human mistake, the solution was easy and the key problem was in Spark service configuration (I configured extremely small vCPU values and it generated timeouts for Spark service):

*

*I used setting vCPU in the range 1-14 but I used default units millicpu (not cpu)

*After setup correct units cpu and restart of Spark service, everything was fine.

Wrong setting
Correct setting


text:
Q: Stop words analyzer in elasticsearch in a cluster I want to know that analyzer (in elasticsearch) should only be implemented on master node or has to be implemented on all the nodes separately?
Could not find an accurate answer.
Please help!
Thanks

{
filter: {
spanish_stemmer: {
type: "stemmer",
language: "spanish"
},
spanish_stop: {
type: "stop",
stopwords: "_spanish_"
}
},
my_analyzer: {
spanish: {
filter: [
"lowercase",
"spanish_stop",
"spanish_stemmer"
],
tokenizer: "standard"
}
},
mappings: {
customparent: {
properties: {
name: {
type: "string",
analyzer: "my_analyzer"
},
title: {
type: "string",
analyzer: "my_analyzer"
},
fullImageAltDescription: {
type: "string",
analyzer: "my_analyzer"
}
}
}
}
}

Adding Logs : -
I am using Elasticsearch(2.4.1v) Spring data transport client to fetch the data from elasticsearch got stuck with below error  : -
org.elasticsearch.action.search.SearchPhaseExecutionException: all shards failed
    at org.elasticsearch.action.search.AbstractSearchAsyncAction.onFirstPhaseResult(AbstractSearchAsyncAction.java:206) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.action.search.AbstractSearchAsyncAction$1.onFailure(AbstractSearchAsyncAction.java:152) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.action.ActionListenerResponseHandler.handleException(ActionListenerResponseHandler.java:46) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.TransportService$DirectResponseChannel.processException(TransportService.java:872) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.TransportService$DirectResponseChannel.sendResponse(TransportService.java:850) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.TransportService$4.onFailure(TransportService.java:387) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:39) ~[elasticsearch-2.4.0.jar:2.4.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_101]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_101]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_101]
Caused by: org.elasticsearch.index.query.QueryParsingException: [match] analyzer [my_analyzer] not found
    at org.elasticsearch.index.query.MatchQueryParser.parse(MatchQueryParser.java:101) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.index.query.IndexQueryParserService.innerParse(IndexQueryParserService.java:320) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:223) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:218) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.query.QueryParseElement.parse(QueryParseElement.java:33) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.SearchService.parseSource(SearchService.java:856) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.SearchService.createContext(SearchService.java:667) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:633) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.SearchService.executeDfsPhase(SearchService.java:264) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:360) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:357) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376) ~[elasticsearch-2.4.0.jar:2.4.0]
    at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37) ~[elasticsearch-2.4.0.jar:2.4.0]
    ... 3 common frames omitted
00:52:06.100 [http-bio-8080-exec-3] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
00:52:06.100 [http-bio-8080-exec-3] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Sep 05, 2017 12:52:06 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/api] threw exception [Request processing failed; nested exception is Failed to execute phase [dfs], all shards failed; shardFailures {[tdPbTD9IQhSuvkFMYt1WbA][catalogviews][0]: RemoteTransportException[[Shellshock][my_ip:9300][indices:data/read/search[phase/dfs]]]; nested: SearchParseException[failed to parse search source [{"from":0,"size":10,"query":{"match":{"title":{"query":"Top Coat","type":"boolean","operator":"OR","analyzer":"my_analyzer","fuzziness":"1","minimum_should_match":"95%"}}}}]]; nested: QueryParsingException[[match] analyzer [my_analyzer] not found]; }{[tdPbTD9IQhSuvkFMYt1WbA][catalogviews][1]: RemoteTransportException[[Shellshock][my_ip:9300][indices:data/read/search[phase/dfs]]]; nested: SearchParseException[failed to parse search source [{"from":0,"size":10,"query":{"match":{"title":{"query":"Top Coat","type":"boolean","operator":"OR","analyzer":"my_analyzer","fuzziness":"1","minimum_should_match":"95%"}}}}]]; nested: QueryParsingException[[match] analyzer [my_analyzer] not found]; }{[tdPbTD9IQhSuvkFMYt1WbA][catalogviews][2]: RemoteTransportException[[Shellshock][my_ip:9300][indices:data/read/search[phase/dfs]]]; nested: SearchParseException[failed to parse search source [{"from":0,"size":10,"query":{"match":{"title":{"query":"Top Coat","type":"boolean","operator":"OR","analyzer":"my_analyzer","fuzziness":"1","minimum_should_match":"95%"}}}}]]; nested: QueryParsingException[[match] analyzer [my_analyzer] not found]; }{[tdPbTD9IQhSuvkFMYt1WbA][catalogviews][3]: RemoteTransportException[[Shellshock][my_ip:9300][indices:data/read/search[phase/dfs]]]; nested: SearchParseException[failed to parse search source [{"from":0,"size":10,"query":{"match":{"title":{"query":"Top Coat","type":"boolean","operator":"OR","analyzer":"my_analyzer","fuzziness":"1","minimum_should_match":"95%"}}}}]]; nested: QueryParsingException[[match] analyzer [my_analyzer] not found]; }{[tdPbTD9IQhSuvkFMYt1WbA][catalogviews][4]: RemoteTransportException[[Shellshock][my_ip:9300][indices:data/read/search[phase/dfs]]]; nested: SearchParseException[failed to parse search source [{"from":0,"size":10,"query":{"match":{"title":{"query":"Top Coat","type":"boolean","operator":"OR","analyzer":"my_analyzer","fuzziness":"1","minimum_should_match":"95%"}}}}]]; nested: QueryParsingException[[match] analyzer [my_analyzer] not found]; }] with root cause
[catalogviews] QueryParsingException[[match] analyzer [my_analyzer] not found]
    at org.elasticsearch.index.query.MatchQueryParser.parse(MatchQueryParser.java:101)
    at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
    at org.elasticsearch.index.query.IndexQueryParserService.innerParse(IndexQueryParserService.java:320)
    at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:223)
    at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:218)
    at org.elasticsearch.search.query.QueryParseElement.parse(QueryParseElement.java:33)
    at org.elasticsearch.search.SearchService.parseSource(SearchService.java:856)
    at org.elasticsearch.search.SearchService.createContext(SearchService.java:667)
    at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:633)
    at org.elasticsearch.search.SearchService.executeDfsPhase(SearchService.java:264)
    at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:360)
    at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:357)
    at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
    at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77)
    at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
    at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

A: You have to set in all node.
For example, if you set synonym analyzer with your own dictionary, you have to place synonym.txt in the specific folder in all node.
Edit:
Looks like your mapping is ok, try to add 'type' custom to your analyzer.
"analyzer": {
    "spanish": {
        "type": "custom",
        "tokenizer": "standard",
        "filter": [
            "lowercase",
            "spanish_stop",
            "spanish_stemmer"
        ]
    }
}

A: BTW, The problem was in analyzer mapping itself as mentioned by Ansaldos. I Had to put my_analyzer in analyzer block. i have added correct mapping below.

{ "settings":{ "analysis":{ "filter":{ "spanish_stop":{ "type":"stop",
  "stopwords":"spanish" }, "spanish_stemmer":{ "type":"stemmer",
  "language":"spanish" } }, "analyzer":{ "my_analyzer":{
  "tokenizer":"standard", "filter":[ "lowercase", "spanish_stop",
  "spanish_stemmer" ] } }, "mappings":{ "catalogviewparent":{
  "properties":{ "title":{ "type":"string", "analyzer":"my_analyzer" },
  "fullImageAltDescription":{ "type":"string", "analyzer":"my_analyzer"
  }, "name":{ "type":"string", "analyzer":"my_analyzer" } } } } } } }


text:
Q: How to iterate over a zipped folder? My question is how to iterate over a zipped folder, and access the files in it.
Another question is how do I get file type (something like: ".txt", ".pdf", ".zip" and etc.)
I know how to work with .txt files, but not something like this.
import zipfile

with zipfile.ZipFile("/path/blabla.zip", 'r') as first_zip:
    first_zip.printdir()
    temp = first_zip.infolist()

As for now I have only learned that .printdir() print the names and extension of the file in the zip. And .infolist() returns something like a list (to be honest I do not know what type it returns) with the name and file size.


text:
Q: Mysql optimizing query I have some existing Mysql query and just wondering how to IMPROVE it. Because it's take sometimes up to 20s to execute.
Well in fact it's take up to 0.3690s to find right records but then when need to get 40k record is take up to 20s .
So my question is how can I improve my settings or my sql code to get records faster? Or it's depend now only on my machine (such SAS hard drive) ?
First some necessary info:
my application use MySQL server 5.6 and InnoDB Engine
my custom settings:
innodb_buffer_pool_size = 7G
innodb_log_buffer_size = 64M
innodb_log_file_size = 2G
innodb_flush_log_at_trx_commit = 0
innodb_write_io_threads = 32
join_buffer_size = 32M
tmp_table_size = 128M
max_heap_table_size = 128M
sort_buffer_size = 128M
table_open_cache = 4000
bulk_insert_buffer_size = 256M

Table definitions:
CREATE TABLE `tblusers` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`password` varchar(50) NOT NULL,
`user_name` varchar(45) NOT NULL,
`phone` varchar(12) NOT NULL,
`machine_id` int(11) NOT NULL DEFAULT '1',
`lang_id` int(11) NOT NULL DEFAULT '14',
`user_type` tinyint(4) NOT NULL DEFAULT '1' ,
`created_on` datetime NOT NULL,
`active_open` tinyint(4) NOT NULL DEFAULT '0' ,
`email_hash` varchar(50) NOT NULL DEFAULT '1',
`profile_approved` tinyint(4) NOT NULL DEFAULT '0',
`menage_data` tinyint(4) NOT NULL DEFAULT '0' ,
`mailing_agree` tinyint(4) NOT NULL DEFAULT '0' ,
`edited` tinyint(4) NOT NULL DEFAULT '0',
`deleted` tinyint(4) NOT NULL DEFAULT '0',
`warnings` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `email_UNIQUE` (`email`),
UNIQUE KEY `user_name_UNIQUEE` (`user_name`),
KEY `fk_tblUsers_hlpLangs1_idx` (`lang_id`),
KEY `email_hash` (`email_hash`),
KEY `trio` (`user_type`,`profile_approved`,`deleted`,`email_hash`),
CONSTRAINT `tblusers_ibfk_1` FOREIGN KEY (`lang_id`) REFERENCES `hlplangs` (`lang_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `tblhostess` (
  `user_id` int(11) NOT NULL,
  `first_name` varchar(45) NOT NULL,
  `sure_name` varchar(45) DEFAULT NULL,
  `gender` tinyint(4) NOT NULL DEFAULT '0' ,
  `dob` datetime NOT NULL,
  `driver_license` tinyint(4) NOT NULL DEFAULT '0',
  `sanepid` tinyint(4) NOT NULL DEFAULT '0',
  `city_id` int(11) NOT NULL,
  `province_id` int(11) NOT NULL,
  `picture_id` int(11) NOT NULL DEFAULT '1',
  `hair_id` int(11) NOT NULL DEFAULT '1',
  `hair_color_id` int(11) NOT NULL DEFAULT '1',
  `number_of_view` int(11) NOT NULL DEFAULT '0',
  `who_can_see` tinyint(4) NOT NULL DEFAULT '0' ,
  `complete_register` tinyint(4) NOT NULL DEFAULT '0',
  `skin_id` int(11) NOT NULL DEFAULT '1',
  `bra_id` int(11) NOT NULL DEFAULT '1',
  `wear_id` int(11) NOT NULL DEFAULT '1',
  `shoe_id` int(11) NOT NULL DEFAULT '1',
  `desc` text,
  `height` int(11) NOT NULL DEFAULT '0',
  `weight` int(11) NOT NULL DEFAULT '0',
  `bust` int(11) NOT NULL DEFAULT '0',
  `waist` int(11) NOT NULL DEFAULT '0',
  `hip` int(11) NOT NULL DEFAULT '0',
  `redirect_url` varchar(255) DEFAULT NULL,
  `friend_url` varchar(90) DEFAULT NULL,
  `premium` tinyint(4) NOT NULL DEFAULT '0',
  `premium_until` datetime DEFAULT NULL,
  `work_as_model` tinyint(4) NOT NULL DEFAULT '0',
  `work_as_hostess` tinyint(4) NOT NULL DEFAULT '1',
  `work_as_fotomodel` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_club` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_party` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_promo` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_trade` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_event` tinyint(4) NOT NULL DEFAULT '0',
  `work_in_gala` tinyint(4) NOT NULL DEFAULT '0',
  `phone_ver` tinyint(4) NOT NULL DEFAULT '0',
  `cert` tinyint(4) NOT NULL DEFAULT '0',
  `fb_premium` tinyint(4) NOT NULL DEFAULT '0' ,
  PRIMARY KEY (`user_id`),
  KEY `fk_tblHostess_tblCities1_idx` (`city_id`),
  KEY `fk_tblHostess_hlpProvinces1_idx` (`province_id`),
  KEY `fk_tblHostess_hlpHairColor1_idx` (`hair_color_id`),
  KEY `fk_tblHostess_hlpHair1_idx` (`hair_id`),
  KEY `fk_tblHostess_hlpShoes1_idx` (`shoe_id`),
  KEY `fk_tblHostess_hlpBra1_idx` (`bra_id`),
  KEY `fk_tblHostess_hlpWear1_idx` (`wear_id`),
  KEY `fk_tblHostess_hlpSkinColor1_idx` (`skin_id`),
  KEY `premium` (`premium`),
  KEY `num_of_views` (`number_of_view`),
  KEY `views_premium` (`number_of_view`,`premium`),
  CONSTRAINT `tblhostess_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tblusers` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `tblhostess_ibfk_2` FOREIGN KEY (`city_id`) REFERENCES `hlpcities` (`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `tblhostess_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `hlpprovinces` (`province_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `tblhostessmailings` (
  `hostess_id` int(11) NOT NULL,
  `new_job_offers` int(11) NOT NULL DEFAULT '2' ,
  `comments` int(11) NOT NULL DEFAULT '1' ,
  `job_offer_accept` int(11) NOT NULL DEFAULT '1',
  `private_message` int(11) NOT NULL DEFAULT '1' ,
  `job_offer_sms` int(11) NOT NULL DEFAULT '0' ,
  `job_offer_private` int(11) NOT NULL DEFAULT '0' ,
  PRIMARY KEY (`hostess_id`),
  CONSTRAINT `tblhostessmailings_ibfk_1` FOREIGN KEY (`hostess_id`) REFERENCES `tblhostess` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `tbljoboffers` (
  `offer_id` int(11) NOT NULL AUTO_INCREMENT,
  `employer_id` int(11) NOT NULL,
  `subject` varchar(250) NOT NULL,
  `content` text NOT NULL,
  `content_html` text,
  `date_added` datetime NOT NULL,
  `active` tinyint(3) unsigned NOT NULL DEFAULT '1' ,
  `approved` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `edited` tinyint(3) unsigned NOT NULL DEFAULT '0' ,
  `email` varchar(100) DEFAULT NULL,
  `freqence_id` int(11) NOT NULL DEFAULT '1' ,
  `premium` tinyint(3) unsigned NOT NULL DEFAULT '0' ,
  `start_date` datetime DEFAULT NULL ,
  `end_date` datetime DEFAULT NULL ,
  `premium_old_user` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `sending` tinyint(3) unsigned NOT NULL DEFAULT '0' ,
  `external_sent` tinyint(3) unsigned NOT NULL DEFAULT '0' ,
  `internal_sent` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `archiwal` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `friend_url` varchar(250) DEFAULT NULL,
  `deleted` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `to_export` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `exported` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `sms_sent` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `sms_sending` tinyint(3) unsigned NOT NULL DEFAULT '0' ,
  `private` tinyint(4) NOT NULL DEFAULT '0' ,
  `private_paid` tinyint(4) NOT NULL DEFAULT '0' ,
  PRIMARY KEY (`offer_id`,`freqence_id`),
  KEY `fk_tblJoboffers_tblEmployers1_idx` (`employer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `tbljobofferslocations` (
  `location_id` int(11) NOT NULL AUTO_INCREMENT,
  `offer_id` int(11) NOT NULL,
  `city_id` int(11) NOT NULL,
  `province_id` int(11) NOT NULL,
  `ref_code` varchar(100) DEFAULT NULL,
  `display_times` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`location_id`),
  UNIQUE KEY `offer_id` (`offer_id`,`city_id`,`province_id`),
  KEY `fk_tblJobOffersLocations_hlpProvinces1_idx` (`province_id`),
  KEY `fk_tblJobOffersLocations_tblCities1_idx` (`city_id`),
  KEY `fk_tblJobOffersLocations_tblJobOffers1_idx` (`offer_id`),
  CONSTRAINT `tbljobofferslocations_ibfk_1` FOREIGN KEY (`offer_id`) REFERENCES `tbljoboffers` (`offer_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `tbljobofferslocations_ibfk_2` FOREIGN KEY (`city_id`) REFERENCES `hlpcities` (`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `tbljobofferslocations_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `hlpprovinces` (`province_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

records count approx in db
users 100k
job offers around 20k (all)
and locations around 40k
And finally my sql example:
select email, first_name, sure_name
            from tblusers u join tblhostess h on h.user_id = u.user_id
            join tblhostessmailings m on m.hostess_id = h.user_id
            join
            (select province_id from tbljoboffers o join tbljobofferslocations l on l.offer_id = o.offer_id
            where o.deleted = 0 and o.start_date > date_add(current_timestamp, INTERVAL -1 DAY) and o.approved = 1 and o.active = 1 and o.internal_sent = 1 and o.private = 0
             group by l.province_id) z on z.province_id = h.province_id
            where u.deleted = 0 and u.email_hash = '1' and email != '' and user_type = 1 and (m.new_job_offers = 2)

What I wonna to get from here is a list of all users within 1 day who gets at least one offer on their inside mail box
All jobs are divided into province so this
(select province_id from tbljoboffers o join tbljobofferslocations l on l.offer_id = o.offer_id
            where o.deleted = 0 and o.start_date > date_add(current_timestamp, INTERVAL -1 DAY) and o.approved = 1 and o.active = 1 and o.internal_sent = 1 and o.private = 0
             group by l.province_id)

gets the full list of region and rest get information about users
Sometimes happens i will need retrive 40k records with this query so I really need to improve this.
Thanks in advance.

A: I would look at the subquery you are joining by itself.
select province_id from tbljoboffers o join tbljobofferslocations l on l.offer_id = o.offer_id
        where o.deleted = 0 and o.start_date > date_add(current_timestamp, INTERVAL -1 DAY) and o.approved = 1 and o.active = 1 and o.internal_sent = 1 and o.private = 0
         group by l.province_id

The date comparison in the WHERE clause is likely part of the slow down, how long does that subquery take to run on its own?  A greater than comparison on a date_add function will likely be slow.  But, without changing the query itself you might gain some performance by simply making that subquery into a view and then you can join the view back to the main query.
CREATE VIEW vprovince_ids AS
select province_id from tbljoboffers o join tbljobofferslocations l on l.offer_id = o.offer_id
            where o.deleted = 0 and o.start_date > date_add(current_timestamp, INTERVAL -1 DAY) and o.approved = 1 and o.active = 1 and o.internal_sent = 1 and o.private = 0
             group by l.province_id

Then your main query would become:
select email, first_name, sure_name
            from tblusers u join tblhostess h on h.user_id = u.user_id
            join tblhostessmailings m on m.hostess_id = h.user_id
            join vprovince_ids z on z.province_id = h.province_id
            where u.deleted = 0 and u.email_hash = '1' and email != '' and user_type = 1 and (m.new_job_offers = 2)

Hopefully that helps!

A: I've slightly restructured the query for readability and to follow the explanation of how I would think / apply indexes to the respective tables.
select
      u.email,
      u.first_name,
      u.sure_name
   from
      tblusers u
         join tblhostess h
            on u.user_id = h.user_id
            join tblhostessmailings m
               on h.user_id = m.hostess_id
              and m.new_job_offers = 2
            join (
            select DISTINCT
                  l.province_id
               from
                  tbljoboffers o
                     join tbljobofferslocations l
                        on o.offer_id = l.offer_id
               where
                      o.deleted = 0
                  and o.approved = 1
                  and o.active = 1
                  and o.internal_sent = 1
                  and o.private = 0
                  and o.start_date > date_add( current_timestamp, INTERVAL -1 DAY)
                 ) z
                  on h.province_id = z.province_id
   where
          u.deleted = 0
      and u.email_hash = '1'
      and u.user_type = 1
      and u.email != ''

First, your queries would be best to have all columns represent the proper table (or alias) they are coming from so others in the future, or offering help don't have to guess where columns are coming from which tables (yet you did provide the table structures).
To better handle your queries, having your table with a bunch of individual indexes is not the best way to support your queries.  Instead, you need to have indexes that match the type of criteria you are searching on.  In  the case of the inner query of job offers, you are explicitly looking for 6 criteria, AND applying a group by.  Having an index on the criteria components will significantly improve.  Also, due to the other criteria, I have moved the date basis to the end, both visually, and as part of the index.  Since you are not doing any aggregates by province, I removed the group by, and just did DISTINCT.
table          create index on...
tblJobOffers   ( deleted, approved, active, internal_sent, private, start_date )

Think of the indexes like this.  If you had individual indexes on things like deleted or approved or active...  Only one of them would be used as basis to help optimize the query.  But since multiple fields are used in your query, it would be faster to use those indexes that matched multiple criteria you are running with.
Try to think of it like this... Each index is a box with the content ordered first by the first field, then sub-sorted by the field under it and so forth.
If you index on just "deleted", you have two boxes... one with all deleted stuff, one with NOT deleted.  Similar if only an "active" index.  But by having a composite index as I have, the engine can jump quickly to the records in question...  Seeing your column names, they appear to be "flags" of either on = 1, or off = 0
Deleted = 0
   Approved = 0
      (ignored, you don't want approved = 0)
   Approved = 1
      Active = 0
         (ignored, you don't want active = 0)
      Active = 1
         Internal_Sent = 0
            (ignored, you don't want internal sent = 0)
         Internal_Sent = 1
            Private = 0
               Start_Date
                   2014 Dec...
                   2015 Jan...
                   2015 Feb...
                   2015 Feb 4
                   2015 Feb 5
                   2015 Feb 6
            Private = 1
               (ignored, you don't want private = 1)

Deleted = 1
   (ignored since you are not even looking for deleted = 1 records)

So, following the tree down, the index can jump directly to the 2015 Feb transactions,  get those and ignore everything else.  Use that to join to the province locations and it's done.
For your OUTER query, your join TO the "tblhostessmailings" is based on the hostess ID, but also you are only looking for specific flag of new job offers = 2.  Have that as a compound index too.  Hostess table is joined by the user ID, so that should have an index.  And tblUsers has multiple criteria too, so that (in similar context as job offers above) should have a compound index
table                index
tblhostessmailings   ( hostess_id, new_job_offers )
tblhostess           ( user_id )
tblusers             ( deleted, user_type, email_hash, email )

See what these sugggestions and revised query do for your performance, and let us know the performance improvement as a result, good or bad.

A: *

*Indexed columns on performing the search, not on selecting

*Use unique indexes

*Use short indices

*Do not abuse indexes


text:
Q: Python plotly go.bar textposition is not working I want to display text value on the group bar plot and the gross profit and net profit on line plot from the code below but it doesn't work.
I have added textposition to go.bar but it isn't working. I don't understand why it is not working.

create_visual is a function create visualization of the all stock profit loss in filter-HK-CODE2.csv and it creates the html file and the png file.
from utils import *
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots

# y folder

df_stock = pd.read_csv('filter-HK-CODE2.csv')

def create_visual(filename):

    createDir_if_not_exist('out/y/img')
    createDir_if_not_exist('out/y/interactive')

    print('read file: ' ,filename)

    df = pd.read_csv('data/y/'+ filename)

    df.replace('-', '0', inplace=True)
    df['Total Turnover'] = pd.to_numeric(df['Total Turnover'])
    df['Net Profit'] = pd.to_numeric(df['Net Profit'])
    try:
        df['Gross Profit'] = pd.to_numeric(df['Gross Profit'])
    except:
        print('No GP')
    stockcode = filename[0:5]

    #print('stockcode: ', stockcode)

    #print(df['Total Turnover'])
    #print(df['Net Profit'])

    fig = make_subplots(specs=[[{"secondary_y": True}]])

    fig.add_trace(go.Bar(name='Revenue', x=df['Closing Date'], y=df['Total Turnover'],base = 0,textposition="inside",),secondary_y=False)
    fig.add_trace(go.Bar(name='Net Profit', x=df['Closing Date'], y=df['Net Profit'],base = 0,textposition="inside",),secondary_y=False)

    try:
        fig.add_trace(go.Scatter(x=df['Closing Date'], y=df['Gross Profit']*100/df['Total Turnover'], name="GPM%",textposition="bottom center"),secondary_y=True)
    except:
        print('No GP')

    fig.add_trace(go.Scatter(x=df['Closing Date'], y=df['Net Profit']*100/df['Total Turnover'], name="NPM%",textposition="bottom center"),secondary_y=True)

    fig.update_layout(barmode='group',template="seaborn",
        title_text=str(df_stock[df_stock['StockCode'] == int(stockcode)]['Name of Securities'].values[0]) + '    ' + stockcode +'.HK',
        xaxis_title="date",
        title_font_color="red",
        yaxis_title=df['Unit'].values[0] +'    '+ df['Currency'].values[0],
        font=dict(
            size=18,
        ))
    #fig.show()
    pio.write_image(fig,'out/y/img/'+str(stockcode)+'.png', width=1480, height=780,format ='png')
    fig.write_html('out/y/interactive/'+str(stockcode)+'.html')

if __name__ == '__main__':

    count = 0
    '''
    for file in os.listdir('data/y'):
        print('file No : ',count)
        create_visual(file)
        count += 1
    '''
    create_visual('00001PL-Y.csv')


text:
Q: C++ including python.h and boost/python.hpp causes SEH exception I've recently stumbled across something while trying to fix the python implementation in the c++ software I'm working on. If you have the following included:
#include <python.h>
#include <boost/python.hpp>

then the following code causes an SEH Exception with a memory access violation:
boost::python::object mainModule;

Py_Initialize();

std::lock_guard<std::mutex> lg(PythonAccessMutex);
this->mainModule = boost::python::import("__main__");

boost::python::dict globalDict = boost::python::extract<boost::python::dict>(this->mainModule.attr("__dict__"));

Removing the python.h include resolved my issue but I've been unable to find out why this was causing the exception and I'd like to be able to share with my coworkers why they shouldn't do this (past the obvious reason of it breaks the code)
I should be specific and point out that the code runs fine until it hits the extract function.

A: There are macro conflicts if Python.h is included before a Boost.Python header.  For instance, Python.h includes LongObject.h defining ULONGLONG_MAX that confuses Boost's config.  The inclusion issue is noted in detail/prefix.hpp:

The rule is that <Python.h> must be included before any system headers (so it can get control over some awful macros). Unfortunately, Boost.Python needs to #include <limits.h> first, at least... but this gets us as close as possible.

After some setup work, detail/wrap_python.hpp includes Python.h.


text:
Q: Regarding finding out time spent on each application in Android KK Kindly help to figure out a way so that I can find time spent on each application package in Android KK device .
In Android 5.0+ version we have Usage Stats api to get the stats related to app packages in the system.
reference to Android 5.0 : Using usageStats.getTotalTimeInForeground() to get the time every application in a device spent in foreground
How to get relevant data for package in Android KitKat.
Thanks in advance .


text:
Q: How to import a large wikipedia sql file into a mysql database? I need a database table with "topics" so I downloaded wikipedia's sql file of categories (enwiki-latest-category.sql.gz on http://dumps.wikimedia.org/enwiki/latest/)
The file is 74MB (unzipped) but the mysql limit is 32MB. How can I import this file?
By the way: I tried bigdump (http://www.ozerov.de/bigdump/) but it also seems to have an import limit of 32MB.

A: You could split it in pieces of 32MB and import them individually. It shouldn't be too time consuming.

A: If you have mysql installed on your Windows desktop, I have something crazy you may want to try.
Please perform the following steps on your local mysql box

*

*STEP 01) Unzip the file enwiki-latest-category.sql.gz to enwiki-latest-category.sql

*STEP 02) CREATE DATABASE mycat;

*STEP 03) `mysql -u... -p... -Dmycat < enwiki-latest-category.sql

*STEP 04) Export the CREATE TABLE for category
mysqldump -u... -p... --no-data mycat category > category_00.sql

*STEP 05) Dump the data divided into 10 sections. Since the AUTO_INCREMENT is 134526529, round it to 135000000 (135 million). Dump 20% (27 million) at a time
Just run 5 mysqldumps using the --where option against cat_id
mysqldump -u... -p... --no-create-info mycat category --where="cat_id <=  27000000"                         | gzip > category_01.sql.gz
mysqldump -u... -p... --no-create-info mycat category --where="cat_id  >  27000000 AND cat_id <=  54000000" | gzip > category_02.sql.gz
mysqldump -u... -p... --no-create-info mycat category --where="cat_id  >  54000000 AND cat_id <=  81000000" | gzip > category_03.sql.gz
mysqldump -u... -p... --no-create-info mycat category --where="cat_id  >  81000000 AND cat_id <= 108000000" | gzip > category_04.sql.gz
mysqldump -u... -p... --no-create-info mycat category --where="cat_id  > 108000000"                         | gzip > category_05.sql.gz

Upload these 6 files, unzip them,  and load them in order.
Give it a Try !!!


text:
Q: Find And Replace Current Text to Wrap In Color So I'm trying to make an alias for cal that will run it through sed to wrap the current day in the terminal escapes for red.
cal | sed "s/($(date +%d))/\\033\[94m$(date +%d)\\033\[0m/g"

However, I apparently can't use inline command execution like $(date +%d) inside of a capture group.
In addition, if I use the command substitution in both place, I can get the replacement to work, but not the backslashes to escape the color code.
$ cal | sed "s/$(date +%d)/\\033\[94m$(date +%d)\\033\[0m/g"
      May 2016
Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7
 8  9 10 033[94m11033[0m 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Is there a way to wrap a replacement in colors? In addition, is there a better regex to handle single digit days? (Since on the first through ninth days of the month, it will highlight every instance of that number on the calendar.)
EDIT: I'm running OS X, Darwin Kernel Version 15.2.0, since apparently the cal implementation on OS X doesn't support the -h option.

A: Try:
cal -h | sed "s/$(date +%d)/"$'\033\[94m&\033\[0m/g'

Notes:

*

*By default, cal highlights the current day.  I used the -h option to turn that off so it doesn't interfere with your preferred color. [Update: apparently this applies to GNU cal only]

*You are right that $(date +%d) has to appear in double-quotes.  The rest of the command, however, does not.  Above, I used bash's $'...' for the rest of the command because it supports escape sequences.

*There is no need for a second $(date +%d).  We can recall the matched text with &.

*If you have GNU sed, a convenient way to fix the single-digit day issue is to require the matched text to be a whole word using \<...\>:
cal -h | sed "s/\<$(date +%d)\>/"$'\033\[94m&\033\[0m/g'  # GNU

If your sed does not have that feature, you will need to s commands:
cal -h | sed "s/ $(date +%d) /"$'\033\[94m&\033\[0m/g; '"s/ $(date +%d)$/"$'\033\[94m&\033\[0m/g'

The first substitute command looks for the date surrounded by spaces.  This works for all single digit dates except the ones at the end of a line.  The second looks for dates preceded by a space and followed by the end of the line ($).