Don't be Greedier

Question: Consider the following two-player game, Don't be Greedier, that involves players taking alternate turns removing pebbles from one pile of pebbles, subject to the following rules:
(1) The player to remove the last pebble or pebbles from the pile wins the game.
(2) On the very first move of the game, the player to play is not allowed to remove all the pebbles and win immediately (that would be greedy).
(3) After the first move, the number of pebbles removed can't be more than the number of pebbles removed in the turn immediately prior (that would be greedier). That is, the sequence of numbers of pebbles removed on each turn is a monotonically non increasing sequence.
Starting with a pile of 12 pebbles, which player would win a game of Don't be Greedier, assuming optimal play?
Comment: Rollback to previous version. Defacement of one's own question. in particular one with upvoted answers provided is not an acceptable behavior of this site. If there is a good reason to delete this question, please contact the moderators.
Comment: This is a slight variation on the game of NIM (with misere play instead of normal play). To echo Eric, what did you try?
Comment: If a player removes one pebble when there is an odd number of pebbles remaining, that player wins.
Comment: With best play the game you described is a **draw**. It would be a more interesting game if you added a rule that **at least one** pebble must be removed at each turn.
Answer: The first player can win. Here is a winning strategy (someone else may have a more elegant explanation).
Winning Strategy
Say the person who goes first is called $F$, and the person who goes last is called $L$.
If a person removes one pebble from an odd pile, that person wins the corresponding sequence of removing one pebble at a time. This makes it easy to manufacture a winning strategy.
$F$ first removes four pebbles to reduce the stack to eight.
$L$ has two options that do not obviously lose: remove two or remove four pebbles.
If $L$ removes two pebbles, there are six left. $F$ obviously does not want to remove one pebble, because then $L$ can remove one pebble from an odd pile and win. So $F$ and $L$ both remove two pebbles at a time, and we find that $F$ wins.
If $L$ removes four pebbles, there are four pebbles left. $F$ can remove the remaining four and win.
Thus, this strategy wins $F$ the game regardless of the actions of $L$. In other words, the person who chooses first can win.
Proof: this is the only winning strategy for $F$
The strategy above is the strategy of removing four pebbles at the start. Every other part of the strategy is in response to the moves of $L$.
If $F$ removes six or more, $F$ clearly loses.
If $F$ removes an odd number, he loses when $L$ removes one.
If $F$ removes two, the corresponding move sequence of removing two pebbles at a time causes $F$ to lose.
The only other option is for $F$ to remove four pebbles at the start, which is the winning strategy presented above.
Answer: One can show that the second player to play wins if and only if the starting number of stones is exactly a power of two.
Proof:  Let $(n, k)$ denote the position where $n$ stones remain and $k$ stones are the maximum allowed to be taken.  If $k\geq n$ the next player to play wins.  Otherwise, we show that the first player wins if and only if $k$ is at least equal to the place value of the least significant $1$ when $n$ is written in binary.  (This is $1$ if $n$ is odd, $2$ if $n$ is even and not divisible by $4$, $4$ if $n$ is divisible by $4$ and not $8$, and so on.)
The proof is by induction on $n$.  Suppose this is shown for all values smaller than $n$, that $m$ is this place value, and that $k\geq m$.  Then, the first player may remove $m$ stones, leaving us in the position $(n-m, m)$.  The least significant $1$ of $n-m$ is in a higher place than that of $n$ since the binary expansion of $n-m$ is just that of $n$ with the least significant $1$ removed, so $m$ is less than the place value of the least significant $1$ in $n-m$.  By induction the next player to play cannot win, so the player who just moved will win.
On the other hand, suppose that $k<m$.  Then no matter how many stones the first player removes, he will introduce a $1$ with a place value less than the number of stones he removes; that is, he moves to $(n-x, x)$ where $x$ is greater than the place value of the least significant $1$ in the binary expansion of $n-x$.  By induction the second player will win.
Since the original position of the game is $(n, n-1)$ the second player wins if and only if the least significant $1$ in $n$ has place value at least $n$; that is, if $n$ is a power of two.  In particular, if $n=12$ then the first player wins.
Answer: The first player can win if he/she removes $4$.
The second player has to remove $4$ or $2$ because if he/she removes $1$ or $3$, the first player will win by removing only $1$s.
However, if the second player removes $4$, the first player will win by removing $4$ again.
On the other hand, if the second player removes $2$, the first player removes $2$. Then, the first player has to remove $2$ again otherwise the first player will win by removing $1$s. However, in this case, the first player will win by removing $2$ again.
Hence, the first player can win in this strategy.
By the way, if the first player removes $n\not=4$, then the second player can win.
If the first player removes an odd number $n$, then the second player will win by removing $1$s only.
If the first player removes $2$, the second player will win by removing $2$s untill the first player removes $1$. If the firt player takes $1$, then the second player removes $1$s only.
If the first player removes an even number $n\ge 6$, then the second player will win by removing $12-n$.
Answer: If the 1st player removes n pebbles with $n\geq6$ or $n=1$ then 2nd player wins. Assume that 1st player removes n pebbles with $n\in \{ 2,3,4,5\}$. If $n=3 or 5$ then 2nd player removes one pebbles and thus wins in the end since after the 1st player plays there is an odd number of pebbles remaining. If $n=2$ and 2nd player removes 1 pebble during first round then 1st player wins. If 2nd player removes 2 pebbles during the first round then he wins in the end.
If $n=4$ then the 1st player wins and its easy to see all possible cases.
In general if a player reaches the point to remove pebbles from an odd number of them he removes one and wins in the end.
Answer: You can make a minimax table, starting with 1, should only take a couple minutes.  For row $R$ and column $C$, does the player win if there are $R$ pebbles left and he is allowed to draw up to $C$:
$$\begin{array} {c|c|c|c|c|c|}
\text{Pebbles \ Draws} & 1 & 2 & 3 & 4 & 5 & 6 \\ \hline
1 & W \\ \hline
2 & L & W \\ \hline
3 & W & W & W \\ \hline
4 & L & L & L & W \\ \hline
\end{array}\\
\vdots \\
\begin{array} {c|c|c|}
& ... & 12 \\ \hline
12 & ... & ? \\ \hline
\end{array}\\
$$

Don't be Greedier


React routes are not working in facebook's create-react-app build

Question: I am using react router to define the routes. And i am using create-react-app for developments. My question is if i type the url for subpages in address bar and try to visit it works in development build but not in production build.
I am using a a simple express server for hosting the production build
<code>var express = require('express'),
  app = express(),
  http = require('http'),
  httpServer = http.Server(app);

app.use(express.static(__dirname + '/build'));

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});
app.listen(3001);
</code>
Comment: Which URL? The main one - yourdomain.com/ or a sub-page - yourdomain.com/some/page/123?
Comment: @HoriaComan sub-pages
Answer: You must configure your webserver to serve the same page for all the routes you've defined, or implement server-side rendering in React. The development webserver is probably configured as such, but the production one (Apache? Nginx? something else?) isn't. This question might help.
The reason why this is, is that React is used in building single page applications. You have a single traditional webpage, which loads some scripts - the output of your build process most likely, and then those scripts take care of everything else. This includes generating new DOM, making requests to the "server" for data, and even faking a multi-page app behaviour by manipulating the URL when views change. This last bit is what react-router does.
However, web servers are usually oblivious to these things. They know how to serve URLs. And when you request yourdomain.com/ they'll serve that main page, but when you request yourdomain.com/some/page/123 they won't know what to serve, unless specially configured. And one configuration is to also return the contents of the main page for these other URLs. React-router will pick up the URL and use the proper components, so everything will look OK>
Comment: To be more specific, the author would want to change `/` to `/*` in the handler that serves `index.html`.


How to get google UserID by email or GoogleDrive permissionId

Question: Google Drive returns:

user email
permission Id

