text:
Q: How to show $\lim_{n\rightarrow \infty}\sum_{k=1}^n(\sqrt{1+\frac{k}{n^2}}-1) = \frac{1}{4}$? It is a exercises.
$$
\lim_{n\rightarrow \infty}\sum_{k=1}^n(\sqrt{1+\frac{k}{n^2}}-1) = \frac{1}{4}
$$
I know
$$
\lim_{n\rightarrow \infty}\sum_{k=1}^n(\sqrt{1+\frac{k}{n^2}}-1) \le \frac{1}{4}
$$
by integral estimates. But I can't get the equal .

A: Notice that Squeeze theorem says,
$$\color{red}{\boxed{\left( f\leqslant g\leqslant h \right) \wedge \left( \lim_{a} f=\lim_{a} h=\ell \right) \implies \lim_{a} g=\ell}}.$$
Letting $\displaystyle g(n):= \sum_{j=1}^{n}\left(\sqrt{1+\frac{j}{n^{2}}}-1 \right)$. We will show that $\displaystyle \lim_{n\to +\infty} g(n)=\frac{1}{4}$ showing that for some suites $f(n)$ and $g(n)$ we have

*

*$\displaystyle f(n)\leqslant g(n)\leqslant h(n)$.

*$\displaystyle \lim_{n\to +\infty} f(n)=\frac{1}{4}.$

*$\displaystyle \lim_{n\to +\infty} h(n)=\frac{1}{4}.$
Taylor series of mapping $x\mapsto \sqrt{1+x}$ around of $x=0$ give
$$\sqrt{1+x}=1+\frac{x}{2}-\frac{x^{2}}{8}+\mathcal{O}(x^{3}).$$
Hence
$$\color{red}{\boxed{1+\frac{x}{2}-\frac{x^{2}}{8}\leqslant \sqrt{1+x}\leqslant 1+\frac{x}{2}, \quad 0<x<1}}, \quad (*)$$
Setting $x:=j/n^{2}$, we have in $(*)$,
$$1+\frac{(j/n^{2})}{2}-\frac{(j/n^{2})^{2}}{8}\leqslant \sqrt{1+\frac{j}{n^{2}}}\leqslant 1+\frac{(j/n^{2})}{2}$$
$$1+\frac{j}{2n^{2}}-\frac{j^{2}}{8n^{4}}\leqslant \sqrt{1+\frac{j}{n^{2}}}\leqslant 1+\frac{j}{2n^{2}}$$
$$1+\frac{j}{2n^{2}}-\frac{j^{2}}{8n^{4}}\color{red}{-1}\leqslant \sqrt{1+\frac{j}{n^{2}}}\color{red}{-1}\leqslant 1+\frac{j}{2n^{2}}\color{red}{-1}$$
$$\frac{j}{2n^{2}}-\frac{j^{2}}{8n^{4}}\leqslant \sqrt{1+\frac{j}{n^{2}}}-1\leqslant \frac{j}{2n^{2}}$$
Hence
$$\sum_{j=1}^{n}\left(\frac{j}{2n^{2}}-\frac{j^{2}}{8n^{4}}\right)\leqslant \sum_{j=1}^{n}\left(\sqrt{1+\frac{j}{n^{2}}}-1\right)\leqslant \sum_{j=1}^{n}\left(\frac{j}{2n^{2}}\right)$$
$$\frac{(n+1)(12n^{2}-2n-1)}{48n^{3}}\leqslant \sum_{j=1}^{n}\left(\sqrt{1+\frac{j}{n^{2}}}-1\right)\leqslant \frac{n+1}{4n}$$
Hence,

*

*$\displaystyle f(n)=\frac{(n+1)(12n^{2}-2n-1)}{48n^{3}}$ so $\displaystyle \lim_{n\to +\infty} f(n)=\frac{1}{4}$.

*$\displaystyle h(n)=\frac{n+1}{4n}$ so $\displaystyle \lim_{n\to +\infty} h(n)=\frac{1}{4}$.

*$f(n)\leqslant g(n)\leqslant h(n)$.