https://developers.google.com/drive/api/v3/reference/permissions
Google Drive Activity API v2 returns Google UserID, example:
personName: people/ACCOUNT_ID
https://developers.google.com/drive/activity/v2/reference/rest/v2/activity/user#KnownUser
How can I match user email OR userPermissionId against 'people/ACCOUNT_ID' ?
Is there a way I can get ACCOUNT_ID having user email/permissionId or vice versa?
Comment: By `people/ACCOUNT_ID` doy you mean the `resourceName` returned by the [People API](https://developers.google.com/people/api/rest/v1/people/listDirectoryPeople?)?
Comment: Yep, that's correct.
Answer: people.get request will give you nothing if resourceName not equal to people/me or person not in your contact list.
Answer: Provided you have the personName from the Drive Activity API:

This name corresponds to the People API resourceName

Make a people.get request specifying the resourceName of form people/xxxxx and set personFields to emailAddresses and fields to emailAddresses/value

The Drive API v3 method Permissions: list will return you all existing permission ids and matching emailAddresses for a specified file

There is no way to filter Permissions: list results directly by emailAddresses, so you would need to implement a programmatic functionality to compare all permissions for a file against a certain user name
Comment: I see two workarounds for now:

1. Use `people.get` and request `photos`, you can use this API without Oauth (i.e. request public info). Then match the `photo.url` from the response with the photo url returned by Drive API.

2. Match the [Drive.Changes.list](https://developers.google.com/drive/api/v3/reference/changes/list) timestamp with Drive Activity timestamps. If `Activity.timestamp` is **almost** the same as the `Drive.Change.timestamp` then the `lastModifyingUser` is probably the `Person`. By 'almost' I mean a very short interval (up to a second).
Comment: as mentioned by @PlugHead, when you request `people.get`, you'll NOT get the email address if the person is not in your contact list.
Comment: FYI, if you add `emailAddresses/value` in the `fields`, I get an empty result. Removing `fields` works as expected.
Comment: I've created an issue that was accepted: (https://issuetracker.google.com/issues/130103879)


JAVASCRIPT - API Star Wars -Promise return

Question: meu problema é que eu não consigo retornar o results['name'] do request da api. Quando clico no botão ele me retorna o response.data com a seguinte resposta

['Object, Object'] e quando eu seto data.results me retorna o erro :
  scripts.js:15 Uncaught (in promise) TypeError: Cannot read property
  'name' of undefined
      at scripts.js:15

A ideia é : assim que clicar no botão, me retornar um planeta aleatório.
Se alguém puder ajudar eu agradeço.
let button = document.querySelector('#botao');
let name   = document.querySelector('#Name');

function getPlanet() {

    let randomNumber = Math.floor(( Math.random() * 88 ) + 1 )
    let apiUrl = 'https://swapi.co/api/planets/' + randomNumber

        // integrando API para adicionar a função getPlanet;
    axios.get  (apiUrl).then(( async function ( response ) {
        console.log(response)
      updateInfo ( await response.data.results['name'])
    } ))
}
function updateInfo(data) {
    name.innerText = data.results
}
        // Evento Click;
button.addEventListener('click', getPlanet);

Answer: Sua forma de usar a requisição assincrona está meio errada tente assim, outras observações, depois de name, não tem nenhum array results dentro do retorno da api
veja
{ name: 'Saleucami',
  rotation_period: '26',
  orbital_period: '392',
  diameter: '14920',
  climate: 'hot',
  gravity: 'unknown',
  terrain: 'caves, desert, mountains, volcanoes',
  surface_water: 'unknown',
  population: '1400000000',
  residents: [],
  films: [ 'https://swapi.co/api/films/6/' ],
  created: '2014-12-10T13:47:46.874000Z',
  edited: '2014-12-20T20:58:18.450000Z',
  url: 'https://swapi.co/api/planets/19/' }

Sendo assim não da para fazer response.data.results['name'] e dentro de updateInfo, você não tem como acesssar results também.
let button = document.querySelector('#botao');
let name   = document.querySelector('#Name');

async function getPlanet() {
    try{
       let randomNumber = Math.floor(( Math.random() * 88 ) + 1 )
       let apiUrl = 'https://swapi.co/api/planets/' + randomNumber

        // integrando API para adicionar a função getPlanet;
       const response = await axios.ge(apiUrl)
       updateInfo(response.data.name)
    }
    catch(error => console.log(error))
}
function updateInfo(name) {
    name.innerText = name
}
        // Evento Click;
button.addEventListener('click', getPlanet);


Q-Range - the most mysterious parameter of quantization in Logic Pro X?

Question: I'm trying to wrap my head around quantization fine-tuning. The one parameter that I doesnt seem to fully understand (for now :P) is Q-Range. I made some research on the web and some people are telling that it's kind of filter:

positive values quantize only inside the range
negative values quantize only outside the area

I made a few experiments and I can say that it's not true in 100% situations. Does anybody know how does this parameter really affect the quantized material?
I found this as well (here's the link), and it seems to be a real thing, but do I really need to spend time analyzing it thoroughly or is there an easier method to understand it?
Answer: I'm not sure if this helps, but here's what apple says on their page:
<code>"Q-Range: Q-Range is ideal for recordings that already have the right
groove but are too hurried or laid back in places. It lets you retain
the original feel, but positions the rhythmic center precisely in the
groove. A value of 0 means that every note or transient marker is
quantized. Negative Q-Range values move only notes or transient markers
that fall outside the set range to ideal quantization grid positions,
while those closer to an ideal position are not quantized. In this
case, the most poorly played notes or transient markers—those outside
the range—are moved to perfect timing positions on the quantization
grid (or closer to these positions, depending on the Q-Strength
setting).

Tip:   To obtain the best Q-Range results, use a low, even Quantize
value, such as 1/4 note. Set the Q-Range parameter to compensate for
the maximum error in the recording."
</code>


HTTP GET data from function in script in head not available in body after calling function

Question: I have a script in HTML page head that declares a function to make a get requests for JSON data and passes it to element's innerHTML.
function called on page load.
Script in head correctly gets JSON data and populates elements innerHTML.
I would like to cross-fade loop between the 2 bits of JSON data.
Script in body tries to get element's innerHTML and create array to use as input to cross fade loop.
Element's innerHTML variable comes back empty.
The cross-fade loop script works if strings are declared in array.
Fiddle here
How can I get the JSON values into the text cycle?

£ GBP

Answer: Resolved with setInterval to delay pulling HTML elements before they had been updated:
var intervalID = window.setInterval(updateText, 1500);
function updateText() {
    var usd = document.getElementById("price").innerHTML
    var gbp = document.getElementById("priceGbp").innerHTML
    words = [usd, gbp]
    }

var i = 0;
var text = "BTC";
    function _getChangedText() {
          i = (i + 1) % words.length;
          return text.replace(/BTC/, words[i]);
        }
    function _changeText() {
          var txt = _getChangedText();
            var d = document.getElementById("changer")
            d.className = "fadeOut";
            setTimeout(function(){
             d.className = "";
            document.getElementById("changer").innerHTML = txt;
        }, 800);
    }setInterval("_changeText()", 3000)


C++ force implementation of method in child class but with a different signature

Question: Is there a way to force implementation of a method in a child class where the implementation will have a different signature for each derived class?
I know I can do this, using pure virtual:
class Base {
  public:
   virtual void getValue(string& s) = 0;
}

class Derived : public Base {
  public:
   void getValue(string& s);
}

Above, pure virtual getValue in the base class forces the derived class to implement getValue.  But what I really want to do is something like this:  Force each derived class to implement getValue() but each with a different signature:
class Base {
  public:
   void getValue() = 0;
}

class Derived_A : public Base {
  public:
   void getValue(string& s);
}

class Derived_B : public Base {
  public:
   void getValue(int *j);
}

The problem with the above is that, due to name mangling, each signature is effectively a different function, and thus Derived_A and Derived_B inherit getValue() = 0 and the compiler thinks that they also are abstract.
I've been playing around with some different ways to do this, but it appears to me there is no way to do it.  I'm thinking I should simply not declare getValue in the Base class and then just make sure each derived class implements their version of it.
Comment: Have a look at templates, mixins and the CRTP, these would open a whole world of possibilities beyond dynamic polymorphism. Something like `void getValue() = 0;` absolutely makes zero sense BTW.
Comment: @ R Sahu- thanks for fixing my typos!
Comment: @πάντα ῥεῖ -- thanks.  reading up on CRTP now.  Looks like that may be just what I needed in this case.
Comment: Re: "I should simply not declare getValue in the Base class" -- maybe. You're talking here about writing code; the underlying problem is one of design. What is it that you're trying to do? Why do you need different signatures in the derived classes, and what connection, if any, do those functions have to the one declared in the base class?
Comment: @DanielGoldfarb imagine this possible how would you use this functionality, have you though about it?
Comment: And no CRTP will not solve  your problem.
Comment: This is an XY problem. "In order to do X I need Y". However, it is undoubtedly the case that X is not the right thing to be doing. What, logically are you trying to achieve? In english?
Answer: If use of CRTP would work for you, you can use:
#include <string>

template <typename TypeSelector>
class Base {
  public:
     using type = typename TypeSelector::type;
     virtual void getValue(type t) = 0;
};

struct TypeSelector_A {
   using type = std::string&;
};

class Derived_A : public Base<TypeSelector_A> {
   public:
      void getValue(std::string& s) { /* Add real implementation */ }
};

struct TypeSelector_B {
   using type = int*;
};

class Derived_B : public Base<TypeSelector_B> {
   public:
      void getValue(int* j) { /* Add real implementation */ }
};

int main()
{
   Derived_A a;
   Derived_B b;
}

Comment: Why would you need inheritance and virtual function in this case when it cannot be really used?
Comment: @Slava, That questions CRTP as a fundamental, viable, concept.
Comment: I do not think so, I think your example is abuse of CRTP.
Comment: Why use an intermediate selector class? Why not simply use `template
class Base {
  public:
     virtual void getValue(type t) = 0;
};`
Comment: @Slava, it will be if `Base` does not have anything else in it. If  `Base` has additional code that uses `getValue`, then it is a legitimate use of CRTP.
Comment: @vdavid so CRTP concept can be brought here and for all doubts RSahu can task you "are you questioning fundamental concept?"
Comment: @vdavid, that's a possibility too.
Answer:
But what I really want to do is something like this: Force each derived class to implement getValue() but each with a different signature

The whole point of having virtual function (abstract or not) is that you can use it with pointer or reference to the base class which means you would use signature of the function from the base class. With that having what you want is completely useless. What you want can be implemented by returning std::variant or std::any with every virtual function in tree so keeping signature the same.
You should think how would you use such concept if it would be possible. If you think somethink like this:
void foo( Base *b ) {
    if( auto *d = dynamic_cast<Derived_A *>( b ) ) {
       std::string str;
       d->getValue( str );
       ...
    }
    if( auto *d = dynamic_cast<Derived_B *>( b ) ) {
       int i = 0;
       d->getValue( &i );
       ...
    }
}

then getValue() does not need to be virtual, you only need vritual destrictor in Base. But this is considered bad design.


"GetLatest" with Powershell doesn't download files on new TFS workspace

Question: I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.
I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.
Can anyone see what I'm doing wrong?
$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = @(
    @("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
    @("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)

Write-Host "Operations:"

foreach ($projectAndWs in $projectsAndWorkspaces)
{
    if (-not(Test-Path $projectAndWs[1]))
    {
        New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
    }

    $tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
    $recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
    $itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
    $fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
    $getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
    Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}

Write-Host "Finished"

Comment: The `$tfsServer = "http://tfsserver:8080/tfs"` should be `$tfsServer = "http://tfsserver:8080/tfs/nameOfACollection"`
Comment: If you look in source code explorer what does it show about whether you have the latest? TFS-VC tracks on the server what versions of what files are in a workspace. If you manually delete files it does not know and will not download them. You might need to force a download to get everything.
Comment: @Richard I'm creating a brand new workspace though... surely it shouldn't have any files when first created?
Comment: Bang goes that theory!
Comment: That's the one! Thanks mate, change this to an answer and I'll mark it as the solution
Comment: @GiulioVian please post your comment as the answer.
Answer: The $tfsServer = "http://tfsserver:8080/tfs" should be $tfsServer = "http://tfsserver:8080/tfs/nameOfACollection"
Answer: The "$/Client1/Project1" string smells. I would add a backtick before the dollar sign so it is not read as a variable or use single quotes.
Backtick

"`$/Client1/Project1"

Single quote

'$/Client1/Project1'

Comment: Neither of these changes make any difference unfortunately


How to change the pagination of related entities displayed on a taxonomy term page?

Question: On a default taxonomy term page, related contents are automatically paginated by 10.
Let's say those related contents are always nodes and we always display the default teaser view mode.
How can I change the number of node teaser by page without using a module or a view?
Answer: The taxonomy module uses the default_nodes_main variable to decide how many to show per page (this happens around line 55 of taxonomy.pages.inc in case you're interested).
Usually you would implement a custom module and provide a form to override that variable for your users. But you don't have to do that, if you just want to set the variable once and be done with it use one of the following methods instead:

Use Drush (drush vset default_nodes_main 20)
Add a PHP snippet somewhere that will be run in your site (you only need to do it once)
variable_set('default_nodes_main', 20);

Use the Devel variable editor


Admin language module

Question: I'm currently building websites with the Administration Language Module. For the first time, the admin language is different than the default language but it doesn't work. For example, my default language is English and I'll set Spanish for the admin menu. My admin menu (and all administration dashboard) is partially translate.
As you can see, sometime item's menu are in English and in Spanish.

However, "People" is correctly translate in Translate Admin.

Can you help me?
Answer:
Visit admin/config/regional/language and select an admin language
Visit admin/config/regional/language/admin_language and enable Use administration language for the core toolbar
Comment: I trying but doesn't work. I am still searching in different patch on drupal.org.
Thanks for your help.

Admin language module


Using custom test helpers in your test cases

Question: I'm trying to write test cases for my custom module and in order to speed things along for current and future testing I defined a garbage class that can spit out random data. However the testing module cannot seem to locate my Garbage class. After some debugging I realize that Drupal looks in the registry table to find the class and while my class is defined in the default registry table, simpletest creates it's own custom registry table to run tests which doesn't contain my class or it's location. Is there any way around this or some way to force simpletest to make an exact duplicate of the registry table?
Notes:

The garbage class is located in a separate file (Garbage.php)
Yes I do have 'files[] = Garbage.php' in my .info file.
While I could just move the garbage functions into test case itself, I may need to reuse it for other tests later on so having it in a separate class is ideal.

Garbage class
<code>    class Garbage {
        public static function getGarbageString(int $i = 1) {
            $return = array();
            for ($j = 0; $j < $i; $j++) {
                $return[$j] = self::_getRandomString();
            }

            return $i == 1 ? $return[0] : $return;
        }

        private static function _getRandomChar() {
            return chr(mt_rand(33,126));
        }

        private static function _getRandomString() {
            $length = mt_rand(1, 255);
            $return = '';
            for ($i = 0; $i < $length; $i++) {
                $return .= self::_getRandomChar();
            }

            return $return;
        }
    }
</code>
Located in .module file
<code>    function getRecord($recordName) {
        return $records[$recordName];
    }
</code>
Located in RecordTestCases which extends DrupalWebTestCase
<code>    public function testGetRecord() {
        $badData = Garbage::getGarbageString();
        $this->assertNull(getRecord($badData), 'Testing get record with bad data');
    }
</code>
Answer: If getRecord() and testGetRecord() are methods of the Garbage class, then you have a misplaced } bracket.
Alternately, testGetRecord() will have no idea what to do with $this, since it's not part of a class definition. It would need to be a method of a subclass of DrupalUnitTest, or DrupalWebTest. As-is, PHP will choke on it.
Comment: Sorry for not clarying, they're not in Garbage class. getRecord is in .module file and testGetRecord is in the test class.


Replace one of the segment with a wildcard in a simple way?

Question: I have this code in nginx config:
location ~ ^/assets/(static|dynamic)/(images|styles|scripts|fonts|videos|audios|var)/(.*) {
    alias /var/web/app1/assets/$1/$2/$3;
    autoindex off;
    expires 366d;
}

Now I want to replace the (images|styles|scripts|fonts|videos|audios|var) with a wildcard. And everything should continue to work as-is. That is, in that segment, there could be a directory with any name whatsoever.
Is there a simple way to do it in a simple way? Preferably without a regexp.
Comment: `location /assets/static/ { root /var/web/app1; ... } location /assets/dynamic/ { root /var/web/app1; ... }` ?
Comment: @jhnc I don't understand
Comment: Rejected suggested revision: `nginxconf` is not supported for syntax highlighting: https://meta.stackexchange.com/a/184109/168269
Answer: If you want to replace this part (images|styles|scripts|fonts|videos|audios|var) with wildcard, you can just remove that part and only keep (.*) in location.
Like this:
location ~ ^/assets/(static|dynamic)/(.*)$ {
    alias /var/web/app1/assets/$1/$2;
    autoindex off;
    expires 366d;
}

Update:
Here is another approach, while keeping 4 segments, but using regex:
location ~ ^/assets/(static|dynamic)/([^/]+)/([^/]+)$ {
    alias /var/web/app1/assets/$1/$2/$3;
    autoindex off;
    expires 366d;
}

Comment: Probably the update still allows access to 3-segment (ie. files directly inside `static` or `dynamic`), as an attacker can just put: `/assets/static//protected.file`. You need something like `^/assets/(static|dynamic)/([^/]+)/([^/]+)$`
Comment: Two prefix locations suggested by @jhnc are better in terms of performance.
Comment: that's wrong because I want there to be 4 segments
Comment: @IvanShatsky yes, in terms of performance two separate locations will be a bit faster.
Comment: @Durimar I don't know if it's possible without using regex. but why do you need 4 segments?
Comment: The update (and the original question code) are actually 4 **or more** segments: `.*` can include multiple `/`


Similarities when adding a new point to a poset.

Question: I'm trying to solve the problem 7.3 of the book Notes on Set Theory written by Moschovakis.

Basically, I have to prove that for every poset $P$ we have
  $\mathrm{Succ}(P)=_o P+_o [0,1)$, were $P+_o [0,1)$ is obtained by
  placing disjoint copies of $P$ and $[0,1)$ side-by-side and
  $\mathrm{Succ}(P)$ is obtained by adding a new point to the elements
  of $P$.

So, to prove that I'm supposed to find an order preserving bijection $\pi$ (called similarity) between $\mathrm{Succ}(P)$ and $ P+_o [0,1)$. But it seems imposible to me to find a bijection, because if $P$ is finite, we'd have that the image of a point have to be an interval.
Am I wrong? In this case, could youu give me a bijection?
Maybe I've understood wrong some definitions?
Thank you!
Comment: What is $[0,1)$? If that's the order set $\{x:0\le x<1\}$ within the ordinal numbers or $\Bbb Z$, then it is indeed the single point $\{0\}$. Or is that the poset's $0,1$, i.e. the greatest and least elements of the poset? Those aren't always uniquely defined though.
Comment: Not that it makes any difference to this problem, but how do you add the extra point in $\text{Succ}(P)$? Do you make it non-comparable to all elements?
Comment: Maybe that's my problem Mario. I thought that $[a,b)=\{x\in \mathbb{R}\,:\, a \leq x < b\}$ but it's make more sense what do you say, that it's $\{0\}$. Thank you!
Answer: To confirm what Mario Carneiro suggested in the comments, at the beginning of Chapter $7$ you'll find that $[0,n)$ is defined to be $\{i\in\Bbb N:i<n\}$, so $[0,1)=\{0\}$. You should probably write your similarity in terms of the formal definitions of $\operatorname{Succ}(P)$ and $P+_oQ$.
$\operatorname{Succ}(P)$ is formally defined on p. $93$ as the poset whose field is $\operatorname{Field}(P)\cup\{t_P\}$, where $t_P=\mathbf{r}(\operatorname{Field}(P))$, and whose ordering is given by setting $x\le_{\operatorname{Succ}(P)}y$ iff
$$x\le_Py\lor[x\in P\land y=t_P]\lor x=y=t_P\;.$$
Thus, the new element is specifically added at the 'top' of $P$: it's bigger than every element of $P$.
$P+_oQ$ is formally defined at $\mathbf{7.37}$ to be the poset whose field is
$$\big(\{0\}\times\operatorname{Field}(P)\big)\cup\big(\{1\}\times\operatorname{Field}(Q)\big)$$
with the lexicographic order that makes $\langle i,x\rangle\le_{P+_oQ}\langle j,y\rangle$ iff
$$i<j\lor[i=j=0\land x\le_P y]\lor[i=j=1\land x\le_Qy]\;.$$
(There's a typo in my copy of the book, which has $U$ and $V$ instead of $P$ and $Q$ for the subscripts on the orders in the displayed line.) Note that although you didn't give mention it in your question, this definition does mean that every point of $P$ precedes every point of $Q$, so $P+_o[0,1)$ essentially also just adds a new element at the 'top' of $P$.
Comment: That's was my problem. I took by mistake the definition of chapter 2. So silly! Hahahaha
Answer: So, I think the exercise can be solve this way:
By definition we have
$$[0,1)=\{x\in \mathbb{N} \, : \, 0 \leq x < 1\}= \{0\}$$
Let $t_P$ be the unique point that satisfies  $t_P\in \mathrm{Succ(P)}$ and $t_P\notin P$, and let $\pi:{\mathrm{Succ}(P)}\longrightarrow{P+_o [0,1)}$ defined by $$\pi(p) = \left\{\begin{array}{ll} (1,0) & \text{if } p=t_P \\ (0,p) & \text{otherwise.} \end{array} \right.$$
This map is bijective, because $\pi(\pi^{-1}((a,b)))=(a,b)$ and $\pi^{-1}(\pi(c))=c$ for all $(a,b)\in P+_o [0,1)$, $c\in \mathrm{Succ}(P)$, where $\pi^{-1}$ is:
$$\pi^{-1}((a,b)) = \left\{\begin{array}{ll} b & \text{if } a=0 \\ t_p & \text{if } a=1  \end{array} \right.$$
Let's prove that it is order preserving. If $p_1\leq_{\mathrm{Succ}(P)}p_2$, we have three different cases:

If $p_1\leq_P p_2$, then  $$\pi(p_1)=(a_1,b_1)=(0, p_1)\leq_{P+_o [0,1)} (0, p_2)=(a_2,b_2)=\pi(p_2),$$ because $a_1=a_2=0$ and $b_1\leq_P b_2$.
If $x\in P p_2=t_p$, then $$\pi(p_1)=(a_1,b_1)=(0, p_1)\leq_{P+_o [0,1)} (1,0)=(a_2,b_2)=\pi(p_2),$$ because $a_1<a_2$.
If $p_1= p_2=t_p$, then $$\pi(p_1)=(a_1,b_1)=(1,0) \leq_{P+_o [0,1)}  (1,0)=(a_2,b_2)=\pi(p_2).$$

So,  $\pi$ is a similarity.


Closure of the curve $C = \{(x,y): y = e^x, x \in \mathbb{C}\}$ in the Zariski topology

Question: I have to find the closure, in the Zariski topology, of the curve $C = \{(x,y): y = e^x, x \in \mathbb{C}\}$.
I suppose the answer is $\mathbb{C}^2$ and I guess I have to use the Taylor expansion of the function $e^x$ or the implicit function theorem to prove it, but I have no idea.
Answer: Suppose that a polynomial $p(x, y)$ vanishes on $C$. Then $p$ has the property that for all $a$, $p(a, e^a) = 0$. Because $e$, and hence $e^2, e^3, \ldots$ are transcendental, we have that for each natural number, $p(n, y)$ is the zero polynomial in $y$. It follows that $p$ is the zero polynomial. (You could also argue directly from the algebraic independence of $x$ and $e^x$ over $\mathbb{C}$, which is much easier to prove than the transcendence of $e$.)
Comment: How could not I see that? Thank you.


MySQL: Select last from group, but with conditions

Question: I have the following table:
name     created_for created_on            status
jen      2012-05-27  2012-02-15 12:14:09    Y
joe      2012-10-01  2012-02-15 12:22:09    Y
bob      2012-10-01  2012-02-15 12:47:09    N
jim      2012-10-01  2012-02-24 12:47:09    N
jim      2012-10-01  2012-02-29 12:47:09    Y
sam      2012-10-01  2012-03-11 12:47:09    N
sam      2012-10-01  2012-03-15 12:47:09    C
sam      2012-10-01  2012-03-22 12:47:09    Y
tom      2012-10-01  2012-04-10 12:47:09    N
tom      2012-10-01  2012-04-11 12:47:09    N

What I want to return is the last row of name, created_on for each person that has a created_for date of 2012-10-01, but ONLY IF the status for that last entry is an N. So for the table above, I want to get back:
name     created_on
bob      2012-02-15 12:47:09
tom      2012-04-11 12:47:09

The status condition is what's throwing me. I can't seem to figure out where to place the "where status='N'" to get the right results.
Comment: What's the query you're currently using?
Answer: Try this:
 SELECT t1.*
 FROM
 (
    SELECT name, MAX(created_on) MaxDate
    FROM YourTableName
    GROUP BY name
  ) t1 INNER JOIN YourTableName t2  on t1.name    = t2.name
                                   AND t1.MaxDate = t2.created_on
 WHERE t2.created_for = '2012-10-01'
   AND t2.status = 'N'

Comment: That works for the subset of the table above but as soon as I add another row like: `bob 2012-10-04 2012-07-07 12:12:12 N` bob is no longer returned for 2012-10-01
@mahmoud-gamal
Comment: @Jim Thats because the record you added `bob 2012-10-04 2012-07-07 12:12:12 N` has the `created_for` field = `2012-10-04` not `2012-10-01` there for isn't returned because of the condition `WHERE t2.created_for = '2012-10-01'`
Comment: No, look again. It no longer returns bob FOR 2012-10-01. With the table subset I posted, it returns the 2 rows wanted. However, if I add that addition row for Bob with a later date, only 1 row is returned. The bob row for 2012-10-01 is no longer returned.
Answer: select t.*
from MyTable t
inner join (
    select name, max(created_on) max_created_on
    from MyTable
    where created_for = '2012-10-01'
    group by name
) tm on t.name = tm.name and t.created_on = tm.max_created_on
where t.status = 'N'

SQL Fiddle Example


ASP.NET Gridview with all records editable

Question: I thought this would be simple, but I sure am having a lot of trouble doing this:
The title of this question may be a bit misleading. I don't have to use a gridview. In fact, I know the GridView is probably not the way to go on this. I just didn't know how else to title it. But, for now just consider:
I have a very simple class called Student. It has 4 properties:
int ID
string FirstName
string LastName
string Email
I want to keep a generic collection of these in memory (session state):
List students;
Ok, now the problem:
I want the user to create as many of these Student objects as they want. For displaying these I just want a simple table of some kind with the 3 textboxes on each row. I would like every row to have textboxes insead of labels so that any record can be edited at anytime.
When the user is finished created their student objects, then they proceed on to do other things. But, I am just having trouble finding a way to display the records this way. Do I use the ListView(3.5), html table, gridview, repeater, etc.?
How would you do it?
Answer: I would be inclined to use the ListView personally for this, since you can insert Rows with it. Your LayoutTemplate would be a table with a
 in it. Your ItemTemplate would have your TextBox's  (and optional a save button per row. Then you could have an InsertItemTemplate if you need inserts as well.
Anywhere on the page you can add a button to Save all items by looping through the ListView.Item collection and calling ListView.Update(itemIndex, validate).
<asp:ListView runat="server" ID="lv" InsertItemPosition="LastItem" DataKeyNames="id">
<LayoutTemplate>
    <asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />

        First Name
        Last Name
        Email

    <asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
</LayoutTemplate>
<ItemTemplate>

        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' />
        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' />
        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' />
        <asp:LinkButton runat="server" CommandName="update" Text="Save" />

</ItemTemplate>
<InsertItemTemplate>

        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' />
        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' />
        <asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' />
        <asp:LinkButton runat="server" CommandName="insert" Text="Save" />

</InsertItemTemplate>
</asp:ListView>

protected void SaveAll(object sender, EventArgs e)
{
    lv.Items.ToList().ForEach(li => lv.UpdateItem(li.DataItemIndex, true)_;
}

Answer: Yes you could use a grid view to do this.
you could create a custom template for the columns so that they display in a textbox as opposed to a label. you can then capture the 'save' event an loop through the rows and update your data.
Answer: Yes, this is possible.  This is just a code sample for what Victor had posted.
            <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" DataKeyNames="PartNumber" GridLines="Horizontal"
                ForeColor="#333333" CellPadding="4" Width="800" PageSize="20" OnDataBound="gvPartDetails_DataBound" OnSelectedIndexChanged="gvPartDetails_SelectedIndexChanged" OnSorting="gvPartDetails_Sorting">
                <Columns>
                    <asp:TemplateField HeaderText="#">
                        <ItemTemplate>
                            <asp:Label ID="lblNumber" runat="server" Text='<%# Bind("Number") %>' ToolTip='<%# Bind("Description") %>'></asp:Label>
                        </ItemTemplate>
                        <HeaderStyle Wrap="False" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="LOC 1">
                        <ItemTemplate>
                            <asp:TextBox ID="txt_Qty1" AutoPostBack="false" runat="server" MaxLength="5" Width="50" Text='<%# Bind("Qty1") %>'></asp:TextBox>
                        </ItemTemplate>
                        <HeaderStyle Wrap="False" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="LOC 2">
                        <ItemTemplate>
                            <asp:TextBox ID="txt_Qty2" AutoPostBack="false" runat="server" MaxLength="5" Width="50" Text='<%# Bind("Qty2") %>'></asp:TextBox>
                        </ItemTemplate>
                        <HeaderStyle Wrap="False" />
                    </asp:TemplateField>
                </Columns>

                <EmptyDataTemplate>
                    No Details For This Such and Such.

                </EmptyDataTemplate>

                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <EditRowStyle BackColor="#999999" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <HeaderStyle BackColor="#284775" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
                <AlternatingRowStyle BackColor="Gainsboro" ForeColor="#284775" />
            </asp:GridView>

And then the code behind... this is very rough...
   private void ApplyChanges()
    {
        foreach (GridViewRow row in this.gvDetails.Rows)
        {
           //do something with cells and data objects
           //and then save add to list, save, etc.
        }
    }

EDIT
Above is where you will get your editing of the data.  You can work with DataTables, DataViews, DataSets, and as the other solution shows, you can bind your grid to a list of your object.  This should be determined based upon the data object model in your system and how the rows would be generated.
Comment: thanks for posting the sample code. I wasnt going to try to do so from my phone.
Answer: Gridview is going to be the easiest way to implement this. You could use an html table, but when the user wants to add more users you're going to have to do a lot more. Create a template for the gridview with your four properties (Id, FirstName, LastName, Email), and then just bind it from the session object like:
public void BindGrid()
{
  // assume students is the name of your GridView control
  students.DataSource = (List<Student>)Session["StudentList"];
  students.DataBind();
}


GCM app not installing to emulator when it's Run/debug

Question: so, I basically was following this tutorial step by step
http://developer.android.com/guide/google/gcm/demo.html
I made the server give me the "No devices registered!"
all I have to do is make the app launch, that is where my problem start.
log cat registers:
"Trace - error opening trace file: no such file or directory (2)
AndroidRunTime - Shutting Down VM
dalvikvm - threadid=1: thread exiting with uncaught exception (group=0x40a13300)
AndroidRunTime - FATAL EXCEPTION: main"

MANIFEST:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gcm.demo.app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
        android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission
        android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />
    <uses-permission
        android:name="com.google.android.c2dm.permission.RECEIVE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DemoActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.google.android.gcm.demo.app" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
    </application>

</manifest>

By the way, I imported the project to make sure that the problem is not from my lousy programming.
Answer: To run GCM on emulator you need to create google account on your emulator. HAve you create it?
The emulator shows only shows the message in Logcat on successful execution
Answer: Make sure it's Google API emulator. Also login with a gmail account in the emulator.
Answer: If you have followed all the guides in GCM demo app, then you can capture your uncaught exceptions with this:
import android.content.Context;
import android.os.Process;

public class ExceptionHandler implements UncaughtExceptionHandler{

    public ExceptionHandler() {
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

            // capture the exception information

        Process.killProcess(Process.myPid());
        System.exit(0);
    }

  }

And in your main activity :
@Override
public void onCreate(Bundle bundle) {

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
}


Similar book to All the Mathematics You Missed but at a graduate level that is of a reasonable size?

Question: All the Mathematics You Missed
That is, a book that covers the motivation and important ideas of various fields of mathematics at the graduate/professional level (Measure Theory, Functional Analysis, Representation Theory, Algebraic Topology, Stochastic Analysis, Harmonic Analysis, Number Theory etc.)? I know there's the Princeton companion, but it is a massive book and not exactly suitable for light reading while commuting say.
Thank you.
Comment: What's wrong with the Princeton companion? It's exactly what you're asking for. Get an electronic version if portability is an issue.
Comment: I don't have anything to read electronic books and I don't intend to buy one just to read one single book.
Answer: You might have a look at Zeidler: Quantum Field Theory I and see whether you like that. There are also two more volumes. In many parts of the books there a great explanations from a motivational point of view, for instance on cohomology.
Comment: It would be good training ... Think of a 24 kg kettlebell instead.
Comment: Professional trainers hate him! One weird trick to get that 6-packs!
Comment: If I carry 1000 pages around, I might as well carry the Princeton Companion, but thanks anyway.


Not asking for input

Question: I have this:
Scanner input = new Scanner ( System.in );
int selection = input.nextInt();
if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();
}

However, when it gets to Please enter a string, it doesnt ask for any input. It just goes to the rest of the program.
Comment: This is unrelated to your question but when performing console input like this you should use `print` instead of `println` so that what the user types in the console is after the colon (on the same line). `System.out.print("Please enter a string: ");`
Answer: The Scanner waits at nextInt() until the user has pressed enter.  When that happens, it consumes the digits but not the new line character(s) itself.  Thus, the next call to nextLine() returns immediately with an empty String as its result.
This should fix it:
int selection = input.nextInt();
input.nextLine();
if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();

But my preferred way is to always use nextLine and do the parsing separately:
String selectionStr = input.nextLine();

//consider catching a NumberFormatException here to handle erroneous input
int selection = Integer.parseInt(selectionStr);

if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();
   //...

Comment: +1 For suggesting to always use `nextLine` and parse what you want separately.
Answer: try:
input.nextLine();

after your nextInt();
Scanner input = new Scanner(System.in);
int selection = input.nextInt();
input.nextLine();
System.out.println(selection);
if (selection == 1) {
    System.out.println("Please enter a string: ");
    String code = input.nextLine();
}

Comment: Was this answer really necessary? You didn't even know the answer yourself until you read @Mark's answer.
Answer: simple & graphical input :
String str=JOptionPane.showInputDialog(null,"Message","Title",JOptionPane.QUESTION_MESSAGE);

Not asking for input


Can't use local .aar file inside the library module

Question: I have an aar of socialauth-android library added to my project. I've put it inside the flatDir directory as described here and it works just fine.
Now, I'm moving some of my code into the library module named commons, to reuse it in the another project. socialauth-android will be used entirely by library module, so I've moved it inside the project/commons/libs/ an rewritten my build.gradle files. From now on I can't build my project, because the following error arises:
Error:A problem occurred configuring project ':ScrollApplication'.
> Could not resolve all dependencies for configuration ':ScrollApplication:_developmentDebugCompile'.
   > Could not find :socialauth-android:.
     Searched in the following locations:
         http://dl.bintray.com/populov/maven//socialauth-android//socialauth-android-.pom
         http://dl.bintray.com/populov/maven//socialauth-android//socialauth-android-.aar
         https://oss.sonatype.org/content/repositories/snapshots//socialauth-android//socialauth-android-.pom
         https://oss.sonatype.org/content/repositories/snapshots//socialauth-android//socialauth-android-.aar
         https://repo1.maven.org/maven2//socialauth-android//socialauth-android-3.2.pom
         https://repo1.maven.org/maven2//socialauth-android//socialauth-android-3.2.aar
         file:/home/artem/Workspace/scrollandroid/libraries/socialauth-android-3.2.aar
         file:/home/artem/Workspace/scrollandroid/libraries/socialauth-android.aar
     Required by:
         scrollandroid:ScrollApplication:unspecified > scrollandroid:commons:unspecified

The error says that dependency resolver tries to find socialauth-android.aar inside the project/libraries folder which is the folder for all common libraries shared between modules of my project. But I've written in my project/commons/build.gradle file that the flatDir for the commons module is project/commons/libs! Moreover, all jar libraries contained inside the project/commons/libs/ are found during the  build w/o any issues.
What can be the source of this issue?
Following are my build.gradle files (some of its code, like dependencies declarations, is dropped for brevity):
project/settings.gradle:
include ':ScrollApplication', ':commons'

project/build.gradle:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0-rc1'
    }
}

project/commons/build.gradle:
apply plugin: 'com.android.library'

repositories {
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
    mavenCentral()

    flatDir {
        dirs "libs"
    }
}

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile(name:'socialauth-android', ext:'aar')
}

project/app/build.gradle:
apply plugin: 'com.android.application'

repositories {
    maven { url "http://dl.bintray.com/populov/maven" }
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }

    mavenCentral()

    flatDir {
        dirs "../libraries"
    }
}

configurations {
    apt
}

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 21
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile project(':commons')

    compile fileTree(dir: '../libraries', include: ['*.jar'])
}

Upd: project structure added
├── build.gradle
├── commons
│   ├── build.gradle
│   ├── libs
│   ├── proguard-rules.pro
│   └── src
│       ├── androidTest
│       │   └── java
│       └── main
│           ├── AndroidManifest.xml
│           ├── assets
│           ├── java
│           └── res
├── gradle
│   └── wrapper
├── libraries
│   ├── aws-android-sdk-18.104.22.168-core.jar
│   ├── aws-android-sdk-184.108.40.206-s3.jar
│   ├── libGoogleAnalyticsServices.jar
│   └── supertooltips-3.0.1.aar
├── scrollandroid-hg.iml
├── ScrollApplication
│   ├── build.gradle
│   ├── proguard.cfg
│   ├── ScrollApplication.iml
│   └── src
│       └── main
│           ├── AndroidManifest.xml
│           ├── assets
│           ├── java
│           └── res
├── settings.gradle
└── stacktrace.txt

Comment: Can you provide a listing of your directory structure?
Comment: @AndroidGuy yeah, sure, here it is. :)
Comment: Sorry to keep asking for more, but could you list all the files (and folders) in the "libraries" directory.
Comment: @AndroidGuy added it. if I need to add something else - just tell me. thank you. :)
Answer: It appears that the commons library is being built correctly (can you compile it separately to verify?) but the application is not.  Gradle has some special rules for handling transitive dependencies (dependences nested in other dependencies) which exists since commons depends on socialauth-android.
Try adding an extra directory to the "flatDir" attribute in "project/app/build.gradle"
flatDir {
    dirs "../libraries", "../commons/libs"
}

Comment: UP! someone found a cleaner why to do this?
Comment: That fixed the issue, thank you very much. The only issue left is that from now on 'app' module knows about some internals of 'commons' module, which seems a little bit dirty to me. Also, it seems strange that 'app' don't need to know about 'commons/libs' directory if all libraries contained in 'commons/libs' are jars, not aars. Nevertheless, thank you for your help, I'll read about transitive dependencies in the Gradle docs.
Comment: Another thing to try would be adding "{transitive=true}" to the compile dependency for common.  See http://www.gradle.org/docs/current/userguide/dependency_management.html#sub:configurations
Comment: Indeed working, thank you. Would be nice if the parent module would fetch the library directories of the submodule automatically to avoid those cross-module references...
Answer: Seems to be a known issue that has been there for long time. The way to include the .aar dependency now days is like referenced in this question:
Adding local .aar files to Gradle build using "flatDirs" is not working
By default the resulting artifact will not include the files in the .aar file, unless you create a gradle task that copy the .aar content into your desired artifact.
If you plan to publish your .aar library in a Maven repo, the resulting POM file will have your dependency version set as undefined. To change it, you will need to work with the Dependency Substitution methods from gradle in your project.


Bach BWV 812 Allemande: Fingering for this semiquaver passage over held note

Question: Bach BWV 812 Allemande : bar 3 - any suggested fingerings to play the descending D6 - A5 while holding G5 - starting from the 2nd beat
The suggested fingering with 4 on D6 suggests to shorten the full minim to switch the thumb from G5 to A5.
The edition is Henle.
Comment: Piano, harpsichord, or organ (or clavichord)?
Answer: Yes, that's definitely the idea. (You know, I've played this edition for 30 years and never noticed that the suggested fingering is technically impossible. But no one is going to miss the last beat of the upper g, particularly since the bass voice has another g.)
Comment: Also even if, it is not going to matter, as this is the last note of the phrase in the second voice.
Answer: TL;DR I would play the semiquaver D5 – A4 passage 1 - 4 - 3 - 2 by using my left-hand thumb on the minim G4, swapping in my right-hand thumb between the C# - B

I would play the minim (half-note) G4 with my left hand thumb. When the right hand reaches B4, the right-hand thumb can take over the G4 from the left hand. This allows G4 to be granted its full length. (I actually swap thumbs between the C#5 and the B4.)
This use of the thumb(s) allows the semiquavers D5 – A4 to be played 1 - 4 - 3 - 2.
It also requires a change in the left hand compared to the fingering given in the Henle. Rather than LH 1 on beat 3, I use finger 4. Once the RH thumb is swapped in on the G4, I can adjust my LH fingering to prepare for the upcoming descent (and ornament, if included).
The danger is that the left hand thumb will produce an accented G4, so care must be taken to keep the inner voice intact.
Here is the suggestion, notated:
Comment: I was about to upvote you until I found that Beat 3.0 of the left hand of the offending measure actually is __also__ assigned the thumb in the original sheet music.
Comment: @Dekkadeci You'll notice that i changed it to finger 4.
Comment: @Dekkadeci Just FYI, I've revised my answer to make explicit the additional fingering changes.
Answer: Shortening the G does work, but as an alternative you might want to try 3-2-4-3 on D-C#-B-A. 4 on the B is only slightly more awkward than on the D.
Answer: G5 is assigned the right-hand thumb twice in a row, implying that you should not shift your right-hand thumb from G5 to A5 and shorten the minim.
C♯6 is implied to be assigned to the right-hand middle finger, but assigning B5 the right-hand ring or middle finger both seem plausible. Assigning B5 the right-hand pointer finger is more likely to result in an awkward-sounding accent on Beat 3.75's A5 due to B5 probably needing to be slightly clipped (or going for an awkward right-hand middle finger crossover for A5).
Therefore, 4-3-4-3 and 4-3-3-2 for that D6-A5 both seem plausible.
Since Beat 4.0 of the right hand of that measure is assigned the pinky finger, 4-3-4-3 is actually the most plausible fingering of the two options.
Comment: Yeah I think all the reasons given [here](https://music.stackexchange.com/a/126139/13430) strongly reason why the minim can be shortened. Meanwhile the fact that the thumb has the g "twice in a row" really doesn't imply that you shouldn't be allowed to use it for something else in between. Indeed the awkwardness that you point out with all possible permutations keeping the thumb on g just underlines the intent of the published fingerings.
Comment: @sehe - I was taught in piano lessons that playing Baroque keyboard music in a detached style is de rigeur, so there actually should not be any awkwardness in practice with the best fingering that obeys the sheet music. I actually have a further edit for the most plausible remaining fingering.
Answer: I tried it out - I would play 3-2-3-2 on the D-C#-B-A (on the piano, and probably the harpsichord, but not the organ).  This naturally enforces a slurring of the notes that I find appropriate - contrary to some traditions, I find that most of Baroque and Classical era music is frequently played far too legato on the piano.  Keep in mind that, on the harpsichord which is probably the instrument Bach wrote these suites for (though he would've been fine with playing it on other keyboard instruments as well), fine gradations of loudness are not available and articulation is the primary means of expression.


Guitar Bone Picks

Question: I know this question may sound off-topic, but from what bones are bone picks made and how different are they from plastic, metal, wooden or rubber picks?
How difficult is it to make a bone pick and is there a minimal size beyond which the bone pick will
break or be inefficient?
I would like to make a bone pick for myself, yet not know where to start.
Answer: Generally, the majority of bone products are made from Cow bone, which is processed for use in musical instruments, jewelry carving and other crafting uses. Bone "blanks" can be purchased in a variety of sizes. It is also possible to clean and dry bones yourself for project work.
It is fairly easy to work with bone.
Bone can be cut with a fine toothed saw such as a hacksaw. It can be sanded and filed, and some artists use grinding stones and wheels on it. You have to be careful not to let the work get too hot as you can burn it. Finishing can be done with fine sanding and abrasive polish.
Although strong, bone can be brittle, so you wouldn't want to make the pick leading edge too thin. A steeper taper more like a "jazz" pick would likely be more resistant to chipping.
Ivory and Tortoise shell were common materials for plectrums (picks) before plastics.
You will get some tone differences from the different materials, and flexibility and wear rates differ.  Bone is hard and picks made from it don't have flexibility so are more like stone or glass picks.
To get started all you need is a saw, a rough file and some sandpaper, and a bone blank big enough for the size pick you want.
Comment: Last time I worked on a bone nut, I didn't feel too good after. Maybe wear a mask.
Comment: @Tim  good point.  In fact,  **always** wear a mask when sawing or sanding or grinding pretty much any material.
Comment: Slightly off topic: Bear in mind old ivory and tortoise shell (even 200 year-old antiques) are now basically illegal to even transfer ownership of in many (most) US States. Old instruments can get by this rule because there is a "percentage rule." (200 grams, with caveats)
Answer: Different bones (from a given animal) have different strengths.  For example, the human shoulder blade is extremely strong and difficult to break, whereas less dense bones such as those in the lower arm will fracture more easily.  OTOH, aside from the shock value, making your picks out of human vs. cow vs. kodiak bear bones won't matter much (tho' picks made from the jawbone of your mortal enemy would be excellent).  Bird skeletons are a poor choice, as their bones are not dense at all and will break very easily.
As Alphonso pointed out, very few bones have much in the way of flexibility.
Comment: What am I supposed to do, kill some human being and take their shoulder blade? I'm not in the mood to kill, just yet.
Comment: @SovereignSun you could always raid some tomb or sarcophagus.  Just don't wake a mummy.

Guitar Bone Picks


Evaluating performance of machine learning models

Question: I'm trying to predict when a location has enough wind to go sailing. I've built several models that look for correlations between different weather conditions and whether it ends up being windy X hours later. Ultimately, I want to produce something like "Based on current conditions, there is a 70% chance it will be windy 1 hour from now."
I have several models that consider different factors, so my challenge is figuring out which one to use.
In this particular location, I know it's windy 15% of the time (3 years of data). Therefore, a model that always predicts a 15% chance basically deserves an overall score of 0 -- because it's more or less a coin flip. On the other end, a model that always predicts 0% or 100% deserves a "perfect" score. But what about in between?
Is that the right way to compare models? How should I calculate an overall score for each model?
Thx in advance!
Comment: This question might be better suited to [Data Science.SE.com](http://datascience.stackexchange.com), since it's not really about statistics per se. Consider flagging it for migration if you don't get good answers here.
Answer: There are several different ways to evaluate the performance of predictive models. Depending on your context you may need more or less sophistication.
The simplest measure is the concept of accuracy = (correct predictions) / total predictions. For this measure, higher accuracy is better.
Although very simple, accuracy is subject to several problems in particular it does not differentiate a false positive (you say that is windy and in fact it is not) from a false negative (when you say that it is not windy and it is).
If false positives and false negatives have different costs (or benefits depending on how you want to put it) for your scenario, then accuracy is not good enough for you.
In such cases, you should start with what is called a ROC analysis which will essentially show how different classifiers trade off true positives with false positives. This will allow you to get a better understanding of the performance of your model.
While you are at it, you should also look up the concept of confusion table which is essentially a contingency table of the output of your classifier, that is essential to build all sorts of evaluation metrics for predictive models.
An introduction to some key concepts is provided in this MIT presentation Evaluating Predictive Models.
Hope this helps,
Comment: I up-voted and agree with everything. In this case where it appears that there is a desire for risk assessment rather than classification I might emphasize a well calibrated model with Brier score/c-statistic/validation curve (http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3575184/) But these methods of assessment may not work well for non-likelihood based models (trees/tree ensembles etc) that the poster appears to be considering.
Answer: If you see your problem as trying to calculate the probability of wind, it's no technically the same the problem of trying to predict when it will be windy or not.
In the first case your model will output "70%", "15%", "0%", etc. It's a regression problem, and a model can be evaluated using means squared error, for example.
In the second case you are trying to build a model that will output "yes" or "no", and it's a classification problem, and then the usual metrics are accuracy, f1 measure, AUC (area under ROC curve), etc.
In both cases you need to evaluate the model against a test set where you know the answers (usually you set aside some of the training data for this purpose).
I would say in this case your problem is most likely a classification problem. as you say yourself.
Now thinking of the weather reports that give probabilities of rain, that can perhaps be seen as a prediction + measure of the confidence. 80% chance of rain (wind... ) is kind of like predicting a yes with a pretty high confidence, 40% chance of rain is kind of predicting a "no" with a low confidence.
Some machine learning tools will allow you to put a confidence value on the result, others won't.
Finally I will just recommend the free open source tool Weka, it implements a whole bunch of different kinds of classifiers and will do the evaluation for you, too.
Answer: The question and your self-answer touch on a wide range of machine learning concepts. I will share my opinion on a couple of these.

In this particular location, I know it's windy 15% of the time (3
  years of data). Therefore, a model that always predicts a 15% chance
  basically deserves an overall score of 0 -- because it's more or less
  a coin flip. On the other end, a model that always predicts 0% or 100%
  deserves a "perfect" score. But what about in between?

So your prior probability of being windy is 0.15. You are right in your statement that you should take this prior probability of the event happening when you are evaluating the performance of your classifier. You can give the Bayesian Information Reward (BIR) a go.
The intuition of BIR is as follows: a bettor is rewarded not just for identifying the ultimate winners and losers (0's and 1's), but more importantly for identifying the appropriate odds. In doing so, it compares all predictions with the prior probabilities.
Let's say you have a list of 10 Arsenal (football team in England) games with possible outcomes: Win or Lose. The formula for binary classification rewarding per game is:

where, p is your model's prediction for a particular Arsenal game, and p′ is the prior probability of Arsenal winning a game. The catch-point is: if I know beforehand that p′=0.6, and my predictor model produced p=0.6,even if its prediction was correct it is rewarded 0 since it is not conveying any new information.

After doing a little more research, I believe what I want is either a
  decision tree or a multi-variate classification engine.

I think a Markov network (aka Markov Random Field) would be more appropriate. The wind will not materialise of thin air but will be blowing towads your location from  neighbouring ones in certain directions. So the probability of observing wind (e.g. Wind speed > 10 mph) at any square mile will be closely dependent on its neighbours (with ideally a time lag - depending on how far or close you define the neighbours).
Answer: After doing a little more research, I believe what I want is either a decision tree or a multi-variate classification engine.
Basically each of my weather conditions (e.g. temperature) is simply a feature. The machine learning algorithm can figure out which features are most relevant and ultimately make a prediction of wind / no wind based on a new set of features (the current weather conditions).
These links were very helpful:

https://www.igvita.com/2007/04/16/decision-tree-learning-in-ruby
https://github.com/mperham/bayes_motel
Comment: this doesn't address the issue of evaluating the final model, decision trees are generally poor predictors


Compatibility of Build agents when upgrading from TFS 2010 RTM to TFS 2010 SP1 with Cumulative Update 1

Question: I have TFS 2010 RTM installed on my production server and on all my build agents.  (Meaning I have what was initially released as TFS 2010, no service packs or updates.)
I would like to upgrade my server to the latest TFS 2010 SP1 with the Cumulative Update 1.
To get there I first have to install TFS 2010 SP1 on my prod server.  I then have to install TFS 2010 Cumulative Update 1.
Here is my Question:
If I install TFS 2010 SP1 on my prod server and then install TFS 2010 Cumulative Update 1, are all my build agents going to stop being able to talk to my server?  If so, will they stop working right when I install TFS 2010 SP1?
Basically, I am wondering if I need a multi computer down time.  I would like to just update my Prod Server then go back and update the build agents later (if needed).
What is the compatibility levels between Build Agents running TFS 2010 RTM and a Server running TFS 2010 SP1 with Cumulative Update 1?
Comment: You are aware RC is release candidate? No service pack for that. Install RTM first.
Comment: @TomTom - My bad. I meant RTM.  I have updated my question.  Thanks for catching that.
Answer: SP1 agents can talk to an RTM build controller just fine.  You definitely want to upgrade your agents to SP1 as soon as possible (lots of good fixes), but it won't break the agent communication to upgrade the controller first.


Java reading SWF and outputting to browser SocketCloseException

Question: function for reading swf, I'am using it also for images, but images are loaded ok:
public static InputStream readImage(String file) throws IOException {
    InputStream input = new FileInputStream(file);

        return input;
}

and here the last function for output where I'am passing the input stream:
  public static void writeImage(InputStream input) {

    try
    {
        byte[] buffer = new byte[1024];
        byte[] bytesSend;
        int bytesRead;
        /*
        while ((bytesRead = input.read(buffer)) != -1)
        {
            responseBody.write(buffer, 0, bytesRead);
        }
        */
        IOUtils.copy(input, responseBody);
        responseBody.flush();
        responseBody.close();
    }
    catch(IOException e)
    {
        System.out.println("bbbb");
        e.printStackTrace(System.out);

    }

  }

I've tried to use both the IOUtils.copy AND the while loop, i get the following errors:
sun.net.httpserver.StreamClosedException

java.nio.channels.AsynchronousCloseException

The SWF file has modules that are loaded too, so there are 4-5 swf requests..
Which server implementation I'am using?
public void run() {
    try
    {
        InetSocketAddress addr = new InetSocketAddress(8080);
        HttpServer server = HttpServer.create(addr, 0);

        server.createContext("/", new MyHandler());
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
        System.out.println("Server is listening on port 8080" );
    }
    catch(IOException e)
    {
        System.out.println("Http point error");
        System.out.println(e);
    }

}

Maybe somone has some ideas about this, I can provide more info if needed
Answer: It seems like the browser is deciding to stop reading the image file part way through.
One possibility is that you haven't set the right content type in the response.
Another is that you've arranged the browser side (e.g. in your HTML or Javascript) to "GET" the SWF document in a context where it makes no sense.
Comment: I've setted the content-type its application/x-shockwave-flash, what you mean by "arrange the browser side"? no its not about images, its about SWF, sometimes its loads successfully, but then the sockets are closed, I have http and sockets in one programm running paralell
Comment: If it is not about images, why do you call the methods `readImage` and `writeImage` ???
Comment: Either way, I think that it is something to do with what happens on the browser side.  Is anything showing up in your browser's web development UI / logs?
Comment: yes the application flash is displayed, but not all modules are loaded or even no one is loaded
Comment: I use the readImage and writeImage for the SWF and Images, they both work, the swf are loaded to the browser, but I can't understand why the error are ocurring


Memory leak detection tool in Cygwin

Question: I am scouting for a memory leak detection tool in cygwin. What could be the best memory leak detection tool for a C application in cygwin ?
Comment: There seems to be a [duplicate of this question](http://stackoverflow.com/questions/11811356/memory-leak-tool-on-cygwin).
Comment: True. I too came across that link before posting this query. It appears as a pretty old status and i believe that things should have changed/evolved by now. Also, the answers do not seem to point to a definite or best memory leak tool.
Answer: Allegedly you can use dmalloc under Cygwin: http://dmalloc.com/docs/5.4.3/online/dmalloc_18.html

Memory leak detection tool in Cygwin


how to load RTL style in RTL language

Question: I have a multi language website, one of languages is a RTL language, in Drupal 7 I put my CSS in style.css and RTL CSS to style-rtl.css and by default drupal also load style-rtl.css file, Now in Drupal 8 ,I have a multi language theme, how can I tell Drupal to load my RTL style in RTL language?
update
I found this link but I am not sure about that because  I have a CSS file with almost 1400 lines, I should put [dir="rtl"] before all of any selector ? !!!
Answer: Drupal 8 uses libraries, and you can load these in templates. One way of achieving language direction dependant libraries would be to use the html_attributes['dir'] variable in html.html.twig and load different libraries depending on the value:
{% if html_attributes['dir'] == 'ltr' %}
  {{ attach_library('your_theme_name/styles') }}
{% elseif html_attributes['dir'] == 'rtl' %}
  {{ attach_library('your_theme_name/styles_rtl') }}
{%- endif -%}

Set up a couple of libraries:
styles:
  version: 8.x-1.0
  css:
    theme:
      css/styles.css: {}

styles_rtl:
  version: 8.x-1.0
  css:
    theme:
      css/styles-rtl.css: {}

Answer: For those who are looking for an alternative solution:

You can also define a new library in libraries.yml file of your
  theme and point that library to use a certain CSS or JS or whatever
  you need.

Next step is to use a preprocess such as theme preprocess to tell Drupal8 to use that library in a specific condition.
Example:
Defining new library beneath your default one in themename.libraries.yml
rtl:
  version: VERSION
  css:
    theme:
      assets/css/themename.style-rtl.css: {}

Next you can detect the current direction of your pages with a preprocess in themename.theme file:
function themename_preprocess_html (&$variables) {
    // Load specific library for pages with html attribute of RTL
    if ($variables['html_attributes']['dir'] == 'rtl') {
          $variables['#attached']['library'][] = 'themename/rtl';
    }
}

Clear the cache and you are good to go
Comment: Thanks, this worked for me. Just wanted to point out that adding the library to the info.yml file will make it load in every page which is not what we need for multilingual sites.
Comment: Sure thing but I'm not saying that you should add it to info.yml file but libraries file, you can include a library based on your need in twig as well, so it's up to you
Comment: sorry, I haven't seen this answer. nice solution vote up
Answer: I just wrote a simple module called Twig RTL Detection which extends twig and provides a boolean is_language_rtl function for twig so you can simply add rtl libraries if this function returns TURE in any html.twig files you want.
{{ attach_library('my_theme/front') }}
{% if is_language_rtl() %}
  {{ attach_library('my_theme/front_rtl') }}
{% endif %}

Comment: Hi Alireza,
nice to see your answer. nice solution. maybe you can add more functionality and create a module  twig_tweak_rtl  ;)
Comment: Hi @Yuseferi, thanks for your reply, I would be glad to hear your ideas about this module, ad how it can be extended using features

how to load RTL style in RTL language


Como esperar pelo resultado de uma consulta no Firestore?

Question: Meu problema é o seguinte:
Eu tenho um componente que irá listar umas categorias, exemplo:
categories: Observable<any[]>;

ngOnInit() {
    this.categories = this.categoryService.getAll();
}

No service eu preciso fazer uma consulta primeiro no usuário (para obter um atributo dele), para só depois consultar as categorias. Exemplo:
getAll() {
  this.userService.getCurrentUser().subscribe(user => {
    this.partnership_id = user.partnership_id;
    this.categories = this.db.colWithIds$<Category>('categories', ref => ref
      .where('partnership_id', '==', this.partnership_id)
      .where('enable', '==', true)
      .orderBy('name')
    );
  });
  return this.categories;
}

Só que dessa forma, retorna as categorias em branco, pois o return executa primeiro que a consulta no firestore.
Como proceder nesse caso?
Comment: O valor so esta disponível dentro do subscribe mesmo pq e assincriono. você pode colocar um loading ate a query retornar ou usar o async pipe.
Answer: Firestore é uma promise, ou seja, você precisa passar uma função de callback no "getAll" e no final de todo o processo, já quando estiver com as categorias então chamar a função passada com o resultado.
function petecas(categorias) {
    console.log(categorias);
}

getAll(petecas);

function getAll(petecas) {
      this.userService.getCurrentUser().subscribe(user => {
        this.partnership_id = user.partnership_id;
        this.categories = this.db.colWithIds$<Category>('categories', ref => ref
          .where('partnership_id', '==', this.partnership_id)
          .where('enable', '==', true)
          .orderBy('name')
        );
        petecas(this.categories);
      });
      /*return this.categories;*/
    }


What is a good practice when setting www vs. non-www server (apache)?

Question: I have tried to configure a non-www website on Ubuntu 18.04 with Apache 2.4 and I've managed to make things work, my https://example.me works fine. But, www.example.me subdomain is also active (because I've added ServerAlias).
The https://www.example.me opens as well and shows no certificate which makes me confused - shouldn't it redirect to https://example.com ?
What is a good practice here - should I have both www and non-www subdomains and a separate conf file for each?
Should I use only one of them with permanent redirection?
Why is redirection not working here, do I need some other directive?
Kind regards.
<VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/mysite.me.crt
        SSLCertificateKeyFile /etc/apache2/ssl/mysite.me.key
        SSLCertificateChainFile /etc/apache2/ssl/mysite.me.crt
        DocumentRoot /var/www/html
        ServerName https://example.me
        ServerAlias www.example.me
        UseCanonicalName Off

        ProxyPreserveHost On
        ProxyRequests On
        ProxyVia On

        #ErrorLog /var/log/httpd/tomcat.error.log
        #CustomLog /var/log/httpd/tomcat.log combined

       <Proxy *>
               Order deny,allow
               Allow from all
       </Proxy>
        Include /etc/apache2/sites-available/redirect.conf

        ProxyPass / ajp://localhost:8009/
        ProxyPassReverse / ajp://localhost:8009/
</VirtualHost>

<VirtualHost *:80>
        ServerAdmin email@example.com
        ServerName example.me
        DocumentRoot /var/www/html
        UseCanonicalName Off
        Redirect permanent "/" "https://example.me/"

        ProxyPreserveHost On
        ProxyRequests On
        ProxyVia On

        #ErrorLog /var/log/httpd/tomcat.error.log
        #CustomLog /var/log/httpd/tomcat.log combined

       <Proxy *>
               Order deny,allow
               Allow from all
       </Proxy>
        Include /etc/apache2/sites-available/redirect.conf

        ProxyPass / ajp://localhost:8009/
        ProxyPassReverse / ajp://localhost:8009/

        #ProxyPass / http://localhost:8080/
        #ProxyPassReverse / http://localhost:8080/

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Comment: If you want to know why the redirect does not work you should include your redirect configuration file into the question.
Comment: That redirection contains some two thousand rules with redirection from old website to the new one.
Answer: First, please note that permanent redirects are cached by your web browser, so if you made a change and are testing a modified configuration, take pre-cautions and/or adjust your test methodology.  More about that here.

IMHO your configuration is also riddled with errors and incorrect assumptions.

DO NOT ENABLE / ALLOW proxy requests!!!
    ProxyPreserveHost On
    ProxyRequests On
    ProxyVia On
   <Proxy *>
           Order deny,allow
           Allow from all
   </Proxy>

The directives above are to create a forward proxy. Even worse, it is open proxy,  that can and will be abused by anybody wants to hide their IP-address using your web server.
You do not need ProxyRequests On for a reverse proxy and the ProxyPass  directives to work.
Please remove those.

In your HTTP VirtualHost
When you only have one VirtualHost it becomes the default VirtualHost (for that port and address). A longer description here.  So unless you have additional VirtualHost blocks defined,  this single entry:
<VirtualHost *:80>
        ServerAdmin firstname.lastname@example.com
        ServerName example.me

will be used for all plain http requests, i.e. both http://example.me/some-page.htm?foo=bar , http://www.example.me , http://your.ip-address/ etc. That VirtualHost will be used even when there is no explicit ServerAlias www.example.com designating www.example.com as an alternate host name for that particular VirtualHost.
 Redirect permanent "/" "https://example.me/"

Instructs that all requests will result in a redirect response to https://example.me/  in other words:
 http://example.me/some-page.htm?foo=bar  ==>  https://example.me/some-page.htm?foo=bar
 http://www.example.me                    ==>  https://example.me/
 http://your.ip-address/bob/is.awe-some   ==>  https://example.me/bob/is.awe-some

When you redirect everything away it also makes no sense to then have any other directives normally intended to display content in that VirtualHost, so you can omit the DocumentRoot, ProxyPass etc and keep a very minimal  plain http VirtualHost:
<VirtualHost *:80>
        ServerAdmin firstname.lastname@example.com
        ServerName example.me
        UseCanonicalName Off

        Redirect permanent "/" "https://example.me/"

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

In your HTTPS VirtualHost the same holds true: if there are no other VirtualHosts it will be the default used for any request.
The only thing is of course the server TLS certificate; that is only valid for the hostnames included in there, other hostnames will result in an invalid certificate error/warning.
You probably will need to check the contents of the file you include here:
Include /etc/apache2/sites-available/redirect.conf

Comment: Thank you Bob for such a detailed explanation. They are actually using proxy for tomcat and some other app... I  "inherited" this server from someone else and I'm trying to see what is a good practice and how to configure it and why is invalid certificate warning present with www.example.me. Do you maybe see it in this configuration? Should I add another virtualhost for www and link certificate there? Redirect.conf contains some two thousand rules for redirection of data from old to the new website...
Comment: You do not need to have a  forward proxy  enabled when using a reverse proxy or ajp


Django template and XML question

Question: I have this Django view that does render_to_response(rss.xml, {"list":list}) with this list:
description
description2
description3

the rss.xml template is the following:
<?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
        {% for item in list%}
        {{item}}
        {% endfor %}

This works, however the <'s and "'s get replaced by their special html charactervalues like:
<?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
<a href="link.html">Description</a>
<a href="link2.html">Description2</a>
<a href="link3.html">Description3</a>

how can I just output the raw strings such that the document becomes:
<?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
description
description2
description3

Answer: You should surround the for block with autoescape tags like so:
<?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
{% autoescape off %}
    {% for item in list%}
    {{item}}
    {% endfor %}
{% endautoescape %}

django won't escape the characters between the autoescape tags
see here:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#autoescape
Answer: Replace {{item}} with {{item|safe}} in your code. It will avoid escaping HTML characters. For more information, see this doc page.

Django template and XML question


Distinct count of 2 variables in SQL Server

Question: My table has columns id and status (failed, success) and status_id. Failure entries are redundant until a success reponse is saved. How to fetch distinct success and failure count failure attempts to be counted only once?
Query I tried:
select
    sum(case when status_id in (1,2,3,4) then 1 else 0 end) as success,
    sum(case when status_id in (5,6,7,8) then 1 else 0 end) as failed
from test

This query works but failed attempts are counted twice

id
status_id
status

123
5
failed

123
1
success

123
7
failed

123
5
failed

desired output success - 1 failure - 2
Comment: Sample data in the form of input and output would greatly help your question.
Comment: Provide some sample data as CERATE TABLE + INSERT INTO and desired output for this data.
Answer: To count each success/fail only once, do select distinct in a derived table before aggregating:
select
    sum(case when status_id in (1,2,3,4) then 1 else 0 end) as success,
    sum(case when status_id in (5,6,7,8) then 1 else 0 end) as failed
from (select distinct status_id from test) dt

Answer: Counting the unique status_id's might work.
select
 COUNT(DISTINCT case when status_id in (1,2,3,4) then status_id end) as success,
 COUNT(DISTINCT case when status_id in (5,6,7,8) then status_id end) as failed
from test


GetMonitorCapabilities returns false

Question: I want to adjust the brightness of my monitor on Windows.
I follow this page:
How to use GetMonitorCapabilities and GetMonitorBrightness functions
but, the GetMonitorCapabilities function returns false.
I printed using qDebug, hPhysicalMonitor is NULL. Is this point wrong?
(The GetPhysicalMonitorsFromHMONITOR function returns true)
How can I fix this code?
HMONITOR hMonitor = NULL;
DWORD cPhysicalMonitors = 1;
LPPHYSICAL_MONITOR pPhysicalMonitors;

HWND hWnd = GetDesktopWindow();

// Get the monitor handle.
hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY);