Therefore by Squeeze theorem we get,
$$\color{blue}{\boxed{\lim_{n\to +\infty} \sum_{j=1}^{n}\sqrt{1+\frac{j}{n^{2}}}-1=\frac{1}{4}}}$$
N.B: More generally, if $f\in \mathcal{C}^{2}(]-a,a[,\mathbb{R})$ with $a\in [1,+\infty[$ and $f(0)=0$ we get $$\color{blue}{\boxed{\lim_{n\to +\infty} \sum_{j=1}^{n}f\left(\frac{j}{n^{2}}\right)=\frac{1}{2}f'(0)}}.$$


text:
Q: Equivalent model of a real inductor -2 Is this possible to explain what is happenning on this inductor?

I observed this phenomenon on an inductor. I simulate the phenomenon by adding a parallel resistor to the inductor, but I do not really understand what is happening into the inductor. It is like if it was saturating during the transient voltage applied to the inductance? Can someone tell me what is really happening physically?

A: Saturation is a nonlinear phenomenon; it will not be modeled so simply.
The jagged triangle wave, consider the current through the two parallel paths of inductor and resistor.
The resistive current flows through effective parallel resistance around the inductor.  A typical case is a core made of resistive metal e.g. laminated iron, which acts in parallel by transformer action.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL complex primary key I would like to create a primary key that is complex from two different columns and also IDENTITY. For example:
My table:
create table Location (
     locationID int primary key,
     lat int not null,
     lng int not null,
)

lat = 43
lng = 567

I would like the primary key value will be like the following:
locationID = 43.567-1

The "-1" will be add if there is already a locationID that starts with "43.567".
Is it possible at all?

A: Not tested by myself, but it could be possible using triggers
http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
However you may have problems if you try to issue the query without a value for the primary key

A: You can also just use compound keys, here you can do so by using lat and lng. The beauty of compound keys is that only one of the values of the constituting columns has to be unique.

A: You can make a compound primary key but it would still have to be unique. There is no point to what you are trying to do. You are trying to force non unique values to be unique by adding arbitrary values to duplicates in order to make then unique.
The correct way to approach this would be to have either no repeated lat/lng combinations possible or to simply use your LocationID as the primary key.


text:
Q: oracle apex page stops execution after calling report query I have an oracle apex page that saves the data to a table while page processing ,when a button is clicked. After this I call a report query and generates a pdf report.After the pdf report is generated, the page stops execution without completing the page submit action. Hence the page items do not get refreshed and the page do not reloads. The control goes to the newly generated pdf report. Anybody have a solution for this?
Edit
A button 'SAVE' is created for calling the report query 'SLIP'. Then inside the page a dynamic action is created . javascript code is written inside DA. This javascript will submit the button using the code
apex.submit('SAVE')

A pl/sql page process  is also created for this save button. This will work after above JavaScript code is executed at point 'processing'. After this, report query 'SLIP' is called and pdf report is generated and it is opened in adobe reader. Then the page stops executoin, page do not gets submitted . The page item values will not be cleared and the page do not reloads. That is the issue I'm facing

A: Use JavaScript Code:
apex.submit('BUTTONNAME');


text:
Q: PySpark Identify Duplicates based on Partial Matches from a Column I am looking for a solution to identify an approach to rank the duplicates based on partial match from a Pyspark Dataframe column and tag the first match id to newly generated column.
Input Dataframe:

id
name
class

1
Roger Fernandes
12

2
Kevin Kingsely
11

3
Fernandes Roger
13

4
Jack Sparrow
14

5
Roger thinker
16

6
Ro seman
17

Output Dataframe:

id
name
class
duplicate
id

1
Roger Ferna
12
yes
1

2
Kevin Kingsely
11
no
None

3
Ferna Roger
13
yes
1

4
Jack Sparrow
14
no
None

5
Roger think
16
yes
1

6
Ro seman
17
no
None

Note: We can consider the weightage of partial match as >50%.
Tried:
partition_dataframe = Window.partitionBy(["name"]).orderBy(order_by_column)
data_frame = data_frame.withColumn("Duplicated_Rank", rank().over(partition_dataframe))

Output Dataframe:

id
name
class
duplicate
id

1
Roger Ferna
12
yes
1

2
Kevin Kingsely
11
no
None

3
Ferna Roger
13
yes
1

4
Jack Sparrow
14
no
None

5
Roger think
16
yes
1

6
Ro seman
17
no
None


text:
Q: DiscordJS | How do I create a "responses" page? I am VERY new to DiscordJS (and JS in general).
How exactly do I call a new .js page, and execute from it?
For example, here is code which will eventually have a HUGE list of potential responses. I'd like to put these responses (or the whole module?) on a separate page, for organization sake. How would I do this?
Currently, this is all just in my index:
client.on("messageCreate", async (message) => {
  let args = message.content.trim().split(" ");
  if (message.author.id === "1234567890") {
    const member = await message.guild.members.fetch(message.author.id);
    const responses = [
      "Response 1",
      "Response 2",
      "Response 3",
      "Response 4",
    ];
    const reply = responses[Math.floor(Math.random() * responses.length)];
    if (Math.random() < 0.15) {
      //.50 = 50% chance

      message.reply(`${reply}`);
    }
  }
});

Thank you for any help/pointers!

A: Create your file and export your array from it. Then require that array in your main file.
File responses.js
const responses = [
   "Response 1",
   "Response 2",
   "Response 3",
   "Response 4",
];

export default responses;

Main file
import responses from "path to responses.js"

If you're not using ESM, use module.exports and require:
module.exports = {
   responses
};

//...

const { responses } = require("path to responses.js");


text:
Q: warning C4316: object allocated on the heap may not be aligned 16 Important Information:

*

*Development OS: Windows 8.1 64 bit

*Target OS: Windows 8.1 64 bit

*IDE: Visual Studio 2013 Professional

*Language: C++

The Problem:
I get the following warning when compiling my static library project through the IDE:
warning C4316: ... : object allocated on the heap may not be aligned 16

I could simply ignore this warning...but I'm assuming it's there for a reason and would like to at least understand what it means and what implications it could have in the future.
I believe this line of code is related to the problem, which is called inside my Win32 window wrapper class:
m_direct3D = new Direct3D(this);

m_direct3D is a pointer to my Direct3D wrapper class.
Here is the header file for the wrapper (I admit it needs trimming down):
#pragma once

// Windows
#include <d3d11.h>
#include <DirectXMath.h>

// Standard
#include <stdint.h>
#include <vector>

// JGlib
#include "Window.h"

namespace JGlib
{
    namespace Graphics
    {
        class Direct3D
        {
        public:
            // Construtor and destructor
            Direct3D(const JGlib::Graphics::Window* window);
            ~Direct3D();

            // Public methods
            void Initialise();
            void BeginDraw();
            void Draw();
            void EndDraw();

        private:
            // Private methods

            // Private member variables
            const Window*               m_window;
            ID3D11Device*               m_device;
            IDXGIAdapter*               m_adapter;
            DXGI_ADAPTER_DESC           m_adapterDescription;
            uint32_t                    m_videoCardMemory;
            IDXGIFactory*               m_factory;
            IDXGIOutput*                m_monitor;
            DXGI_MODE_DESC*             m_displayModes;
            uint32_t                    m_numberOfModes;
            DXGI_RATIONAL               m_refreshRate;
            DXGI_SWAP_CHAIN_DESC        m_swapChainDescription;
            D3D_FEATURE_LEVEL           m_featureLevel;
            ID3D11DeviceContext*        m_deviceContext;
            IDXGISwapChain*             m_swapChain;
            ID3D11Texture2D*            m_backBuffer;
            ID3D11RenderTargetView*     m_renderTargetView;
            ID3D11Texture2D*            m_depthStencilBuffer;
            D3D11_TEXTURE2D_DESC        m_depthBufferDescription;
            D3D11_DEPTH_STENCIL_DESC    m_depthStencilDescription;
            ID3D11DepthStencilState*    m_depthStencilState;
            ID3D11DepthStencilView*     m_depthStencilView;
            D3D11_RASTERIZER_DESC       m_rasterDescription;
            D3D11_VIEWPORT              m_viewport;
            float                       m_fieldOfView;
            float                       m_screenAspectRatio;
            ID3D11RasterizerState*      m_rasterState;
            DirectX::XMMATRIX           m_projectionMatrix;
            DirectX::XMMATRIX           m_worldMatrix;
            DirectX::XMMATRIX           m_orthographicMatrix;
            float                       m_screenDepth;
            float                       m_screenNear;
        };
    }
}

I tried googling the issue, but found little information. The information I did find I did not understand.
The conclude, I am asking the following:

*

*What does C4316 mean?

*What is causing it in my code?

*What implications could this have in the future, if I ignore it?

*How do I "fix" the problem that is causing this warning to appear?

Additional Information:
When I changed Visual Studio's configuration manager to compile for x64, this issue does not occur.

A: If you look at the pre-processed code you'll probably find something like this __declspec(align(16)) in there, requesting to be aligned at 16 bytes while new may not align at that constraint. Accoding to http://msdn.microsoft.com/en-us/library/vstudio/dn448573.aspx you can fix it by Override operator new and operator delete for over-aligned types so that they use the aligned allocation routines—for example, _aligned_malloc and _aligned_free.

A: DirectX::XMMATRIX contains SSE data (and is marked with __declspec(align(16)) because of this), and therefore needs to be aligned on 16B boundary, otherwise instructions accessing it will cause access violation.
The warning tells you there is no guarantee memory returned by operator new is 16B aligned.
Can you create the object as a global or local variable instead? That way the compiler can enforce the alignment. If you cannot, you can provide overloaded new and delete for your Direct3D class implemented using _aligned_malloc and _aligned_free.

A:
What does C4316 mean?

C4316 is the error code.  It's a unique identifier that makes it easy to find the documentation.

What is causing it in my code?

The usage of the DirectX::XMMATRIX class.  Instances of that class must be aligned on 16-byte boundaries.  The compiler makes sure that whenever you create a JGLib::Graphics::Direct3D instance on the stack or at global scope, it will align it properly, but if you allocate an instance dynamically on the heap, the compiler can't guarantee that the object will be aligned properly, because malloc() and friends typically only guarantee 8-byte alignment.

What implications could this have in the future, if I ignore it?

Your code may crash when accessing those matrix instances due to SSE instructions operating on misaligned data.

How do I "fix" the problem that is causing this warning to appear?

As the documentation suggests, you need to override your class's operator new and operator delete in order to guarantee 16-byte alignment.  You can use _aligned_malloc() and _aligned_free() to allocate and free memory aligned on larger alignments.

A: You need to override the new and delete operators, like this:
__declspec(align(16)) class MyClass
{
    public:
    DirectX::XMMATRIX           m_projectionMatrix;

    virtual ~MyClass()
    {
    }

    void* operator new(size_t i)
    {
        return _mm_malloc(i,16);
    }

    void operator delete(void* p)
    {
        _mm_free(p);
    }
};


text:
Q: Parsing multiple arrays in PHP I have a CSV file that I am parsing using PHP. However, the output looks as follows:
Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

And so on...
How can I parse each of these individually and/or display only one at random? I've tried using array_values, but that seems to output all arrays, not just one.   Any suggestions? Feel free to let me know if there is anything else I can provide. Thanks guys.
Edit: Added some code if it helps - pretty basic.
//CSV to array and parse
function parseCSV() {
    $file = fopen('feeds/data.csv', 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
        //$line is an array of the csv elements
        $arr = $line;

        $url = array_values($arr)[2];
        $author = array_values($arr)[1];

        print_r($arr);
    }

    fclose($file);
}//end

A: <?php

Class CsvRandomLine
{
    private $line_count=0;
    private $random_element;
    private $handle;
    private $csv_arr;

    function __construct($file='feeds/data.csv')
    {
        $this->handle = fopen($file, "r");

         $this->sort_one_element();
    }

    //CSV to array and parse
    function randomLine()
    {
        $i = 0;

        // move pointer to the sorted line
        while($i < $this->random_element)
        {
          $line = fgets($this->handle);
          $i++;
        }

        $line = fgetcsv($this->handle);

        //add element to $csv_arr with $url and  $author
        $this->csv_arr=array(
                            "url"    =>  $line[2],
                            "author" =>  $line[1]
                        );

    }//end

    function get($property)
    {
        return $this->csv_arr[$property];
    }

    function sort_one_element()
    {
        if($this->line_count!=0)
        {
            $max = $this->line_count;
        }
        else
        {

            $max = $this->countLines();
        }

        $max--;

        $n = rand( 0 , $max );

        //echo $n;

        $this->random_element = $n;

        rewind($this->handle);

        $this->randomLine();

    }

    function countLines()
    {
        $linecount=0;
        while( fgets($this->handle) !== FALSE )
        {
          $linecount++;
        }

        $this->line_count=$linecount;

        return $linecount;
    }

    function __destruct()
    {
        fclose($this->handle);
    }

}

// How to use the class:

$csv_r = new CsvRandomLine();
//Construct automatic sort the first element

echo $csv_r->get("author");
echo '
';
echo $csv_r->get("url");

echo '
';

//Sorting another element
$csv_r->sort_one_element();

echo $csv_r->get("author");
echo '
';
echo $csv_r->get("url");

A: Well I would load the array with all the records on the csv file (the first $line read is always the header of the csv document, and I would use it to create the result assoc_array keys), then if you want to display one (the first of the result array) or a random (just use array_rand()).
Just a dirty example
$result = [];
$keys = null;
while(($line = fgetcsv($f)) !== false){
    if($keys === null){
        $keys = $line;
        continue;
    }
    $row = [];
    foreach($keys as $position => $key){
        $row[$key] = $line[$position];
    }
    $result[] = $row;
}

// here you will have $result with all the records and you can get the first or do whaterver you want to show just one

In case you need just the bare data and no an assoc_array you could do
$result = [];
$keys = null;
while(($line = fgetcsv($f)) !== false){
    if($keys === null){
        $keys = $line;
        continue;
    }
    $result[] = $line;
}

// here you will have $result (raw data) and $keys (the header of the csv)


text: Q: $x^n \equiv m \bmod k$ is there a generic formula for int $n$, $m$, $k$? For example $x^2 \equiv 0 \bmod 4$ or $x^2 \equiv 1 \bmod 4$ and there are no other solutions for $(2,m,4)$. Edit: I am not about try to solve for $x$, I am looking for the possible $(n, m, k)$ triplets.


text:
Q: PowerApps connectors in Logic Apps I'm trying to use Power Apps for Makers and Power Apps for Admins connectors in a Azure Logic App, is there any way to use them on a Logic App like we can use them on Power Automate?

A: I'm afraid there is no way to use them in logic app, we can see the document of Power Apps for Makers and Power Apps for Admins show us they don't support logic app service.

If the connector support logic app, its document should show like:

You can also create a ticket on Azure Feedback page(for logic app) to suggest develop team to add this feature.


text:
Q: Why do transform iterators not implement operator->? While transform iterator implementations such as boost::transform_iterator are certainly useful, all implementations I've found seem to share one common weakness: they only provide operator*, and no operator->.
Given a transform function returning a reference, implementing operator-> is straightforward.
Given a transform function returning by value, implementing operator-> using a proxy should also not be a problem.
Why is it deemed preferable to provide only an operator*, and no operator->? Is the use of a proxy here any different from e.g. std::vector<bool>?
Update: Here's a very simple proof of concept to demonstrate how such a proxy object could work (hard-coded for std::string type):
#include <iostream>
#include <functional>
#include <string>

class StringProxyDemo {
public:
    class Proxy {
    public:
        Proxy(std::string value) : _value(std::move(value)) { }
        std::string *operator->() { return &_value; }
    private:
        std::string _value;
    };

    Proxy operator->() { return _function(); }

    StringProxyDemo(std::function<std::string()> function)
    : _function(std::move(function)) { }

private:
    std::function<std::string()> _function;
};

int main() {
    StringProxyDemo demo(
        []() -> std::string {
            return "Hello, World!";
        }
    );
    std::cout << demo->size() << std::endl;
    std::cout << demo->c_str() << std::endl;
}

Run on Ideone


text:
Q: Associate variable to a list I'm not sure if this is easy possible in C#. But I would like to get to know how this could be done easily.
public partial class Form1
{
  // I left out the unimportant code for this example
  private myControl cLeft,cTop,cBottom,cRight;
  private List<myControl>mControls;
  public Form1()
  {
  InitializeComponents();
  //this list should contain the fields cLeft,cTop,cBottom,cRight...
  mControls=new List<myControl>(){cLeft,cTop,cBottom,cRight};
  /* now I want that cLeft and so on get assigned...
  of course, this doesn't work because the list refers to the values of
   cLeft ... which are null. So I would need to store a reference to those fields to get this work.*/
  mControls.ForEach(x=>x=new myControl(this));
  }

}

I'm sure it could be done through reflection, but I assume that there should be a way to do this easily in C# or isn't it possible?

A: It's just a simple loop, there is no need to use LINQ. You just need a for loop.
for (int i = 0 ; i < mControls.Count ; i++) {
    mControl[i] = new myControl(this);
}

But, there is no need to write cLeft, cTop etc. You can just refer to them using the indexer: mControls[0], mControl[1] etc.
And remember, the foreach loop or the ForEach extension method doesn't work. This is because you are changing the reference of the variable. That is just another confusing (for beginners) feature of reference types!
Consider this method
public void ChangeReference (string s) {
    s = "Hello";
}

And you call this method:
String s = "xxx";
ChangeReference (s);

Will s be "Hello" after the call? No. In the method, you are changing the location of the string in memory, but the argument is still in the same place!


text:
Q: bash: Delete all files older than 1 month, but leave files from Mondays I have a lot of daily backup archives. To manage disk usage, I need a bash script that will delete all files older than 1 month, but keep all files created on Mondays, even if they are older than 1 month.
For example, this will delete all files last modified more than 30 days ago:
 find /path/to/files* -type f -mtime +30 -delete

But I don't really know how to keep files created on Mondays.

A: As find to my knowledge has no weekday check, you need to call an external program.
find /path/to/files -type f -mtime +30 \
    -exec sh -c \
        '[ "$(date +%u -d @"$(stat -c %Y "$1")")" != 1 ] && rm "$1"' -- {} \;

Update: Using the -r switch to date (Kudos to Janos) and only testing, not deleting inside the shell command probably yields the cleanest possible version:
find /path/to/files -type f -mtime +30 \
    -exec sh -c 'test "$(date +%u -r "$1")" != 1' -- {} \; \
    -print  # or -delete instead

A: Slightly simpler and more cautious version of @JoSo's answer:
find /path/to/files -type f -mtime +30 \
    -exec sh -c 'test $(date +%a -r "$1") = Mon || echo rm "$1"' -- {} \;

The differences:

*

*Using date -r to get the last modification date of a file directly

*Using %a to work with more comprehensible weekday names

*Just echo the rm "$1" first to review what will be deleted. If looks good, then either stick | sh at the end to really execute, or remove the echo
However, @JoSo is right to point out that date +%a is locale dependent, so these versions would be indeed safer:
find /path/to/files -type f -mtime +30 \
    -exec sh -c 'test $(date +%u -r "$1") = 1 || echo rm "$1"' -- {} \;
find /path/to/files -type f -mtime +30 \
    -exec sh -c 'test $(LC_TIME=C date +%a -r "$1") = Mon || echo rm "$1"' -- {} \;

A: you can use
stat -c %y yourfile

to get the date the file was created.
Then extract the date with cut to have a var like myvar=yyyymmdd
and finally use
date +%u --d $myvar
date +%u --d 20130822

it will return the day of week, if it returns 1 it was monday.
In my case it return 4 because 22/08/2013 was a Thursday
Edit : if you can get all these working as a simple command line as Jo So suggest, it's better !

A: What about avoiding subprocesses in loop:
find /path/to/files -type f -mtime +30 -printf '%Ta %p\n' \
    | grep -v ^Mon | cut -c5- | tr "\n" "\0" | xargs -0 rm -v


text:
Q: Can I create group & private chat app in socket.io I want to create a chat application which will includes the following functionalities.
1) Group Chat.
2) Private Chat.
3) Images can be share and show in realtime in Group and Private chat
4) Give Option of Who is typing.
I want to create above application in react.js, node.js & socket.io.
Can I?