// Get the number of physical monitors.
BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &cPhysicalMonitors);

if (bSuccess)
{
    // Allocate the array of PHYSICAL_MONITOR structures.
    pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(cPhysicalMonitors* sizeof(PHYSICAL_MONITOR));

    if (pPhysicalMonitors != NULL)
    {
        // Get the array.
        bSuccess = GetPhysicalMonitorsFromHMONITOR( hMonitor, cPhysicalMonitors, pPhysicalMonitors);
        if (bSuccess == FALSE)
        {
            qDebug("GetPhysicalMonitorsFromHMONITOR");
        }
        // Get physical monitor handle.
        HANDLE hPhysicalMonitor = pPhysicalMonitors[0].hPhysicalMonitor;

        DWORD pdwMonitorCapabilities = 0;
        DWORD pdwSupportedColorTemperatures = 0;
        bSuccess = GetMonitorCapabilities(hPhysicalMonitor, &pdwMonitorCapabilities, &pdwSupportedColorTemperatures);
        if (bSuccess == FALSE)
        {
            qDebug("GetMonitorCapabilities");
        }

        DWORD pdwMinimumBrightness = 0;
        DWORD pdwCurrentBrightness = 0;
        DWORD pdwMaximumBrightness = 0;
        bSuccess = GetMonitorBrightness(hPhysicalMonitor, &pdwMinimumBrightness, &pdwCurrentBrightness, &pdwMaximumBrightness);
        if (bSuccess == FALSE)
        {
            qDebug("GetMonitorBrightness");
        }

        qDebug(QByteArray::number(bSuccess));

        qDebug(QByteArray::number((WORD)pdwMinimumBrightness));
        qDebug(QByteArray::number((WORD)pdwCurrentBrightness));
        qDebug(QByteArray::number((WORD)pdwMaximumBrightness));
        // Close the monitor handles.
        bSuccess = DestroyPhysicalMonitors(cPhysicalMonitors, pPhysicalMonitors);

        // Free the array.
        free(pPhysicalMonitors);
    }
}