text:
Q: POSTGRESQL HOW TO DISTINCT Fullwidth I have data in my dataset like below,in varchar data type.
123456789X
123456789x
123456789x
123456789X

Please advise how to use distinct lower to distinct above 4 to 1? Thanks.
I found how to solve this problem by:
SELECT DISTINCT(TRANSLATE(LOWER(telephone),
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

A: This is the solution:
SELECT DISTINCT(TRANSLATE(LOWER(telephone),
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

A: I'd remove the spaces (using replace) and then apply distinct:
SELECT DISTINCT REPLACE(data, ' ', '')
FROM   mytable


text:
Q: How to use the ASM AdviceAdapter with the Tree API? I was wondering whether it is possible to use an AdviceAdapter with the ASM Tree API.
I tried the following, however the heap space runs out of memory.
@Override
public void modify(ClassReader cr, ClassWriter cw) throws Exception
{
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);

    instrumentTestcases(cn);
    cn.accept(cw);
}

@SuppressWarnings("unchecked")
private void instrumentTestcases(ClassNode cn)
{
    for (MethodNode methodNode : (List<MethodNode>) cn.methods)
    {
        if (isTestMethod(methodNode))
        {
            TestModeAdapter adapter = new TestModeAdapter(methodNode, methodNode.access, methodNode.name, methodNode.desc);
            methodNode.accept(adapter);
        }
    }
}

The class TestModeAdapter inherits AdviceAdapter and adds a simple instruction at the beginning and the end of the method. The modification is successful if I use the adapter in the ClassVisitor's visitMethod method.
Is my code incorrect or can the adapter only be used with the core API?
Amendment: TestModeAdapter (extends AdviceAdapter)
@Override
protected void onMethodEnter()
{
    /**
     * InvocationLogger.setMode(LoggingMode.TESTING);
     * try
     * {
     *
     */

    insertInstructionToSetMode(LoggingMode.TESTING);

    Label l0 = new Label();
    this.l1 = new Label();
    visitTryCatchBlock(l0, l1, l1, null);
    visitLabel(l0);
}

@Override
protected void onMethodExit(int opcode)
{
    /**
     * }
     * finally
     * {
     *      InvocationLogger.setMode(LoggingMode.FRAMING);
     * }
     */

    /**
     * i.e.
     *
     *      InvocationLogger.setMode(LoggingMode.FRAMING);
     * }
     * catch (Throwable t)
     * {
     *      InvocationLogger.setMode(LoggingMode.FRAMING);
     *      throw t;
     * }
     */

    Label l2 = new Label();
    visitJumpInsn(GOTO, l2);
    visitLabel(this.l1);
    visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {"java/lang/Throwable"});
    visitVarInsn(ASTORE, 1);

    insertInstructionToSetMode(LoggingMode.FRAMING);

    visitVarInsn(ALOAD, 1);
    visitInsn(ATHROW);
    visitLabel(l2);
    visitFrame(Opcodes.F_SAME, 0, null, 0, null);

    insertInstructionToSetMode(LoggingMode.FRAMING);
}

private void insertInstructionToSetMode(LoggingMode mode)
{
    String modeValue = (mode == LoggingMode.TESTING ? FIELD_NAME_TESTING : FIELD_NAME_FRAMING);

    visitFieldInsn(Opcodes.GETSTATIC, CP_LOGGING_MODE, modeValue, FIELD_DESC_LOGGING_MODE);
    visitMethodInsn(INVOKESTATIC, CP_INVOCATION_LOGGER, METHOD_NAME_SET_MODE, METHOD_DESC_SET_MODE);
}


text:
Q: How to get data from URL using php with each of the next pages I have a link https://vi.wiktionary.org/wiki/Th%E1%BB%83_lo%E1%BA%A1i:M%E1%BB%A5c_t%E1%BB%AB_ti%E1%BA%BFng_Vi%E1%BB%87t
Can someone help me how to get all data from this link with each of the next pages?

A: you can do like this
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

source: https://www.php.net/manual/en/function.file-get-contents.php


text:
Q: Wiki proof of Lucas primality test I have a question about one step in the proof:
Why does $a^{n-1} \equiv 1\ (\operatorname{mod} n)$ imply that $a$ and $n$ are coprime?
Thank you!

A: $\rm a^{n-1}\! = 1\! +\! kn\:$ so $\rm\:d\mid a,n\:\Rightarrow\: d\mid 1 = a^{n-1}\!-kn$

A: Yet another answer: What you wrote implies $a a^{n-2} \equiv 1\ (\operatorname{ mod }n)$. However, $a$ possesses an inverse $\operatorname{mod} n$ iff $(a,n)=1$. So what you wrote is only possible if $(a,n)=1$.

A: (Assume $n \ge 2$.) From Bézout's Identity, we know $a$ and $n$ are coprime iff:
$$ax + ny = 1$$
has integer solutions $x,y$. The equation $a^{n-1} \equiv 1 \pmod n$ translates to the existence of integers $z, y$ such that:
$$za^{n-1} + ny = 1$$
Taking $x = za^{n-2}$ yields the desired equation above.


text:
Q: iPhone webapp: run JavaScript on orientation change I have a webapp saved to the iPhone homescreen, and I need to run some JavaScript when the device changes orientation.
I tried this, but it only seemed to work in a desktop browser and not on the iPhone.
window.onresize = function() {
  alert('rotation change!');
};

Is there some special event I'm supposed to hook into?

A: You're looking for onorientationchange.

A: Use this together with jQuery:
$(document).ready(function () {
  function reorient(e) {
    alert('rotation change!');
  }
  window.onorientationchange = reorient;
  window.setTimeout(reorient, 0);
});

Or you can just use onorientationchange in your code.
You don't need to use jQuery in case you dont need to know when the DOM document is ready.


text:
Q: crop image using libgdx I need to crop image like this

I need to draw partial image from center
I know there is draw() method of batch with a lot of params, but there is no good documentation about all this params, so i can't figure out how to use it.
Here is what i implemented:
public class TexturePart {

    Texture tex;
    Vector2 position;

// Target Dimension of image

    int targetWidth;
    int targetHeight;

// Src Dimensions of Image

    int srcWidth;
    int srcHeight;
    int srcX;
    int srcY;

// Ratio of dimension of target and source

    float srcTargetRatioX;
    float srcTargetRatioY;

// ImagePart variables with values between 0-100 to draw part of image

    int startPercentX;
    int endPercentX;
    int startPercentY;
    int endPercentY;

    int clipWidth;
    int clipHeight;

    int clipSrcWidth;
    int clipSrcHeight;

    public TexturePart(TextureRegion reg, float x, float y) {

        tex = reg.getTexture();
        position = new Vector2(x, y);

        srcX = reg.getRegionX();
        srcY = reg.getRegionY();

        srcWidth = reg.getRegionWidth();
        srcHeight = reg.getRegionHeight();

        clipSrcWidth = srcWidth;
        clipSrcHeight = srcHeight;
        startPercentX = 28;
        startPercentY = 28;
        endPercentX = 72;
        endPercentY = 72;
        SetTargetDimension(srcWidth, srcHeight);
    }

    public void setSrcWidthHeight(int width, int height){
        this.srcWidth=width;
        this.srcHeight=height;
    }

    public void setSrcHeight(int height){
        this.srcHeight=height;
    }

    public void SetTargetDimension(int targetWidth, int targetHeight) {
        this.targetWidth = targetWidth;
        this.targetHeight = targetHeight;
        clipWidth = targetWidth;
        clipHeight = targetHeight;
        srcTargetRatioX = (float) targetWidth / (float) srcWidth;
        srcTargetRatioY = (float) targetHeight / (float) srcHeight;
    }

    public void SetStart(int x, int y) {
        startPercentX = x;
        startPercentY = y;
    }

    public void SetEnd(int x, int y) {
        endPercentX = x;
        endPercentY = y;
    }

    public void Draw(SpriteBatch sp) {

        clipSrcWidth = (int) (Math.abs(startPercentX - endPercentX) / 100f * srcWidth);
        clipSrcHeight = (int) (Math.abs(startPercentX - endPercentY) / 100f * srcHeight);
        int startX = clipWidth/2 + (int) ((float) startPercentX / 100f * (float) srcX);
        int startY = clipHeight/2 + (int) ((float) startPercentY / 100f * (float) srcY);
        clipWidth = (int) (srcTargetRatioX * clipSrcWidth);
        clipHeight = (int) (srcTargetRatioY * clipSrcHeight);
        sp.begin();

        float scaleX=targetWidth/(srcWidth+0.f);
        float scaleY=targetHeight/(srcHeight+0.f);

        sp.draw(tex, 0, 0, srcWidth, srcHeight, srcWidth, srcHeight, 1, 1, 0, startX, startY, clipSrcWidth, clipSrcHeight, false, false);

        //sp.draw(tex, 0,0,clipWidth, clipHeight, clipWidth, clipHeight, clipSrcWidth, clipSrcHeight, false, false);
        sp.end();
    }

But its not working as expected

A: To crop the texture you just need to use TextureRegion
    TextureRegion(Texture texture, int x, int y, int width, int height)

in your case it should look like:
    Texture texture; //this is your original image

    ...

    TextureRegion region = new TextureRegion(texture, texture.getWidth()*0.28f, 0, texture.getWidth()*0.44f, texture.getHeight() );

    ...

    //now you can just draw your texture region
    sp.draw(region); //you can also use other versions of draw to set region position on screen and so on

Why i set x as texture.getWidth()*0.28f? Because if want it centered it should have left margin = 50% of original texture width - texture region width.
    (1 - 0.44) / 2 = 0.28


text:
Q: Resize image when uploading to server or when serving from server to client? My website uses many images. On a weak day users will upload hundreds of new images.
I'm trying to figure out what is the best-practice for manipulating sizes of images.
This project uses Node.js with gm module for manipulating images, but I don't think this question is node or gm specific.
I came up with several strategies, but I can't make a decision as to which is the best, and I am not sure if I am missing an obvious best-practice strategy.
Please enlighten me with your thoughts and experience.
Option 1: Resize the file with gm on every client request.
Option 1 pros:

*

*If I run gm function every time I serve a file, I can control the size, quality, compression, filters and so on whenever I need it.

*On the server I only save 1, full quality - full size version of the file and save storage space.
Option 1 cons:

*

*gm is very resource intensive, and that means that I will be abusing my RAM for every single image server to every single client.

*It means I will be always working from a big file, which makes things even worse.

*I will always have to fetch the file from my storage (in my case S3) to the server, then manipulate it, then serve it. It seems like it would create redundant bandwidth issues.
Option 2: resize the file on first upload and keep multiple sizes of the file on the server.
Option 2 pros:

*

*I will only have to use gm on uploads.

*Serving the files will require almost no resources.
Option 2 cons:

*

*I will use more storage because I will be saving multiple versions of the same file (i.e full, large, medium, small, x-small) instead of only one version.

*I will be limited to using only the sizes that were created when the user uploaded their image.

*Not flexible - If in the future I decide I need an additional size version (x-x-small for instance) I will have to run a script that processes every image in my storage to create the new version of the image.
Option 3:
Use option 2 to only process files on upload, but retain a resize module when serving file sizes that don't have a stored version in my storage.
Option 3 pros:

*

*I will be able to reduce resource usage significantly when serving files in a selection of set sizes.

Option 3 cons:

*

*I would still take more storage as in option 2 vs option 1.

*I will still have to process files when I serve them in cases where I don't have the file size I want
Option 4: I do not create multiple versions of files on upload. I do resize the images when I serve them, BUT when ever an image size was requested, this version of the file will be saved in my storage and for future requests I will not have to process the image again.
Option 4 pros:

*

*I will only use storage for the versions I use.

*I could add a new file size when ever I need, it will be automatically created on a need-basis if it doesn't already exists.

*Will use a lot of resources only once per file
Option 4 cons:

*

*Files that are only accessed once will be both resource intensive AND storage intensive. Because I will access the file, see that the size version I need doesn't exist, create the new file version, use the resources needed, and save it to my storage wasting storage space for a file that will only be used once (note, I can't know how many times files will be used)

*I will have to check if the file already exists for every request.

So,

*

*Which would you choose? Why?

*Is there a better way than the ways I suggested?

A: Solution highly depends on the usage you have for your resources. If you have an intensive utilisation then option 2 is from far the better. If not, option 1 could work nicely also.
From a qualitative point of view I think option 4 is the best of course. But for a question of simplicity and automation, I think option 2 is way better.
Because simplicity matter, I suggest to mix the option 2 and 4 : you will have a list of size (e.g. large,medium,small), but will not process them on upload but when requested as in option 4.
So that in the end, in the worst case you will arrive to the option 2 solution.
My final word would be that you should also use the <img> and/or <canvas> object in your website to perform the final sizing, so that the small computation overhead is not done on the server side.


text:
Q: Is my CPU temperature normal? On my Lenovo T400 laptop, the CPU temperature is mid 40 Celsius under Ubuntu 10.10 and mid 30 Celsius under Windows 7 when the laptop just starts up.
I was wondering if the temperatures are normal, excellent or bad? Why there is such a big difference between Windows 7 and Ubuntu 10.10?
Thanks!

A: If your machine hasn't frozen, it's still fine. Intel CPUs can operate safely at very high temperatures (another thread on this site had one i7 running at over 90 degrees Celsius).
Modern CPUs will shut down if they get too hot, hence my comment about freezing.
For your specific question, the discrepancy could be a result of different tools being used to monitor the sensors in the different operating systems, or different CPU stepping under power saving options, as Martheen has noted.

A: How do you measure them? By physically put a thermometer or from reading from a software? If software, from CPU, GPU, chipset or harddrive? Most likely, it's because some CPU power saving features is not called by Ubuntu. Or, it could be because the GPU driver in Ubuntu is not really that optimized for power saving.


text:
Q: Looking for a clean way to convert a string list to valid List in C# I'm hoping to find a better way (maybe with a nice linq expression) to convert a string list like "41,42x,43" to a list of valid long's.  The below code works, but just feels ugly.
string addressBookEntryIds = "41,42x,43";
var ids = addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries);
var addressBookEntryIdList =new List<long>();
foreach (var rec in ids)
{
    long val;
    if (Int64.TryParse(rec, out val))
    {
        addressBookEntryIdList.Add(val);
    }
}

A: string addressBookEntryIds = "41,42x,43";

Func<string, long?> safeParse = (s) => {
            long val;
            if (Int64.TryParse(s, out val))
            {
                return val;
            }
            return null;
};

var longs = (from s in addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries)
            let cand = safeParse(s)
            where cand.HasValue
            select cand.Value).ToList();

A: use regex
var list = Regex.Matches(@"41,42x,43", @"\d+").Cast<Match>().Select(x => Convert.ToInt64(x.Value)).ToList();

A: Here's another LINQ version:
String addressBookEntryIds = "41,42x,43";
Int64 val = 0;

addressBookEntryIds
  .Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries)
  .Where(id => Int64.TryParse(id, out val))
  .Select(id => val)
  .ToList()

If you prefer a query expression, you can use:
from id in addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries)
where Int64.TryParse(id, out val)
select val

A: Well, here's a LINQ version, but it's not really any less ugly!
string addressBookEntryIds = "41,42x,43";
var ids = addressBookEntryIds.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

Int64 converted;    // Working value used within the select
IEnumerable<Int64> values = ids.Select(x => new
{
    Success = Int64.TryParse(x, out converted),
    Value = converted
}).Where(x => x.Success)
  .Select(x => x.Value);

The difference between this solution and anderson's is that TryParse is only called once per entry.

A: Just a derivation of your code, quite redundant (uses TryParse and then Parse again), but I think it works:
addressBookEntryIds.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
                   .Where(id =>
                   {
                       long val;
                       return Int64.TryParse(id, out val);
                   })
                   .Select(id => Int64.Parse(id));


text:
Q: jquery, why var won't add up and why I cannot see the added img Just two things:
why does my var check won't add up(it's always 0), and what to do to fix it?
second, why I cannot add xmark images, after the table.
The setup of my html is I have alphabet imgs inside td. User should click the imgs alphabetically, every correct click the img is removed. If wrong, an xmark will appear.
(not yet in the code: after three wrongs, it's game over, and then i will ask user if he wants to play again or go back to home)
This is my jquery code:
     $("img").click(function(){
            var error = 0;
            var check = 0;
            var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            var clickedValue = $(this).attr('name');
            alert(check);

            if(clickedValue ==letterArray[check]){
                $(this).parent().empty();
                check+=1;
            } else {
                error+=1;
                $("error").add('	');
            }
        });

my table in html:
just posted the first 6 letters for brevity.

A: Each time the function gets run, new check and error variables are initialized. In order for them to keep state, you need to put them in a higher (such as global) context.
EDIT: For example:
var error = 0,
    check = 0,
    letterArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
 $("img").click(function(){
        var clickedValue = $(this).attr('name');
        alert(check);

        if(clickedValue ==letterArray[check]){
            $(this).parent().empty();
            check+=1;
        } else {
            error+=1;
            $("error").add('	');
// $("error") looks like the wrong selector. You're also misusing .add()
        }
    });

A: Put your alert(check) in the last line of your click function, that is supposed to be different from zero.

A: Your code is in fact working. If you position your alert function within the if statement and then click the last image each time you will see the image removed and the value increment.
DEMO http://jsfiddle.net/hdRT5/53/
if(clickedValue == letterArray[check]){
                $(this).parent().empty();
                check+=1;
                alert(check);
            }


text:
Q: Python & regular expressions Hi i'm making a program that will take a command such as !math(5+5) from skype and return the result, i'm having trouble getting the regex expression right, I have been reading the docs and I just can't get it right.
I am trying to support all operators, so , * /, +, -, %, and **. the trouble comes when I try to use **, either I use one regex and lose the option for exponents or have the exponent only option.

Here's my expression:
expr = re.search(r'((\d+)(\s*.?|.*\**)(\d+))', 'math(500**1000)')

And then i'm parsing it using groups,
build_expr = {
    'number1': int(expr.group(2)),
    'operator': expr.group(3),
    'number2': int(expr.group(4))
}

results for giving the reseach module the argument with exponents:
>>> expr.group()
'500**1000'
>>> expr.group(1)
'500**1000'
>>> expr.group(2)
'500'
>>> expr.group(3)
'**100'

And it works just fine and dandy with 1 character strings, such as math(500+1000)
>>> expr.group(1)
'500+1000'
>>> expr.group(2)
'500'
>>> expr.group(3)
'+'
>>> expr.group(4)
'1000'

Here's the entire function
def math_func(expr_arg):
    expr = re.search(r'((\d+)(\s*.?|.*\**)(\d+))', expr_arg)
    #parse_expr = ' '.join(expr.group()).split()

    build_expr = {
        'number1': int(expr.group(2)),
        'operator': expr.group(3),
        'number2': int(expr.group(4))
    }

    if build_expr['operator'] == '+':
        operation = build_expr['number1'] + build_expr['number2']
        return str(operation)
    elif build_expr['operator'] == '-':
        operation = build_expr['number1'] - build_expr['number2']
        return str(operation)
    elif build_expr['operator'] == '/':
        operation = build_expr['number1'] / build_expr['number2']
        return str(operation)
    elif build_expr['operator'] == '%':
        operation = build_expr['number1'] % build_expr['number2']
        return str(operation)
    elif build_expr['operator'] == '*':
        operation = build_expr['number1'] * build_expr['number2']
        return str(operation)
    elif build_expr['operator'] == '**':
        operation = build_expr['number1'] ** build_expr['number2']
        return str(operation)
    else:
        return 'Invalid operator'
    return 'shes all good son'

f = math_func('math(500+1000)')
Message.Chat.SendMessage('>> ' + f)

A: It can be matched using:
(\d+)\s*([-+*/%]+)\s*(\d+)

Breakdown:

*

*(\d+) will match one or more digits

*\s* will match the whitespaces, if there's any

*([-+*/%]+) will match one or more operator characters

A: How about just using:
(\d+)\s*(\*\*|[+/%*-])\s*(\d+)

[+/%*-] means "one character, one from the list inside brackets".
No need to wrap everything inside a capturing group, the whole match is already stored in group(0).
I'm not sure how you got to .*\** so I can't tell you what's your mistake is here, but the new regex should do the job.

A: Assuming you only have trusted data, you could just replace your math_func with eval and be done with it.


text:
Q: Unable to use Scala and Spring MVC 3 to return JSON I am converting my Java Spring controller classes to Scala.  In Java, a controller method that returned JSON was defined as this:
@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody String[] searchFoods(@RequestParam("term") String searchTerm, Principal principal) { ... }

This works as expected.  The same method in Scala looks like this:
@RequestMapping(value = Array("/search"), method = Array(RequestMethod.GET))
def searchFoods(@RequestParam("term") searchTerm: String, principal: Principal): java.util.List[String] @ResponseBody = { ... }

However, any time this path is requested I get the following exception:
2011-10-09 09:06:19.980:WARN::/searchpath/search.html
javax.servlet.ServletException: Could not resolve view with name 'searchpath/search' in servlet with name 'dispatcher'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1029)

And the web server returns an HTTP 500 error.  Is it possible to use Scala and Spring MVC 3 together to return JSON?

A: Looks like I was putting the @ResponseBody in the wrong place. It needs to appear before the method definition:
@RequestMapping(value = Array("/search"), method = Array(RequestMethod.GET))
@ResponseBody
def searchFoods(@RequestParam("term") searchTerm: String, principal: Principal): java.util.List[String]  = { ... }

I had tried this before, but forgot to clean my project. After moving the annotation to the correct location, then cleaning and rebuilding, everything was working again.  Thanks!

A: Looks like the issue isn't JSON, but path resolution.  Try changing the method annotation to:
@RequestMapping(value = Array("/searchpath/search"), method = Array(RequestMethod.GET))