Comment: From that same topic. *The function fails if the monitor does not support DDC/CI.*
Comment: [GetMonitorCapabilities](https://msdn.microsoft.com/en-us/library/windows/desktop/dd692940.aspx): *"If the function fails, the return value is FALSE. **To get extended error information, call GetLastError.**"*
Comment: this code periodically not worked and then worked. error - `ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA` *An error occurred while transmitting data to the device on the I2C bus.*
Comment: say first call to `GetMonitorCapabilities` can fail with `ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA` but second call with same data and parameters - ok
Comment: laptop computer does not work this funcion... if i fix using wmiSetBrighteness, how to change this code?
Answer: If you want to adjust the brightness using WmiMonitorBrightnessMethods use the code below.
     public static void SetWmiMonitorBrightness(byte targetBrightness)
    {
        ManagementScope scope = new ManagementScope("root\\WMI");
        SelectQuery query = new SelectQuery("WmiMonitorBrightnessMethods");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
        {
            using (ManagementObjectCollection objectCollection = searcher.Get())
            {
                foreach (ManagementObject mObj in objectCollection)
                {
                    mObj.InvokeMethod("WmiSetBrightness",
                        new Object[] { UInt32.MaxValue, targetBrightness });
                    break;
                }
            }
        }
    }

Doing GetMonitorBrightness on the specific monitor I have causes ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA.
So I used WmiSetBrightness instead. It works fine.
If you got a tip related to ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA, please share it with me.

GetMonitorCapabilities returns false


Find the point of discontinuity of the two functions 1. $f(x)=[\sin{x}]$, [] std for greatest integer function

Question: Find the point of discontinuity of the two functions:

$f(x)=\lfloor\sin{x}\rfloor$
$g(x)=\displaystyle{\lim_{n\to\infty}}\dfrac{(1+\sin{\frac{\pi}{x}})^n-1}{(1+\sin{\frac{\pi}{x}})^n+1}$

Both the problems are not yet solved. Please help.
Comment: Can you sketch a graph of $f(x)=\lfloor\sin(x)\rfloor$? The points of discontinuity should be obvious from the graph.
Answer: The first one is simple once you see that $\sin(x)$ only outputs values between 1 and -1 and also repeats every 2$\pi$, so if there's a discontinuity at $x_0$, then there's also one at $x_0+2\pi$.
The second one is easier once you simplify like this: $$\lim_{n\to\infty} \frac{(1+\sin(\frac{\pi}{x}))^n+1}{(1+\sin(\frac{\pi}{x}))^n+1}-\frac{2}{(1+\sin(\frac{\pi}{x}))^n+1}$$$$ = \lim_{n\to\infty} 1-\frac{2}{(1+\sin(\frac{\pi}{x}))^n+1}$$
Now just look at $\lim_{n\to\infty}(1+\sin(\frac{\pi}{x}))^n$.
If $1+\sin(\frac{\pi}{x}) > 1$, then it blows up to infinty.
If $1+\sin(\frac{\pi}{x}) < 1$, then it goes to zero instead.
At last, if $1+\sin(\frac{\pi}{x}) = 1$, then it stays at 1.
Consider all three cases for $g(x)$ and look for the values when it switches from one case to another.
I hope you can take from there.
Comment: Thank you for the hints. It is clear. But how to check all cases of $g(x)$
Comment: Explain further. What do you mean by "how to check all cases"? Are you asking how to do a case distinction?
Comment: Yes. Please provide me the solution of at least one case.
Comment: Please show your workings first. Just because you have three solutions, you don't get a case distinction out of them. Same for the opposite. I don't know if I should start at the "end" or at the "beginning"


How to put more than one image into an observable notebook cell?

Question: I have several images attached to an observable notebook. I'd like to show them all in a cell because the user can toggle through them with a dropdown select. Using an HTML cell, I have:

  <img src=`${await FileAttachment('Side.PNG').url()}` />

Side: method one

  <img src=`${img_urls.houseurl}` />

house: method 2

...and so on

In the first, I call the img url explicitly, and in the second I make a variable earlier to hold it. Both ways I end up with:

  <img src="\`https://static.observableusercontent.com/files/24_rest_of_url_7a9\`">

Side

If I put the URL directly into the src then it works fine.
What is the correct way to template this url into the html?
I suspect it has something to do with strange interpretation of the backticks?

There's an example file for this topic here but it doesn't have an image example
Answer: Observable does seem to treat backticks as a special thing. If you take them out it seems to work just fine.

Side: method one

This is one of those it works, but I don't know why answers, so if anyone knows the details, I'd love to know too!