See this page for a full example.


text:
Q: highlight the selected tab I am working on angularJs and bootstrap application.
Currently working on creating a tabs using angularJS, i want to highlight the selected tab so that users can easily recognize that the tab highlighted is selected. Please suggest how to highlight the selected tab with color #FBDFD9.
Please find the exisiting working code to display tabs : http://plnkr.co/edit/CAlrAzHO2THuglQrsTIi?p=preview
sample html code:

    <tabset>
        <tab ng-repeat="workspace in workspaces"
             heading="{{workspace.name}}"
             active=workspace.active>

                    {{$parent.workspace.id}} : {{ $parent.workspace.name}}

                <input type="text" ng-model="workspace.name"/>

        </tab>
        <tab select="addWorkspace()">
            <tab-heading>

            </tab-heading>
        </tab>
    </tabset>

--EDIT--
Please suggest how to show the outline of the tabs. If there are many tabs, its appearing just like a text without any outline indicating that as a tab. If noticed the output in http://plnkr.co/edit/CAlrAzHO2THuglQrsTIi?p=preview , outline of the tab is shown only for the selected tab. Please advice how to show the outlines of all the tabs(active tab and inactive tabs). I tried to find the solution but could not find the appropriate ID or classname of the tab to write the css code to show the outer line of the tabs.

A: I inspected the HTML with Chrome to see which CSS selector is being used in Bootstrap to style active tabs. Modify your CSS to add this rule:
.nav-tabs>.active>a, .nav-tabs>.active>a:hover, .nav-tabs>.active>a:focus {
  background-color: #FBDFD9;
}

A: Bootstrap adds active class to the active tab, so just target it in your css:
.nav-tabs>.active>a {
  background-color: #FBDFD9;
}

Since the specificity of the selector .nav-tabs>.active>a is the same as the specificity of bootstrap's selector, to have your styles override either use !important
.nav-tabs>.active>a {
  background-color: #FBDFD9; !important;
}

or place your custom styles after bootstrap's in index.html:
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" href="index.css">

Here is working example.


text:
Q: Environment issues with running Anaconda Python in VS Code I am trying to learn Python and debug code for the first time in VS Code (latest edition).  I have anaconda running and the code I have runs fine by itself but now I need to know how to update the code and debug it for the first time.
I keep getting the following error related to NumPy:

Exception has occurred: ImportError
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.
We have compiled some common reasons and troubleshooting tips at:
https://numpy.org/devdocs/user/troubleshooting-importerror.html
Please note and check the following:

*

*The Python version is: Python3.7 from "C:\Miniconda2\envs\myproject_flask\python.exe"

*The NumPy version is: "1.18.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.
Original error was: DLL load failed: The specified module could not be found.

In the Miniconda path above the Python.exe is version 3.7.7. I tried to install NumPy like so in myproject directory:

(myproject_flask) c:\MyProject\source\MyProject.Flask>conda install numpy=1.18.5

I still get the same error when I go to F5 to debug and run to a breakpoint.
Need help with my environment.
I need to use VS Code in my Windows environment with Anaconda.

A: You should launch VS Code from Anaconda Navigator so that the environment is initialized.

A: When you have problems with importing the numpy C-extensions in Anaconda it's very likely that your virtual environment hasn't been activated. Having just Python on the path is not good enough. You also need access to the libraries. This is what the activation does.
When you are running/debugging code you should see a terminal open. You can tell from the prompt
(myproject_flask) C:\MyProject

that conda has been activated. Sometimes this just takes a bit too long for VSCode. So simply push the start button a second time.
Note that the Code Runner extension in VSCode is also known to cause this kind of problems.
However, I wonder why you are using Miniconda2 with Python3, although in general this should work.

A: I was getting the error even after adding all the anaconda paths, it was due to VScode running the code in the python debugger terminal which is not able to enter the conda environment.
This worked for me:
press ctrl+Shift+P > Type Terminal:Select Default profile > Select Command prompt
after this code ran in Command prompt by default, inside the environment.


text:
Q: Problem using paging in Buzz API? I am using Buzz REST API to retrieve all the buzz public updates from 1-08-2011 to 28-082011 and my query term is 'lokpal'. I need to get all the updates that people did about this topic or any other activity with tag 'Anna Hazere'. I have prepared the URL that is:
    REST GET URL
    https://www.googleapis.com/buzz/v1/activities/search?key=AIzaSyD7O9D4uEFyEexRPtxaU1fCsh0yu5leum4&q=lokpal+date%3E2011-07-31+date%3C2011-08-28&alt=json&max-results=100&safe=medium

where %3E refers to '>'  and %3C refers to '<' .

Can someone suggest me how to apply paging property to this and also retrieve all the updates that happened ion public stream. I am already able to get the activities in JSON format but want all the public updates.
Refer:http://code.google.com/apis/buzz/v1/using_rest.html

A: Within the body of the response is a links structure. One of the links is the next link, which is the URL for page 2. In your case, that would be:
https://www.googleapis.com/buzz/v1/activities/search?q=lokpal+date%3E2011-07-31+date%3C2011-08-28&alt=json&max-results=100&c=100


text:
Q: Generate CommonTree from Antlr Lexer and Parser definition
Possible Duplicate:
How to output the AST built using ANTLR?

Is there a way to transform my lexer and parser definition files (.g)
to a CommonTree? (During the process where my parsergenerator is created)
I dont want to use my generated parser. I want the natural antlr parser (which parses lexer and parser definition files) to spit me out a CommonTree object.

A: Sure, it's available here: http://www.antlr.org/grammar/ANTLR/
Posted below to prevent possible link-rot:
/*
 [The "BSD licence"]
 Copyright (c) 2005-2007 Terence Parr
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/** ANTLR v3 grammar written in ANTLR v3 with AST construction */
grammar ANTLRv3;

options {
    output=AST;
    ASTLabelType=CommonTree;
}

tokens {
    DOC_COMMENT;
    PARSER;
    LEXER;
    RULE;
    BLOCK;
    OPTIONAL;
    CLOSURE;
    POSITIVE_CLOSURE;
    SYNPRED;
    RANGE;
    CHAR_RANGE;
    EPSILON;
    ALT;
    EOR;
    EOB;
    EOA; // end of alt
    ID;
    ARG;
    ARGLIST;
    RET;
    LEXER_GRAMMAR;
    PARSER_GRAMMAR;
    TREE_GRAMMAR;
    COMBINED_GRAMMAR;
    INITACTION;
    LABEL; // $x used in rewrite rules
    TEMPLATE;
    SCOPE='scope';
    SEMPRED;
    GATED_SEMPRED; // {p}? =>
    SYN_SEMPRED; // (...) =>   it's a manually-specified synpred converted to sempred
    BACKTRACK_SEMPRED; // auto backtracking mode syn pred converted to sempred
    FRAGMENT='fragment';
    TREE_BEGIN='^(';
    ROOT='^';
    BANG='!';
    RANGE='..';
    REWRITE='->';
}

@members {
    int gtype;
}

grammarDef
    :   DOC_COMMENT?
        (   'lexer'  {gtype=LEXER_GRAMMAR;}    // pure lexer
        |   'parser' {gtype=PARSER_GRAMMAR;}   // pure parser
        |   'tree'   {gtype=TREE_GRAMMAR;}     // a tree parser
        |            {gtype=COMBINED_GRAMMAR;} // merged parser/lexer
        )
        g='grammar' id ';' optionsSpec? tokensSpec? attrScope* action*
        rule+
        EOF
        -> ^( {adaptor.create(gtype,$g)}
              id DOC_COMMENT? optionsSpec? tokensSpec? attrScope* action* rule+
            )
    ;

tokensSpec
    :   TOKENS tokenSpec+ '}' -> ^(TOKENS tokenSpec+)
    ;

tokenSpec
    :   TOKEN_REF
        (   '=' (lit=STRING_LITERAL|lit=CHAR_LITERAL)   -> ^('=' TOKEN_REF $lit)
        |                                               -> TOKEN_REF
        )
        ';'
    ;

attrScope
    :   'scope' id ACTION -> ^('scope' id ACTION)
    ;

/** Match stuff like @parser::members {int i;} */
action
    :   '@' (actionScopeName '::')? id ACTION -> ^('@' actionScopeName? id ACTION)
    ;

/** Sometimes the scope names will collide with keywords; allow them as
 *  ids for action scopes.
 */
actionScopeName
    :   id
    |   l='lexer'   -> ID[$l]
    |   p='parser'  -> ID[$p]
    ;

optionsSpec
    :   OPTIONS (option ';')+ '}' -> ^(OPTIONS option+)
    ;

option
    :   id '=' optionValue -> ^('=' id optionValue)
    ;

optionValue
    :   id
    |   STRING_LITERAL
    |   CHAR_LITERAL
    |   INT
    |   s='*' -> STRING_LITERAL[$s]  // used for k=*
    ;

rule
scope {
    String name;
}
    :   DOC_COMMENT?
        ( modifier=('protected'|'public'|'private'|'fragment') )?
        id {$rule::name = $id.text;}
        '!'?
        ( arg=ARG_ACTION )?
        ( 'returns' rt=ARG_ACTION  )?
        throwsSpec? optionsSpec? ruleScopeSpec? ruleAction*
        ':' altList ';'
        exceptionGroup?
        -> ^( RULE id {modifier!=null?adaptor.create(modifier):null} ^(ARG $arg)? ^(RET $rt)?
              optionsSpec? ruleScopeSpec? ruleAction*
              altList
              exceptionGroup?
              EOR["EOR"]
            )
    ;

/** Match stuff like @init {int i;} */
ruleAction
    :   '@' id ACTION -> ^('@' id ACTION)
    ;

throwsSpec
    :   'throws' id ( ',' id )* -> ^('throws' id+)
    ;

ruleScopeSpec
    :   'scope' ACTION -> ^('scope' ACTION)
    |   'scope' id (',' id)* ';' -> ^('scope' id+)
    |   'scope' ACTION
        'scope' id (',' id)* ';'
        -> ^('scope' ACTION id+ )
    ;

block
    :   lp='('
        ( (opts=optionsSpec)? ':' )?
        a1=alternative rewrite ( '|' a2=alternative rewrite )*
        rp=')'
        -> ^( BLOCK[$lp,"BLOCK"] optionsSpec? (alternative rewrite?)+ EOB[$rp,"EOB"] )
    ;

altList
@init {
    // must create root manually as it's used by invoked rules in real antlr tool.
    // leave here to demonstrate use of {...} in rewrite rule
    // it's really BLOCK[firstToken,"BLOCK"]; set line/col to previous ( or : token.
    CommonTree blkRoot = (CommonTree)adaptor.create(BLOCK,input.LT(-1),"BLOCK");
}
    :   a1=alternative rewrite ( '|' a2=alternative rewrite )*
        -> ^( {blkRoot} (alternative rewrite?)+ EOB["EOB"] )
    ;

alternative
@init {
    Token firstToken = input.LT(1);
    Token prevToken = input.LT(-1); // either : or | I think
}
    :   element+ -> ^(ALT[firstToken,"ALT"] element+ EOA["EOA"])
    |   -> ^(ALT[prevToken,"ALT"] EPSILON[prevToken,"EPSILON"] EOA["EOA"])
    ;

exceptionGroup
    :   ( exceptionHandler )+ ( finallyClause )?
    |   finallyClause
    ;

exceptionHandler
    :    'catch' ARG_ACTION ACTION -> ^('catch' ARG_ACTION ACTION)
    ;

finallyClause
    :    'finally' ACTION -> ^('finally' ACTION)
    ;

element
    :   elementNoOptionSpec
    ;

elementNoOptionSpec
    :   id (labelOp='='|labelOp='+=') atom
        (   ebnfSuffix  -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] ^($labelOp id atom) EOA["EOA"]) EOB["EOB"]))
        |               -> ^($labelOp id atom)
        )
    |   id (labelOp='='|labelOp='+=') block
        (   ebnfSuffix  -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] ^($labelOp id block) EOA["EOA"]) EOB["EOB"]))
        |               -> ^($labelOp id block)
        )
    |   atom
        (   ebnfSuffix  -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] atom EOA["EOA"]) EOB["EOB"]) )
        |               -> atom
        )
    |   ebnf
    |   ACTION
    |   SEMPRED ( '=>' -> GATED_SEMPRED | -> SEMPRED )
    |   treeSpec
        (   ebnfSuffix  -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] treeSpec EOA["EOA"]) EOB["EOB"]) )
        |               -> treeSpec
        )
    ;

atom:   range ( (op='^'|op='!') -> ^($op range) | -> range )
    |   terminal
    |   notSet ( (op='^'|op='!') -> ^($op notSet) | -> notSet )
    |   RULE_REF ( arg=ARG_ACTION )? ( (op='^'|op='!') )?
        -> {$arg!=null&&op!=null}?  ^($op RULE_REF $arg)
        -> {$arg!=null}?            ^(RULE_REF $arg)
        -> {$op!=null}?             ^($op RULE_REF)
        -> RULE_REF
    ;

notSet
    :   '~'
        (   notTerminal -> ^('~' notTerminal)
        |   block       -> ^('~' block)
        )
    ;

treeSpec
    :   '^(' element ( element )+ ')' -> ^(TREE_BEGIN element+)
    ;

/** Matches ENBF blocks (and token sets via block rule) */
ebnf
@init {
    Token firstToken = input.LT(1);
}
@after {
    $ebnf.tree.getToken().setLine(firstToken.getLine());
    $ebnf.tree.getToken().setCharPositionInLine(firstToken.getCharPositionInLine());
}
    :   block
        (   op='?'  -> ^(OPTIONAL[op] block)
        |   op='*'  -> ^(CLOSURE[op] block)
        |   op='+'  -> ^(POSITIVE_CLOSURE[op] block)
        |   '=>'    // syntactic predicate
                    -> {gtype==COMBINED_GRAMMAR &&
                        Character.isUpperCase($rule::name.charAt(0))}?
                       // if lexer rule in combined, leave as pred for lexer
                       ^(SYNPRED["=>"] block)
                    // in real antlr tool, text for SYN_SEMPRED is predname
                    -> SYN_SEMPRED
        |           -> block
        )
    ;

range!
    :   c1=CHAR_LITERAL RANGE c2=CHAR_LITERAL -> ^(CHAR_RANGE[$c1,".."] $c1 $c2)
    ;

terminal
    :   (   CHAR_LITERAL                -> CHAR_LITERAL
            // Args are only valid for lexer rules
        |   TOKEN_REF
            ( ARG_ACTION                -> ^(TOKEN_REF ARG_ACTION)
            |                           -> TOKEN_REF
            )
        |   STRING_LITERAL              -> STRING_LITERAL
        |   '.'                         -> '.'
        )
        (   '^'                         -> ^('^' $terminal)
        |   '!'                         -> ^('!' $terminal)
        )?
    ;

notTerminal
    :   CHAR_LITERAL
    |   TOKEN_REF
    |   STRING_LITERAL
    ;

ebnfSuffix
@init {
    Token op = input.LT(1);
}
    :   '?' -> OPTIONAL[op]
    |   '*' -> CLOSURE[op]
    |   '+' -> POSITIVE_CLOSURE[op]
    ;

// R E W R I T E  S Y N T A X

rewrite
@init {
    Token firstToken = input.LT(1);
}
    :   (rew+='->' preds+=SEMPRED predicated+=rewrite_alternative)*
        rew2='->' last=rewrite_alternative
        -> ^($rew $preds $predicated)* ^($rew2 $last)
    |
    ;

rewrite_alternative
options {backtrack=true;}
    :   rewrite_template
    |   rewrite_tree_alternative
    |   /* empty rewrite */ -> ^(ALT["ALT"] EPSILON["EPSILON"] EOA["EOA"])
    ;

rewrite_tree_block
    :   lp='(' rewrite_tree_alternative ')'
        -> ^(BLOCK[$lp,"BLOCK"] rewrite_tree_alternative EOB[$lp,"EOB"])
    ;

rewrite_tree_alternative
    :   rewrite_tree_element+ -> ^(ALT["ALT"] rewrite_tree_element+ EOA["EOA"])
    ;

rewrite_tree_element
    :   rewrite_tree_atom
    |   rewrite_tree_atom ebnfSuffix
        -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] rewrite_tree_atom EOA["EOA"]) EOB["EOB"]))
    |   rewrite_tree
        (   ebnfSuffix
            -> ^(ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] rewrite_tree EOA["EOA"]) EOB["EOB"]))
        |   -> rewrite_tree
        )
    |   rewrite_tree_ebnf
    ;

rewrite_tree_atom
    :   CHAR_LITERAL
    |   TOKEN_REF ARG_ACTION? -> ^(TOKEN_REF ARG_ACTION?) // for imaginary nodes
    |   RULE_REF
    |   STRING_LITERAL
    |   d='$' id -> LABEL[$d,$id.text] // reference to a label in a rewrite rule
    |   ACTION
    ;

rewrite_tree_ebnf
@init {
    Token firstToken = input.LT(1);
}
@after {
    $rewrite_tree_ebnf.tree.getToken().setLine(firstToken.getLine());
    $rewrite_tree_ebnf.tree.getToken().setCharPositionInLine(firstToken.getCharPositionInLine());
}
    :   rewrite_tree_block ebnfSuffix -> ^(ebnfSuffix rewrite_tree_block)
    ;

rewrite_tree
    :   '^(' rewrite_tree_atom rewrite_tree_element* ')'
        -> ^(TREE_BEGIN rewrite_tree_atom rewrite_tree_element* )
    ;

/** Build a tree for a template rewrite:
      ^(TEMPLATE (ID|ACTION) ^(ARGLIST ^(ARG ID ACTION) ...) )
    where ARGLIST is always there even if no args exist.
    ID can be "template" keyword.  If first child is ACTION then it's
    an indirect template ref

    -> foo(a={...}, b={...})
    -> ({string-e})(a={...}, b={...})  // e evaluates to template name
    -> {%{$ID.text}} // create literal template from string (done in ActionTranslator)
    -> {st-expr} // st-expr evaluates to ST
 */
rewrite_template
    :   // -> template(a={...},...) "..."    inline template
        id lp='(' rewrite_template_args ')'
        ( str=DOUBLE_QUOTE_STRING_LITERAL | str=DOUBLE_ANGLE_STRING_LITERAL )
        -> ^(TEMPLATE[$lp,"TEMPLATE"] id rewrite_template_args $str)

    |   // -> foo(a={...}, ...)
        rewrite_template_ref

    |   // -> ({expr})(a={...}, ...)
        rewrite_indirect_template_head

    |   // -> {...}
        ACTION
    ;

/** -> foo(a={...}, ...) */
rewrite_template_ref
    :   id lp='(' rewrite_template_args ')'
        -> ^(TEMPLATE[$lp,"TEMPLATE"] id rewrite_template_args)
    ;

/** -> ({expr})(a={...}, ...) */
rewrite_indirect_template_head
    :   lp='(' ACTION ')' '(' rewrite_template_args ')'
        -> ^(TEMPLATE[$lp,"TEMPLATE"] ACTION rewrite_template_args)
    ;

rewrite_template_args
    :   rewrite_template_arg (',' rewrite_template_arg)*
        -> ^(ARGLIST rewrite_template_arg+)
    |   -> ARGLIST
    ;

rewrite_template_arg
    :   id '=' ACTION -> ^(ARG[$id.start] id ACTION)
    ;

id  :   TOKEN_REF -> ID[$TOKEN_REF]
    |   RULE_REF  -> ID[$RULE_REF]
    ;

// L E X I C A L   R U L E S

SL_COMMENT
    :   '//'
        (   ' $ANTLR ' SRC // src directive
        |   ~('\r'|'\n')*
        )
        '\r'? '\n'
        {$channel=HIDDEN;}
    ;

ML_COMMENT
    :   '/*' {if (input.LA(1)=='*') $type=DOC_COMMENT; else $channel=HIDDEN;} .* '*/'
    ;

CHAR_LITERAL
    :   '\'' LITERAL_CHAR '\''
    ;

STRING_LITERAL
    :   '\'' LITERAL_CHAR LITERAL_CHAR* '\''
    ;

fragment
LITERAL_CHAR
    :   ESC
    |   ~('\''|'\\')
    ;

DOUBLE_QUOTE_STRING_LITERAL
    :   '"' (ESC | ~('\\'|'"'))* '"'
    ;

DOUBLE_ANGLE_STRING_LITERAL
    :   '<<' .* '>>'
    ;

fragment
ESC :   '\\'
        (   'n'
        |   'r'
        |   't'
        |   'b'
        |   'f'
        |   '"'
        |   '\''
        |   '\\'
        |   '>'
        |   'u' XDIGIT XDIGIT XDIGIT XDIGIT
        |   . // unknown, leave as it is
        )
    ;

fragment
XDIGIT :
        '0' .. '9'
    |   'a' .. 'f'
    |   'A' .. 'F'
    ;

INT :   '0'..'9'+
    ;

ARG_ACTION
    :   NESTED_ARG_ACTION
    ;

fragment
NESTED_ARG_ACTION :
    '['
    (   options {greedy=false; k=1;}
    :   NESTED_ARG_ACTION
    |   ACTION_STRING_LITERAL
    |   ACTION_CHAR_LITERAL
    |   .
    )*
    ']'
    {setText(getText().substring(1, getText().length()-1));}
    ;

ACTION
    :   NESTED_ACTION ( '?' {$type = SEMPRED;} )?
    ;

fragment
NESTED_ACTION :
    '{'
    (   options {greedy=false; k=2;}
    :   NESTED_ACTION
    |   SL_COMMENT
    |   ML_COMMENT
    |   ACTION_STRING_LITERAL
    |   ACTION_CHAR_LITERAL
    |   .
    )*
    '}'
   ;

fragment
ACTION_CHAR_LITERAL
    :   '\'' (ACTION_ESC|~('\\'|'\'')) '\''
    ;

fragment
ACTION_STRING_LITERAL
    :   '"' (ACTION_ESC|~('\\'|'"'))* '"'
    ;

fragment
ACTION_ESC
    :   '\\\''
    |   '\\' '"' // ANTLR doesn't like: '\\"'
    |   '\\' ~('\''|'"')
    ;

TOKEN_REF
    :   'A'..'Z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
    ;

RULE_REF
    :   'a'..'z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
    ;

/** Match the start of an options section.  Don't allow normal
 *  action processing on the {...} as it's not a action.
 */
OPTIONS
    :   'options' WS_LOOP '{'
    ;

TOKENS
    :   'tokens' WS_LOOP '{'
    ;

/** Reset the file and line information; useful when the grammar
 *  has been generated so that errors are shown relative to the
 *  original file like the old C preprocessor used to do.
 */
fragment
SRC :   'src' ' ' file=ACTION_STRING_LITERAL ' ' line=INT
    ;

WS  :   (   ' '
        |   '\t'
        |   '\r'? '\n'
        )+
        {$channel=HIDDEN;}
    ;

fragment
WS_LOOP
    :   (   WS
        |   SL_COMMENT
        |   ML_COMMENT
        )*
    ;


text:
Q: How to skip some content from screen reader I want to skip some content from reading of screen reader.
consider this html

   ...

Dont read this content. This content will be loaded from javascript

   ...

Though the aria-hidden=true is set for the div, the content is read by screen reader. Please help to skip this content

A: Your code looks right, how are you testing this?
Not all browsers / screen readers will support this yet.
Try setting style="display:none;" as this may be more widely supported at the moment.


text:
Q: Suppress output of slide numbers for slides without number for Beamer There is a question about how not to number some slides: Beamer: \nonumber equivalent for slides?
However the slides themselves still have their number printed.
How can I suppress output of that as well?
MWE:
\documentclass{beamer}

\usetheme{Dresden}

\setbeamertemplate{footline}[frame number]{}

\begin{document}

%do not want slide number here
\begin{frame}[noframenumbering]
 \titlepage
\end{frame}

\begin{frame}
Some actual content here
\end{frame}

%and here
\begin{frame}[noframenumbering]
{\Huge Section 2}
\end{frame}

\begin{frame}
Some more actual content here
\end{frame}

%and possibly on 20 more slides
%without specifying format for each of special slides
%every time

\end{document}

A: There are basically three options, how to get rid of the framenumbers:

*

*remove head- and footline via:

\begin{frame}[noframenumbering, plain]...

*temporarily clear the footline

 { \setbeamertemplate{footline}{} \begin{frame}[noframenumbering] \titlepage \end{frame} }

*temporarily redefining the footline

This heavily depends on the used outer theme. With \setbeamertemplate{footline}[frame number]{} used in the MWE this brings no advantage compared to option 2.

To make this automatic for a large number of frames, one can define custom keys. The following example illustrates, how this could work with option 2.:
\documentclass{beamer}
\usetheme{Dresden}

\usepackage{etoolbox}

\defbeamertemplate{footline}{nonum}{%
    \addtocounter{framenumber}{-1}
}

\BeforeBeginEnvironment{frame}{%
\setbeamertemplate{footline}[frame number]{}
}

\makeatletter
\define@key{beamerframe}{nonum}[true]{%
    \setbeamertemplate{footline}[nonum]%
}
\makeatother

\begin{document}

    \begin{frame}[nonum]
        Removeframenumber
    \end{frame}

    \begin{frame}
        normal frame
    \end{frame}

\end{document}

A: I would say the best thing is to link noframenumbering to suppress the print; this can be done using the following toggle:
\setbeamertemplate{navigation symbols}{
\ifbeamer@noframenumbering
\else
  \usebeamerfont{page number in head/foot}
  \usebeamercolor[fg]{page number in head/foot}%
  \hbox to 2cm{\hfil\insertframenumber/\inserttotalframenumber\hfil}
  \vskip2pt\relax
\fi%
}


text:
Q: Безопасность статического сайта Имеется статический сайт на GitHub Pages, где допустимо хранить только html, css и javascript . Читал, что статические сайты менее уязвимы к взлому, но не на 100%.
Пароли хранятся в надёжном месте, браузер портативный.
Каким образом могут осуществляться хакерские атаки на статический сайт, и как от них защититься?

A: Прежде чем говорить о возможности взлома, надо оценить возможный профит от этого:

*

*Получение контроля над чужими вычислительными мощностями: малореально, Github защищается даже от вас в этом отношении: он не позволяет использовать пользовательские плагины для Jekyll (единственного поддерживаемого движка), которые могут содержать произвольный код на Ruby.
Держитесь крепче за свой GitHub-аккаунт:

*

*Включите двухфакторную аутентификацию.

*Для аутентификации через Git используйте SSH-ключи, и назначайте им такие имена, чтобы можно было узнать, какому ключу при случае закрывать доступ.

*Получение конфиденциальных данных пользователей: а вы их собираете? Храните? Github Pages не даёт никаких возможностей по хранению на стороне сервера. Остаётся вариант хранения данных на клиенте (там чего только нет нынче: WebSQL, IndexedDB, LocalStorage) или перехват прямо при вводе.
При отсутствии доступа к клиенту хотя бы на уровне браузера (если у пользователя вредоносные расширения в браузере или дыры/лазейки в ОС, вы вряд ли что-то сделаете) остаётся только обманом заставить пользователя выполнить JS-код злоумышленника: это XSS.
Самый банальный случай — вывод фрагмента URL без экранирования: если там "случайно" (по присланной кем-то ссылке) окажется <script> с вредоносным кодом, браузер его загрузит и выполнит. Бывают и менее явные, это обширная тема.

*Приведение сайта в неработоспособное состояние...
Блокировки провайдерами взломом, наверное, всё же не считаются, хотя и делают сайт неработоспособным для определённого круга пользователей. Рассматриваем неработоспособность для всех (или почти всех; конечно, из исходников любой может поднять копию у себя).
Уязвимым местом является разве что домен: его теоретически могут "угнать" и направить его к машине злоумышленника. Если вы используете *.github.io, то вы полагаетесь в защите домена на GitHub. Если используете собственный, держитесь крепче за аккаунт у регистратора.


text:
Q: can spatial indexes be used for join in mysql? Can spatial indexes be used for joining tables in mysql?
I have two tables with a GEOMETRY column and a spatial index on it. The table is MyISAM.
I would like to join these tables on the rows which intersect.
I cannot get mysql to use the spatial indexes despite using FORCE INDEX in my query.
The query is:
SELECT *
FROM a FORCE INDEX FOR JOIN (asidx)
JOIN b FORCE INDEX FOR JOIN (bsidx)
     ON Intersects(a.g, b.g) -- g is the name of the GEOMETRY

The explain plan is:

| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows  | Extra                          |
|  1 | SIMPLE      | a     | ALL  | asidx         | NULL | NULL    | NULL | 50000 |                                |
|  1 | SIMPLE      | b     | ALL  | bsidx         | NULL | NULL    | NULL | 50000 | Using where; Using join buffer |

Why aren't the indexes use?
For 50k rows tables it runs for 15 minutes.
How can I make it faster?

A: Yes, spatial indexes can be used for joins, but you aren't using an index for your join.
In order for a index to be used for a search, MySQL needs a constant, or an expression that refers to a data column that has already been read.
You're not referencing an indexed column in your ON clause. You're referencing 0 or 1, which is the result of the INTERSECTS() function.
Your ON clause specifies a function on columns from both tables in the join. MySQL won't have the column values required for the function until both records are already read, so no index can be used for the join, requiring a full scan.
Basically, MySQL doesn't know if two records go together until it tries it, so it must try every combination.
Perhaps a better solution would be to precalculate a table of intersection pairs, store them in a separate (junction) table, and join that way.


text:
Q: Msado60_Backcompat crashes in CCommand::CreateParameter I am developing an ADO application (32 bit) on Windows 7 64 bit SP1 (all updates installed): The app must run on Win XP. According to http://support.microsoft.com/kb/2517589/en-us I am using msado60_backcompat. That worked well until lately, but now it crashes.
My code (snippets):
_CommandPtr cmd(__uuidof(Command));
cmd->ActiveConnection = dbconn;
cmd->CommandText = _T("SELECT [si] FROM [TTable] WHERE [TTable].[ti1]=?");
cmd->Parameters->Append(cmd->CreateParameter(L"@ti1", adTinyInt, adParamInput, 1, 7));

CreateParameter is implemented in msado60_backcompat:
inline _ParameterPtr Command15::CreateParameter ( _bstr_t Name, enum DataTypeEnum Type, enum ParameterDirectionEnum Direction, ADO_LONGPTR Size, const _variant_t & Value )
{
  struct _Parameter * _result = 0;
  HRESULT _hr = raw_CreateParameter(Name, Type, Direction, Size, Value, &_result);
  if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
  return _ParameterPtr(_result, false);
}

raw_CreateParameter() calls into msado15.dll into CCommand::CreateParameter. There a crash occurs at offset 0x34f (offset inside the function):

First-chance exception at 0x655ed5a6 (msado15.dll) in adosqlbugcheck.exe: 0xC0000005: Access violation writing location 0xcccccccc.
  Unhandled exception at 0x655ed5a6 (msado15.dll) in adosqlbugcheck.exe: 0xC0000005: Access violation writing location 0xcccccccc.

Msado60_Backcompat.tlb: 73728 bytes, 29.4.2011
msado15.dll: 6.1.7601.17514, 1019904 bytes, 21.11.2010
The error does not occur if I use msado15.dll.
Can someone reproduce the error? Is there a solution?

A: The issue is solved. I was #import-ing the msado60_backcompat.tlb from "C:\Program Files\Common Files". If I import the version from "C:\Program Files (x86)\Common Files" it works. The compiler generates tlh files from both tlb files with exactly the same UUIDs and everything else, they only differ in that the one contains
typedef __int64 ADO_LONGPTR;
typedef ADO_LONGPTR PositionEnum_Param;

While the other contains
typedef long ADO_LONGPTR;
typedef enum PositionEnum PositionEnum_Param;

From my understanding of COM interfaces this should not happen. But since MS commits they really made a mistake it seems to just be the way it is.
Just for information, MS has a new solution coming up: http://blogs.msdn.com/b/psssql/archive/2011/10/03/yes-we-made-a-mistake-and-are-finally-going-to-fix-it.aspx.


text:
Q: Can't Properly Float List To Right Edit Mission accomplished, thank you for your replies. If anyone can help me with the click to expand/fade to view feature, it would be very helpful. I'm currently looking into it.
I am working on a very simple navigation for my website. I can't figure out why the texts can't stick to the right. Here is an example: http://jsfiddle.net/E6ArK/
I also hope to add a click-to-expand and maybe a fade into view feature some time. Any help would be much appreciated.
HTML

Applications

Not Available

Not Available

Forum

Not Available

Not Available

Guilds

Not Available

Not Available

Imageboards

People

Random

Screen Shots

Wallpapers

Projects

Not Available

Not Available

CSS
/* NAVIGATION */

/* Heading */
 .navigation ul li h1 {
    background : #000000;
    color : #ffffff;
    display : table;
    font-weight : 100;
    margin : 0;
    padding : 6px;
    border-right : 3px solid #ffffff;
    font-size : 28px;
    margin-bottom : 3px;
}
/* Positioning */
 .navigation {
    font-family :'Open Sans Condensed', sans-serif;
    margin : 12px;
    position : fixed;
    right : 0;
    top : 0;
}
.navigation ul {
    font-size : 20px;
    margin : 0;
    padding : 0;
    text-align : right;
}
.navigation ul li {
    clear : right;
    color : #ffffff;
    float : right;
    list-style-type : none;
}
/* Second Level */
 .navigation ul li ul {
    display : none;
}
.navigation ul li:hover ul {
    display : block;
}
.navigation ul li ul li {
    background : #000000;
    border-right : 3px solid #ff0000;
    color : #ffffff;
    display : table;
    font-size : 18px;
    margin-bottom : 3px;
    padding : 6px;
}

A: You need to float the heading to the right as well. Add float: right to your block of rules for .navigation ul li h1. That should keep them stuck to the right.

A: You simply need to add a float:right property to your heading styling:
 /* Heading */
 .navigation ul li h1 {
    background : #000000;
    color : #ffffff;
    display : table;
    font-weight : 100;
    margin : 0;
    padding : 6px;
    border-right : 3px solid #ffffff;
    font-size : 28px;
    margin-bottom : 3px;
    float: right;
}

Hope that helps


text:
Q: In Swift, will future new APIs be overridden by user-defined methods in existing apps on the App Store? In Objective-C, for example, if Apple adds new method called method1 to UIView, existing apps which are already released to the App Store and use the following code could crash or behave unexpectedly:
// Objective-C
@interface MyView : UIView
- (void)method1;
@end

// Swift
class MyView : UIView {
    func method1() {
        // do something
    }
}

But in Swift, to override a method, you need a override keyword to prevent overriding accidentally.
If you override a method without override keyword, the compiler generates compile-time error.

What will happen if Apple adds new API methods in the next iOS versions, and if my apps or your apps use methods whose name are the same as the new APIs' names.

In Swift, will new API methods be overridden by methods in existing apps like Objective-C?
Or new APIs don't effect existing same-name user-defined methods thanks to Swift's explicit override feature (override keyword)?

A: If your app is already built and uploaded no you won't have an issue.
But if you try to re-build the app for a new update and you have the bad luck they named a new Api Method the same name of your Object Method, most likely the error you might get is only if the place you use the method you don't use a correct identifier like Not calling self.method1() and just calling method1() and your object inherits from UIViewController, which coincidently has that new Method1.
other than that I wouldn't worry about that type of issue happening, well at least I haven't had an issue like this the 3-4 years I have been programming for iOS.
//Lets assume UIViewController has a new Method in the Api now which
//they updated called   Method1

class MyViewController :UIViewController {

  init {
     //When you try to re-build your app this line of code right here would complain
     //because of ambiguity, two methods called the same one from your
     //Parent Class and your own Class.
     //method1()

     //"super.method1()"  or code below to solve the ambiguity issue.
     self.method1()
  }

//Added this just because I happen to use UIViewController.
 override viewDidLoad() {
     super.viewDidLoad()
 }

  //Your own method without Override, since you want to use your own method.
  func method1() {
    //Does something important
  }

}

Update Based on your comment:
1) Is there a documentation about it or did you tested it yourself in Swift?
I have tested it myself because I have Apps in the App Store. So what happens is that whatever is already uploaded the code will be working because the App you uploaded prepackages the Frameworks with their current working Apis and your Classes.
And No, I have not seen a Documentation about it, I know about it because I have personally see it.
2) And I think you can't define func method1() without a override keyword if UIViewController already has func method1()
Thats correct! Assuming the APi has a method already you have the write Override keyword to be able to use that function with the same name. But remember according to your scenario you mentioned that the API created that method with that name AFTER you had already your project uploaded in the AppStore. So the problem you would only see it when doing some new coding and trying to Rebuild the app.


text:
Q: location of properties file in spring mvc project I am trying to inject values of a properties file into a controller in a spring mvc project. I am using spring version 5.0.4.
Below is the definition of my servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="mu.mra" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Define Spring MVC view resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <util:properties id="countryOptions" location="classpath: countries.properties" />

</beans>

the properties file is located in the src/main/resources folder. But unfortunately I am getting the error below

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'studentController': Unsatisfied
  dependency expressed through field 'countryOptions'; nested exception
  is org.springframework.beans.factory.BeanExpressionException:
  Expression parsing failed; nested exception is
  org.springframework.expression.spel.SpelEvaluationException: EL1021E:
  A problem occurred whilst attempting to access the property
  'countryOptions': 'Error creating bean with name 'countryOptions':
  Invocation of init method failed; nested exception is
  java.io.FileNotFoundException: class path resource [
  countries.properties] cannot be opened because it does not exist'

I am not too sure about the location of the properties file. Should it be in the WEB-INF folder? I would like some explanation as well on this if possible.
Thanks,
Ashley

A: You are right, the properties files do exist in the src/main/resources
you can access them as following
<util:properties id="countryOptions" location="classpath:countries.properties" />

Or using the annotations
@Value( "${property.needed}" )
private String property;


text:
Q: probability based on past successful experience We have tried 2 methods to solve a problem previously.
We have tried Method#1 100 times and it has been successful 70 times and for Method#2, we have tried it 10 times and 6 times it has been successful.
Now I want to know if I want to decide which method to use for the next experiment, which method has the higher possibility of success.

A: If we assume that methods always have the same probability of success $p_1$ and $p_2$ respectively, then we can make some estimate of these (unknown to us) parameters based on empirical evidence. Maximum likelihood estimate will give us $p_1 = 0.7, \, p_2 = 0.6$ and that will be that.
Now comes the tricky part (spoiler: answer for your question as it is won't change). Suppose that second method had $8/10$ success rate. The probability of this happening with $p_2 = 2/3$ would be $45*2^8/3^{10} \approx 0.2$. In other words, while on average second method would be better, there would be a significant chance of it being worse.
If all you care about is having your success rate as high as possible, simply choosing method with best success rate will give you what you want. However, if you wish to, say, get average success rate $0.75$ with least "chance of surprise", actual answer in this altered example would be a mixed strategy (using first strategy with probability $r_1$ and second with probability $r_2$). The higher you set your intended average rate, the greater becomes the dispersion (probability of getting significantly higher or lower than average).
Alternatively, you can try to get the best possible average result for the given deviation (in general case, you will get a mixed strategy as well). Exact means of computing the best mix in these cases are studied in modern portfolio theory.


text:
Q: PowerBI: two filtered location sets in one map I have two sets of identical data that I filter differently. One shows sales by location in test locations and the other in control locations. Is there a way to append the results in a table with a "Test/Control" flag based on the first set of slicers so that I can show all the locations color coded by the flag?

A: You have two options to achieve this. In the Model (DAX) you can create a calculated Table, and use the UNION function to append the two sets of rows together.
https://dax.guide/union/
However UNION is quite fussy - the two parameter tables must have the same set of columns.  Sometimes you can overcome small differences by adding other functions, but complex transforms are harder and you cant debug.
For complex requirements, you can use the Power Query Editor - it has an Append Query button on the Home Ribbon. Each query you feed in can have complex transformations.


text:
Q: Facebook AuthHash storage in rails I am trying to authenticate using facebook in my application, This is done using omniauth and devise gems. The problem is that when the AuthHash returns, it has too much data which I want to use in my application. I don't want to store it in my db, since it is a single time usage data. But need to store it temporarily somewhere, but clearly session is too small for such a huge data.
Can I store convert the auth hash to JSON and store it db and then read from it using JSON.parse? Is it a good practice?
Thanks in advance.

A: This is my approach to the issue, which might or might not suit you:
I execute the "to_json" method for the data retrieved, in order to make the object a "JSON" one:
logger.info(request.env["omniauth.auth"].to_json)

Then I aim to store it in a "metadata" table temporarily, then process them later with a worker and remove them.


text:
Q: Why is my screen blank in A-Frame? I opened up an A-Frame scene both using the Hello World Codepen and the boilerplate, but I just get a blank white screen in Chrome.

A: I found the solution here.It works for me.
Details below:
Chrome
First, enable hardware acceleration:
Go to chrome://settings
Click the + Show advanced settings button
In the System section, ensure the Use hardware acceleration when available checkbox is checked (you'll need to relaunch Chrome for any changes to take effect)
Then enable WebGL:
Go to chrome://flags
Ensure that Disable WebGL is not activated (you'll need to relaunch Chrome for any changes to take effect)
Then inspect the status of WebGL:
Go to chrome://gpu
Inspect the WebGL item in the Graphics Feature Status list. The status will be one of the following:
Hardware accelerated — WebGL is enabled and hardware-accelerated (running on the graphics card).
Software only, hardware acceleration unavailable — WebGL is enabled, but running in software. See here for more info: "For software rendering of WebGL, Chrome uses SwiftShader, a software GL rasterizer."
Unavailable — WebGL is not available in hardware or software.
If the status is not "Hardware accelerated", then the Problems Detected list (below the the Graphics Feature Status list) may explain why hardware acceleration is unavailable.
If your graphics card/drivers are blacklisted, you can override the blacklist. Warning: this is not recommended! (see blacklists note below). To override the blacklist:
Go to chrome://flags
Activate the Override software rendering list setting (you'll need to relaunch Chrome for any changes to take effect)
For more information, see: Chrome Help: WebGL and 3D graphics.
Firefox
First, enable WebGL:
Go to about:config
Search for webgl.disabled
Ensure that its value is false (any changes take effect immediately without relaunching Firefox)
Then inspect the status of WebGL:
Go to about:support
Inspect the WebGL Renderer row in the Graphics table:
If the status contains a graphics card manufacturer, model and driver (eg: "NVIDIA Corporation -- NVIDIA GeForce GT 650M OpenGL Engine"), then WebGL is enabled.
If the status is something like "Blocked for your graphics card because of unresolved driver issues" or "Blocked for your graphics driver version", then your graphics card/driver is blacklisted.
If your graphics card/drivers are blacklisted, you can override the blacklist. Warning: this is not recommended! (see blacklists note below). To override the blacklist:
Go to about:config
Search for webgl.force-enabled
Set it to true
(Like Chrome, Firefox has a Use hardware acceleration when available checkbox, in Preferences > Advanced > General > Browsing. However, unlike Chrome, Firefox does not require this checkbox to be checked for WebGL to work.)
Safari
Go to Safari's Preferences
Select the Advanced tab
Ensure that the Show Develop menu in menu bar checkbox is checked
In Safari's Develop menu, ensure that Enable WebGL is checked

A: Check to see if WebGL and hardware acceleration is enabled in your browser and check that your GPU is not on your system's blacklist.


text:
Q: How can I test several exceptions within one test using an ExpectedException Rule? Got a question regarding the usage of junit's ExpectedException rule:
As suggested here: junit ExpectedException Rule
starting from junit 4.7 one can test exceptions like this (which is much better then the @Test(expected=Exception.class)):
@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();
 exception.expect(Exception.class);
 foo.doStuff();
}

Now I needed to test several exceptions in one test method and got a green bar after running the following test and thus thought every test passed.
@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();

 exception.expect(IndexOutOfBoundsException.class);
 foo.doStuff();

 //this is not tested anymore and if the first passes everything looks fine
 exception.expect(NullPointerException.class);
 foo.doStuff(null);

 exception.expect(MyOwnException.class);
 foo.doStuff(null,"");

 exception.expect(DomainException.class);
 foo.doOtherStuff();
}

However after a while I realized that the testmethod is quit after the first check passes. This is ambiguous to say the least. In junit 3 this was easily possible...
So here is my question:
How can I test several exceptions within one test using an ExpectedException Rule?

A: Short answer: You can't.
If the first call - to foo.doStuff() - throws an exception, you will never reach foo.doStuff(null). You'll have to split your test up into several (and for this trivial case I'd propose going back to the simple notation, without ExpectedException):
private Foo foo;

@Before
public void setUp() {
 foo = new Foo();
}

@Test(expected = IndexOutOfBoundsException.class)
public void noArgsShouldFail() {
 foo.doStuff();
}

@Test(expected = NullPointerException.class)
public void nullArgShouldFail() {
 foo.doStuff(null);
}

@Test(expected = MyOwnException.class)
public void nullAndEmptyStringShouldFail() {
 foo.doStuff(null,"");
}

@Test(expected = DomainException.class)
public void doOtherStuffShouldFail() {
 foo.doOtherStuff();
}

If you really want one and only one test, you can fail if no error is thrown, and catch the things you expect:
@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();

 try {
    foo.doStuff();
    fail("doStuff() should not have succeeded");
 } catch (IndexOutOfBoundsException expected) {
    // This is what we want.
 }
 try {
    foo.doStuff(null);
    fail("doStuff(null) should not have succeeded");
 } catch (NullPointerException expected) {
    // This is what we want.
 }
 // etc for other failure modes
}

This gets quite messy pretty fast, though, and if the first expectation fails, you won't see if anything else fails as well, which can be annoying when troubleshooting.