RawJsonValues in Unity & Firebase

Question: Some problems with the SetRawJsonValueAsync. When I use the code from documentation:
    public class User
{
    public string username;
    public string email;

    public User()
    {
    }

    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

private void writeNewUser(string userId, string name, string email)
{
    User user = new User(name, email);
    string json = JsonUtility.ToJson(user);

    mDatabaseRef.Child("users").Child(userId).SetRawJsonValueAsync(json);
}

Then firebase automatically converts it to the tree of values. Ok. But when i'm trying to get them back:
    public void get_data()
{
    mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
        if (task.IsCompleted)
        {
            Debug.Log("completed");
            string json = task.Result.Value;
            User user = JsonUtility.FromJson<User>(json);
            Debug.Log(user.username);
        }
    });
}

it stops and doesn't print username. Why? Or how i need to get json raws?
Answer: The issue here is task.Result.Value is a C# interpretation of the value in the database. I believe it should be a IDictionary<string, object> given the code that you posted.
What you want is task.Result.GetRawJsonValue():
public void get_data()
{
    mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
        if (task.IsCompleted)
        {
            Debug.Log("completed");
            string json = task.Result.GetRawJsonValue();
            User user = JsonUtility.FromJson<User>(json);
            Debug.Log(user.username);
        }
    });
}

Comment: Thanks a lot! And can I serialize MonoBehavior scripts by this way (i mean using Json), because adding `: MonoBehaviour` leads to some problems.
Comment: If you want to fill out a MonoBehaviour, you need to initialize it on your own (either with `GameObject.Instantiate`, `GameObject.GetComponent`, or `GameObject.AddComponent`) since the constructor is kind of invalid for MonoBehaviour in Unity. Then you can use `JsonUtility.FromJsonOverwrite`. Note that you'll always miss `Awake` and sometimes miss `Start` this way, so it can make it hard to do this safely

https://docs.unity3d.com/ScriptReference/JsonUtility.FromJsonOverwrite.html
Comment: Cheers! It is helpful

RawJsonValues in Unity & Firebase


python - read float values from Tiff file

Question: I need to work with 32 bit tiff files with floating point values. It's a special file that contains 4 layers with floating point values from a depth measurement camera.
I have already tried imageio, tifffile and OpenCV. In opencv I set the attribute flag=cv2.IMREAD_ANYDEPTH as well, but nothing works. It is always imported as an 8 bit integer.
Is there any way to do it in Python? I know it works in Matlab, but I don't have the license.
Thanks in advance, any help is appreciated!
Edit: Sample image: https://ufile.io/fn1j2js6
Edit2: New sample with real 32bit: https://ufile.io/r17sxo0t
Comment: Thanks a lot for your help guys!! Due to this we discovered a bug in the export function of our software. Now I have an actual 32bit tiff file, that's readable by imageio, tifffile and rasterio (not by opencv though).
Comment: Your link doesn't appear to work.
Comment: @SamMason 8 bits per *"sample"*
Comment: Please share a file.
Comment: `tifffile` reads/writes float32 images for me!  https://stackoverflow.com/help/mcve
Comment: Thanks so far - I've uploaded a sample with another file hoster
Comment: @SamMason Thanks, but it didn't work either for me :/ Or have you used any special parameters?
Comment: Your image has 4 channels of 8-bits each. You can check it with `exiftool`.
Comment: yup, the file size is consistent with 8 bits per pixel not 32bpp.  532*460*4 == 978880, while the file size is 979066
Comment: @Jefferson presumably Matlab is trying to be "helpful" when converting data to floats while Python is just giving you the data as is
Comment: @MarkSetchell, oops, yup, that would be the correct term!
Comment: Enjoy your week!
Comment: If you update your sample, maybe we can figure out why cv2 doesn't work?
Comment: Hey @MarkRansom alright lets do it : ) I've uploaded another file. Tested with opencv v3.4 and v4.6 ^^
Answer: You can use scikit image. if its a normal tiff file
from skimage import io
my_img = io.imread('myimage.tiff')

Alternatively if your tiff file is a georeferenced image. You can use gdal
from osgeo import gdal
import numpy as np

ds = gdal.Open("myimage.tiff")

myarr1 = np.array(ds.GetRasterBand(1).ReadAsArray())
myarr2 = np.array(ds.GetRasterBand(2).ReadAsArray())
myarr3 = np.array(ds.GetRasterBand(3).ReadAsArray())

myimage = np.dstack([myarr1, myarr2, myarr3])


Changing root controller causes view to rotate to correct position

Question: First, I want to say that this question does not solve my problem: Orientation problem when I set a RootViewController
My ipad application only works in landscape mode. When I'm changing the root controller, the new storyboard appears correctly. But, it appears in portrait mode and then rotates to the correct orientation. How can I specify the orientation before changing the root controller or tell the storyboards to display in landscape by default ? It is pretty ugly seing the rotation of the view just after the animation.
Also, the landscape left and right are set in the project property.
Here is the code when I change the root view controller.
<code>UIStoryboard *editorStoryboard = [UIStoryboard storyboardWithName:@"EditorStoryboard" bundle:nil];
UISplitViewController *editorViewController = [editorStoryboard instantiateInitialViewController];

UINavigationController *navigationController = [editorViewController.viewControllers lastObject];
editorViewController.delegate = (id)navigationController.topViewController;

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

[UIView transitionWithView:appDelegate.window duration:0.5 options: UIViewAnimationOptionTransitionFlipFromLeft animations:^{
    appDelegate.window.rootViewController = editorViewController;
} completion:nil];
</code>
Comment: Have you checked the `Supported Interface Orientations` are selected only `Landscape Left` or `Landscape Right`(as per your need) in the Application Targets Summary
Comment: Yes, they are checked, forgot to add it
Comment: If they are checked the details are saved in Info.plist so application will load with portrait mode initially. So only select Landscape mode
Comment: I  meant landscape left and right are checked.
Comment: I found answer.  This is work fine.
[http://stackoverflow.com/questions/8053832/rootviewcontroller-animation-transition-initial-orientation-is-wrong][1]

  [1]: http://stackoverflow.com/questions/8053832/rootviewcontroller-animation-transition-initial-orientation-is-wrong
Answer: Did you try to override the
preferredInterfaceOrientationForPresentation
for the new root viewcontroller? Something like this:
<code>-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscape
}
</code>
This from the View Controller Programming Guide for iOS
EDIT: ok, what about trying to get rid of the animation?
Comment: Yes, and it still goes through portrait and then rotates to landscape.


Using Drag'n'Resize jqGrid with expand/collapse

Question: The expand/collapse button does not work properly with jqGrid when using the re-sizable grid with mouse.
The jqGrid is wrapped by a dragable div that sets the width/height of the grid. When I collapse the Grid it continues to show the 'resize' div even though the grid itself is collapsed.
Anyone have suggestions for this issue? Even the jqGrid Demo has this issue. The issue only happens after you resize it once first. Then try to collapse the Grid.
http://trirand.com/blog/jqgrid/jqgrid.html
This demo is replicating my issue. I am using the exact same code. You will notice that the grid also looks rather ugly when dragging.
Answer: So whenever you add the ability to resize the jqgrid it actually wraps the grid inside of a grid that is generated after you resize your grid.  Jqgrid appears to statically set values in inline css which causes some problems.
What I have done to fix this problem is look for the button that will trigger this event.  In the case of jqgrid there is an  tag with a class of 'HeaderButton' (it is the button in the upper right hand corner).  So I used jQuery to target the 'click' event and then changed the height of the 'resize' wrapper div to 'auto'.
So essentially I did this:
<code>//This first line select an element with a class="HeaderButton"
$('.HeaderButton').click(function () {
//Find the ID of the div that jqgrid is creating and replace RESIZEGRIDID with appropriate name
      if ($('#RESIZEGRIDID "/>').attr('data-status') != 'hidden' || $('#RESIZEGRIDID ').attr('data-status') == undefined) {
      $('#RESIZEGRIDID "/>').attr('data-status', 'hidden');
      $('#RESIZEGRIDID "/>').css({ 'height': 'auto' });
      } else {
      $('#RESIZEGRIDID "/>').attr('data-status', 'active');
      $('#RESIZEGRIDID "/>').css({ 'height': 'auto' });
      }
</code>
Hopefully this help ;)
Comment: This worked beautifully. It did the exact job I wanted. Thanks!


cKeditor and Elfinder don't load files to assets

Question: After putting site to hosting, ckEditor and ElFinder don't work. I Tried to see view-source in browser
<code>  <script src="/assets/15f6a66f/ckeditor.js"></script>
</code>
This and other files in assets folder doesn't exists. How can I solve this issue?
Comment: Are you using this url hardcoded somewhere ? where is it coming from.
Comment: This script link from site which i put in hosting (from page which i use ckEditor). I compared page with local site. In local site when i delete folder assets It generate files in folder assets , but when i put it in hosting it doesn't generate files in assets. It generated script link , but files (ckeditor.js and etc.) doesn't exists in folder assets
Comment: you need to install the extension using `composer require` should not copy the extension, if that is the case.
Comment: Is there another way to do this, because i have only ftp access to server i can't use composer
Comment: which composer package are you using for `CKEditor` ?
Answer: Proplem is solved! I made some changes in WebConfig:
<code>'components' => [
    'assetManager' => [
        'linkAssets' => true,
    ],
],
</code>
Another  issue was on permission .htaccess. I changed owner permission to Read, Write and Execute with FileZilla. Both work


Bind JSON object array to View in Angular2 nativescript

Question: I have a JSON object returned from my API like this
{
"ID": "GM5VY",
"Passengers": [
 {
"Firstname": "TEST",
"Lastname": "TRAVELLER",
"TotalCount": "1",
FqtT": [
  {
    "MembershipID": "XXXXXX"
  }
],
"Errors": null,
"Information": null,
"Warnings": null
}
],
"Errors": null,
"Information": null,
"Warnings": null
}

I'm converting this Object to an array using Pipe filter and trying to display Passengers First Name in View. But I couldn't able to retrieve
<StackLayout *ngFor=" let passengerls of PassengerDetails | objtoarray; let i = index">

</StackLayout>

Please help me in acheiving this!!!
Comment: Show your pipe implementation?
Comment: Could you setup an example plunkr
Answer: How about using a simpler way to iterate the array:
<StackLayout *ngFor="let passenger of PassengerDetails.Passengers">

</StackLayout>


Android - Transferir dados e mudar Fragment por Clique

Question: Oi, galera. Eu preciso de ajuda para transferir de Fragment quando eu clicar no meu botão dentro de uma ListView.
Atualmente eu tenho uma MainActivity (extends AppCompatActivity) para gerenciar os Fragments.
Abaixo tem algumas imagens de como está o App
Fragment 1:

ItemListView:

Fragment 2:

Eu quero que quando eu clique no botão de busca ele vá para o Fragment 2 passando o Id ou o objeto completo para esse outro fragmento.
Tentei pelo Adapter, mas fiquei perdido quando a questão é transferir de um Fragment para outro.
No adapter tenho algo como:
 holder.search = (ImageView) view.findViewById(R.id.iv_search);
            holder.search.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Código para transferir o Fragment aqui?
                }
            });

Como resolver esse problema? Desde já agradeço.
Answer: Olá, Victor. Vou escrever um código bem rápido aqui para tentar te auxiliar. Essa transferências de dados entre Fragments vai sempre ter a Activity como intermediária. O Fragment que recebeu o click vai passar o elemento para a Activity e a Activity vai transferir o elemento para o segundo Fragment.
Então, para começarmos, a ideia é que sua Activity implemente uma interface que o Fragment que sofrerá o click conheça e chame. Então, vamos criar a tal interface que será chamada quando houve o click no fragment:
public interface OnPesquisarClickListener  {
    public void onPesquisarClick(MeuObjeto meuObjeto);
}

E vamos então fazer com que a Activity herde dessa interface e implemente o método:
public class MinhaActivity extends AppCompact implements OnPesquisarClickListener {

    //... Outros métodos comuns da Activity

    public void onPesquisarClick(MeuObjeto meuObjeto) {
       //Transfira o objeto para o fragmento dois aqui. Por exemplo, fragmentoDois.pesquisar(meuObjeto)...
    }

}

Certo, agora no seu fragment que sofrerá o click, durante o método onAttach(), que é chamado durante o ciclo de vida do fragment quando uma o fragment é anexado a Activity, capture a Activity usando polimorfismo para termos em mãos uma instância dê OnPesquisarClickListener. Dessa forma:
public void FragmentTwo extends Fragment {

   OnPesquisarClickListener onPesquisarClickListener

   @Override
    public void onAttach(Context context) {
        if(context instanceof OnPesquisarClickListener) {
            onPesquisarClickListener = (OnPesquisarClickListener) context;
        }
        super.onAttach(context);
    }

    //Métodos comuns ao fragment
}

E naquele método que você descreveu vai chamar a instancia de OnPesquisarClickListener que recebemos:
holder.search = (ImageView) view.findViewById(R.id.iv_search);
            holder.search.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //onPesquisarClickListener.onPesquisarClick(...
                }
            });

Qualquer dúvidas é só falar que tento explicar de outras formas. Abs!
Comment: Era exatamente isso que eu queria. Valeu mesmo, cara. Ajudou bastante!
Answer: Tássio, Boa noite.
Mano eu estou com uma duvida bem parecida, porém continuei na duvida. Pois o meu é dentro de um Recycle view.
//Configuração evento de clique
    recyclerBook.addOnItemTouchListener(
            new RecyclerItemClickListener(
                    getActivity(),
                    recyclerBook,
                    new RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {

                            Book book = new Book();
                            book.setTitle(book.getTitle());
                            book.setWriter(book.getWriter());
                            book.setThumbnailHd(book.getThumbnailHd());

                        }

                        @Override
                        public void onLongItemClick(View view, int position) {

                        }

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        }
                    }
            )
    );

e como eu pegarias essas informações no outro Fragment?


In simple graph, union of Edge sets of distinct u−v Path must contain a cycle. T/F

Question: In this question  The union of Edge sets of distinct $u - v $ Path must contain a cycle. the solution shows that for base case of induction we need a multi-graph. But if it is clearly mentioned that the graph is simple, does it suffice to say that a single edge graph u-v doesn't have a cycle in the union of edge sets? And hence the statement fails for simple graphs?
Answer: In a simple graph the base case is vacuously true: there are never two distinct $u-v$ paths whose lengths sum to $2$. From there you can use the same induction argument.
The statement is still true for simple graphs, because every simple graph is also a multigraph that just happens to have at most $1$ edge between each pair of vertices.
Comment: In that case, there is only one possible $u-v$ path. So there cannot be distinct paths in the first place. So the fact that there is no cycle doesn't matter, because there's also no distinct paths to take a union of.
Comment: If I take the graph as a single edge u--v then how is the statement valid in this case?
Comment: Ok. Got it thanks!


Correct usage of ~ parameter expansion flag?

Question: According to man zshexpn (5.0.2):

~      Force  string  arguments  to  any of the flags below that follow within the parentheses to be treated as
                patterns.

For example, using the s flag to perform field splitting requires a string argument:
% print -l ${(s:9:):-"foo893bar923baz"}
foo8
3bar
23baz

My reading of the ~ flag suggests that I should be able to specify a pattern in place of a literal string to split on, so that the following
% print -l ${(~s:<->:):-"foo893bar923baz"}

should produce
foo
bar
baz

Instead, it behaves the same as if I omit the ~, performing no splitting at all.
% print -l ${(s:<->:):-"foo893bar923baz"}
foo893bar923baz
% print -l ${(~s:<->:):-"foo893bar923baz"}
foo893bar923baz

Answer: Ok, rereading the question, it's the difference between this:
$ val="foo???bar???baz"
$ print -l ${(s.?.)val}
foo
bar
baz

And this:
$ val="foo???bar???baz"
$ print -l ${(~s.?.)val}
foo???bar???baz

It operates on the variable, i.e. the "argument" to the split (from your documentation quote). In the first example, we substitute literal ?, and in the second, we treat the variable as a glob, and there are no literal ?, so nothing gets substituted.
Still, though, split works on characters and not globs in the substution itself, from the documentation:
s:string:
    Force field splitting (see the option SH_WORD_SPLIT) at the separator string.

So, it doesn't look like you can split on a pattern. The ~ character modifies the interpretation of the string to be split.
Also, from the same pattern expansion documentation you reference, it continutes:

Compare with a ~ outside parentheses, which forces the entire
  substituted string to be treated as a pattern. [[ "?" = ${(~j.|.)array} ]]
  with the EXTENDED_GLOB option set succeeds if and
  only if $array contains the string '?' as an element. The argument may
  be repeated to toggle the behaviour; its effect only lasts to the end
  of the parenthesised group.

The difference between ${(~j.|.)array} and ${(j.|.)~array} is that the former treats the values inarray as global, and the latter treats the result as a glob.
See also:

${~spec} Turn on the GLOB_SUBST option for the evaluation of spec; if
  the '~' is doubled, turn it off. When this option is set, the string
  resulting from the expansion will be interpreted as a pattern anywhere
  that is possible, such as in filename expansion and filename
  generation and pattern-matching contexts like the right hand side of
  the '=' and '!=' operators in conditions.

Here is a demo that shows the differences:
$ array=("foo???bar???baz" "foo???bar???buz")
$ [[ "foo___bar___baz" = ${(~j.|.)array} ]] && echo true || echo false
false
$ [[ "foo___bar___baz" = ${(j.|.)~array} ]] && echo true || echo false
true

And for completeness:
$ [[ "foo___bar___baz" = ${(~j.|.)~array} ]] && echo true || echo false
true

Comment: Quick note on some things I learned from the developers. The difference between `${(~j.|.)array}` and `${(j.|.)~array}` is that in the first one, only `|` added by the join are part of the pattern; `|` in the existing array elements are still literal characters. (Imagine an array of file names, one of which is the unfortunately named `a|b`.) In the second one, *all* `|`, whether part of an array element or added by the join, are considered part of the pattern.
Comment: I understand what the `s` flag does; I'm asking about the `~` flag, which this answer does not address. Please re-read the question. The `~` appears *inside* the parentheses along with the `s` flag; it is not the `~` operator that appears immediately preceding the parameter name (after any flags).
Comment: Updated answer to include example of what the `~` flag does.
Comment: It could be bad wording in the documentation, but I'm pretty sure the argument in `${(s.foo.)bar}` is `foo`, not `bar`.
Comment: The problem I have with the last quote from the docs you show is that there doesn't seem to be any difference between `${~(j.|.)array}` and `${(~j.|.)array}`.
Comment: `bar` is the argument, as I've demonstrated in my examples, per the `${(s.foo.)bar}` comment. It could very well be bad wording in the documentation -- I'm taking an empirical approach here. I've updated the answer to explain and demonstrate the differences of the other comment.
Comment: The fact that the last two produce the same result makes me think that the flag `~` is just irrelevant for the `j` flag. (Which makes sense: what does it mean to join the words with a pattern, rather than a string?) The first example is a syntax error because the flags come before the operator; fixing to `${(j.|.)~array}` outputs true as well.
Comment: I agree, in the context of joining, I can't think of an example where it would have an effect, but that's the difference between inside and outside the parentheses, and it applies to other parameter expansion flags.


Queria saber como passar um registro de um array de uma página php para outra e então para uma tabela sql

Question: Gostaria de saber como passar um registro do array de uma página php para outra página php que vai, então, dar um insert na tabela correspondente no banco de dados, sou iniciante em php e já tentei de várias formas mas sem sucesso. (PS: quero passar da página carrinho.php para finalizar.php) (OBS: também aceito outras sugestões de como passar os dados sem ser por array)
Meu código atualmente está assim:
Minha tabela:
CREATE TABLE pedido (
id_pedido int not null AUTO_INCREMENT,
id_empresa int not null,
data_pedido varchar(15) not null,
data_entrega varchar(15) not null,
estado int not null,
data_vencimento varchar(45),
CONSTRAINT pk_ped PRIMARY KEY (id_pedido),
CONSTRAINT fk_ped FOREIGN KEY (id_empresa) REFERENCES empresa (id_empresa)
);

carrinho.php:
<?php
session_start();

if (!isset($_SESSION['tudo'])) {
  $_SESSION['tudo'] = array();
}

if (isset($_GET['add']) && $_GET['add'] == 'carrinho') {

  $idProduto = $_GET['id_residuo'];
  if (!isset($_SESSION['tudo'][$idProduto])) {
    $_SESSION['tudo'][$idProduto] = 1;
  } else {
    $_SESSION['tudo'][$idProduto] += 1;
  }
}
?>

  <meta charset="utf-8" />

           Nome do Residuo
           Quantidade
           Preco Unitário R$
           Total
           Remover

      <?php
      if (count($_SESSION['tudo']) == 0) {
        echo 'Carrinho Vazio';
      } else {
        try {

          $pdo = new PDO('mysql:host=localhost;dbname=bd_reuse', "root", "");
          $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $ex) {
          echo "ERRO: " . $ex->getMessage();
          exit;
        }

        $idEmpresa = $_SESSION['id_empresa'] + 0;

        $_SESSION['dados'] = array();
        $estado = "0";
        $tudo = 0;
        $quantidadeTotal = 0;

        foreach ($_SESSION['tudo'] as $idProduto => $quantidade) {

          $select = $pdo->prepare("SELECT * FROM residuo WHERE id_residuo = ?");
          $select->bindParam(1, $idProduto);
          $select->execute();
          $residuos = $select->fetchAll();
          $total = $quantidade * $residuos[0]["valor_residuo"];
          $tudo += $total;
          $valor = $residuos[0]["valor_residuo"] + 0.0;
          $quantidadeTotal += $quantidade;
          $dataP = date('d-m-Y');
          $dataE = date('d-m-Y', strtotime('+1 week'));
          $dataV = date('d-m-Y', strtotime('+1 month'));
          echo
          '

              ' . $residuos[0]["nome_residuo"] . '

              ' . $quantidade . '

              ' . number_format($residuos[0]["valor_residuo"], 2, ",", ".") . '

              ' . number_format($total, 2, ",", ".") . '

               Remover

';

          array_push(
            $_SESSION['dados'],
            array(
              'id_empresa' => $idEmpresa,
              'data_vencimento' => $dataV,
              'data_pedido' => $dataP,
              'data_entrega' => $dataE,
              'estado' => $estado,
              'quantidade_item' => $quantidade,
              'valor_item' => $valor
            )
          );
        }
      ?>

           <?php echo ' Finalizar Pedido ' ?>

           Valor Total
           <?php echo number_format($tudo, 2, ",", ".") ?>

           Quantidade Total
           <?php echo $quantidadeTotal ?>

      <?php
      }
      ?>

finalizar.php:
<?php
session_start();

try {
    $pdo = new PDO('mysql:host=localhost;dbname=bd_reuse', "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
    echo "ERRO: " . $ex->getMessage();
    exit;
}//fim conexao

$insert = $pdo->prepare("INSERT INTO pedido (id_empresa, data_pedido, data_entrega, estado,
data_vencimento) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam(1, $_SESSION['dados']['id_empresa']);
$insert->bindParam(2, $_SESSION['dados']['data_pedido']);
$insert->bindParam(3, $_SESSION['dados']['data_entrega']);
$insert->bindParam(4, $_SESSION['dados']['estado']);
$insert->bindParam(5, $_SESSION['dados']['data_vencimento']);
$insert->execute();
?>

É basicamente isso, desculpe pelo código grande.
Agradeço pela paciência e eu agradeço demais quem puder ajudar pois estou realmente precisando disso funcionando.
Comment: Não faz muito sentido isso... Os itens do carrinho estarão numa tabela, quando clicar em finalizar você recupera esses itens sem precisar passar de uma página para outra
Comment: Concordo com @PapaCharlie, mantenha uma tabela com os pedidos dos clientes(carrinho de compras), acontece de clientes inicializarem uma transação de compra em um dispositivo e terminar em outro. Se utilizar o dispositivo cliente para armazenar ou rotear esses dados ele fica restrito a finalizar a compra apenas nesse dispositivo e navegador e os dados dessa operação podem se perder em caso de falha do equipamento do cliente ou limpeza de  memória do browser.
Answer: Então pelo que eu sei a maneira mais facil fazer isso seria você armazenar os dados do array num COOKIE e depois recuper essa informações na outra página no caso "finalizar.php", lembrando que os COOKIES ficam armazenados no cliente ou seja no navegador do usuário, mas para essa situação se encaixa perfeitamento porque creio que você queira apenas passar essas informações para outra página para depois transferilas para o banco de dados. Se voce nao souber utilizar COOKIES e só pesquisar ou ir na documentação e bastante simples de usar.


How to calculate numerical trend lines in python

Question: I have a monitoring application in python 2.6 that calculates the number of entries in a queue (queue_len). I want to create a simple function that can use these queue_len rate of change values over time and extract a trend from them.
The goal is to start up or shut down queue processing nodes depending of the +ive or -ive trend over time and not flip flop.
MACD from the financial arena looks sort of what I need or does it? Looking for any help here.
Comment: There is no real way to trend these types of things. MACD is also a laggish indicator, so it won't help you much.
Answer: Isn't that just a simple derivative?
<code>def derivs(l):
  return [l[i + 1] - l[i] for i in range(len(l) - 1)]
</code>
Comment: Yes for sure this derivative is part of what I'm after. I would see the solution as somehow using this first derivative of the moving averages and then applying another function/formula to that which would magically tell me when a certain high or low threshold value has been triggered i.e., the trend has reversed or some such. Does that make sense?
Comment: Then do just that ;) `numpy` will be a good module to use for this, as it contains many number-crunching functions.
Comment: Because nobody chimed in here with a piece of code that I could just slot in to solve my problem I took your advice and had to do it myself!
Comment: Mind posting how you did it? I bet it would save others with the same problem a few hours of coding.
Comment: 2nd @Blender's suggestion of posting your code - I am interested in exactly this ability to estimate trend and trend change of an underlying value set


Nodejs - Generating unique random alpha numeric random string for Database

Question: I have a use case where I need to generate alpha numeric capital case strings of length 25, so the total possible unique combinations are very high:
36 pow (25) = 808281277464764060643139600456536293376

The string is to be stored in MySql database table with unique set to true
I am using following code to generate the string:
const Chance = require('chance');
const chance = new Chance(Date.now() + Math.random());
let randomStr = chance.string({length: 25,
                pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'});
console.log(randomStr);

Node.js can run in cluster mode, so value of timestamp can be same for different requests so I also added Math.random(). Is this enough to ensure that MySql unique constraint won't be violated by the random strings.
Comment: You want a universally-unique string that's largely alphanumeric? That sounds an awful lot like [a UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier), which your database probably supports already.
Comment: Yes, UUIDs are 128 bits. That's significantly smaller than your 25-character identifier, while still being universally unique **and** optimized in most databases for fast lookups.
Comment: @ssube uuid is 128 bit
Comment: @ssube I haven't mentioned that I am going to use it for lookups and want to improve the lookup performance
Comment: Performance has little to do with it. The database is the only actor able to guarantee that a value is unique, so it should be the one producing those values. Most databases have fantastic UUID support, which happens to include performance optimizations.
Answer:
Is this enough to ensure that MySQL unique constraint won't be violated by the random strings.

3625 has 129 bit. If we apply the birthday problem, then you're likely getting a collision around 264 strings. You'll probably generate much less than that. This is only true provided that you use a good randomness source.
Math.random() is not a good randomness source.
Comment: Doesn't appending timestamp and math.random()  to generate seed guarantee a unique number atleast every nanosecond which should be enough if I am not using more than 4 node servers in a cluster
Comment: It's not guaranteed, but it's pretty unlikely. Also, you can even solve this without any randomness at all. Just give each node in the cluster a different identifier (a single character is enough). It's unlikely, but if two requests are handled at the same time in a single node server, then you can use a counter. Concatenate the node id, the counter and the timestamp in order to get a short and guaranteed unique ID.


Custom error page: The path is either invalid or you do not have access to it

Question: I'm trying to add a custom page, by using admin/config/system/site-information
When I enter the field, as follows:
Default 404 (not found) page
http://mysite.com/errors/404.html

It shows the following error:
The path 'errors/404.html' is either invalid or you do not have access to it.
Though when I enter in my browser: http://mysite.com/errors/404.html it opens just fine.
So, what's wrong with Drupal, why it doesn't see it?
Answer: When you go to admin/config/system/site-information to enter the path in the field Default 404 (not found) page, you don't have to add .html just write errors/404 and it will work.
Comment: well, it's the same, guess it only handles the very pages created in drupal itself
Comment: When you said _custom page_, how did you create this page? (Did you use a content type like `basic page` or anything else? If you want to use a path in drupal, he has to know it before)
Comment: Well it was just one html page I wanted to display. Now I understand, I had to add it, so I `block` instead. And I want only to display this block, I tried `block/4` but it doesn't work either. Is there any way to assign a node for a block?
Comment: You can't assign a block in a path (i think, i'm not a Drupal expert) But you can put a block in a page which already exist (and so who has a path)
Comment: Does it mean I need to create a new content type, then add one and only entry to that type just to display a single page as a node?
Comment: Best way to do (the simple way) is to create a content type of `basic page` and in **url path setting** put `errors/404`...After go to `admin/config/system/site-information` and follow the procedure
Answer: I suppose if properly, you have directory "errors" where have a file 404.html. In Drupal one of the right way to do this is like next: create node Page content type (may by only enter title, see and remember node id after saving), copy node.tpl.php from modules/node folder in your current theme folder, rename this copy to node--NID.tpl.php where NID is id of previosly saved node, then edit this template as you want, then add path alias to this node as "errors/404.html"
Comment: Thanks, I think this is exactly what I need. I'll give it a try right now.
Comment: Looks like it was a too simple thing to do, I din't even need to alter the templates, but thanks for advice though.


Quando utilizar parâmetros opcionais acima de overloading e vice-versa?

Question: Um parâmetro opcional no C# é declarado da seguinte forma (veja o parâmetro y):
public void DoFoo(String x, String y = "") { ... }

Em muitos casos, essa feature pode ser substituida pelo overload da assinatura do método
public void DoFoo(String x) { ... }
public void DoFoo(String x, String y) { ... }

Quando a melhor opção seria usar overloading acima de um parâmetro opcional e vice-versa?
Answer: Limitações técnicas
Expor métodos com parâmetros opcionais como APIs para outras linguagens que não suportam esta funcionalidade gera problemas, neste caso sobrecarga de métodos é o recomendável.
Operações com reflection também apresentam incompatibilidade com parâmetros opcionais.
Funcionalidade
Seu método faz a mesma coisa independentemente dos parâmetros?
Se sim, use parâmetros opcionais, se não use sobrecarga de métodos. Funcionalidades diferentes devem estar em métodos diferentes.
Tirando as limitações técnicas e funcionalidade, os próximos pontos são subjetivos, ou seja, é questão de preferência, gosto e alinhamento com seu time/equipe em relação ao estilo de código empregado:
Parâmetros opcionais = Menos código
Sobrecarga de método:
public void Method(string str1)
{
   // ...
}

public void Method(string str1, string str2)
{
   // ...
}

Parâmetros opcionais:
public void Method(string str1, string str2 = null)
{
   // ...
}

No exemplo acima, apenas um método é necessário, diminuindo significativamente a quantidade de código. Consequentemente haverá menos documentação XML.
Parâmetros opcionais = Intellisense mais conciso
Com parâmetros opcionais, o Intellisense do VS exibe o método em uma linha só com os parâmetros opcionais:

Com sobrecarga de método, você tem que navegar por cada método para achar o que você deseja:

Referência
Answer: O uso dos parâmetros opcionais delegam à lógica da função como serão feitas as operações internas, não deixando a chamada da função decidir qual será o comportamento e uso desses parâmetros.
Em uma função que possui outras sobrecargas, o uso dos parâmetros são explicitados em sua chamada, dando uma noção básica do que será feito em sua lógica interna. Isso possibilita a quem utilizar essa função decidir qual seria a melhor realização de determinada tarefa.


How to copy or duplicate an array of arrays

Question: I'm trying to make a function that duplicates an array of arrays. I tried blah.slice(0); but it only copies the references. I need to make a duplicate that leaves the original intact.
I found this prototype method at http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

It works, but messes up a jQuery plugin I'm using - so I need to turn it onto a function... and recursion isn't my strongest.
Your help would be appreciated!
Cheers,
Comment: Be sure to declare "i" with `var`!  Also it's risky to iterate over an array with a `for ... in` loop - much safer to use numeric indexes.
Comment: See: http://stackoverflow.com/questions/565430/deep-copying-an-array-using-jquery
Answer: function clone (existingArray) {
   var newObj = (existingArray instanceof Array) ? [] : {};
   for (i in existingArray) {
      if (i == 'clone') continue;
      if (existingArray[i] && typeof existingArray[i] == "object") {
         newObj[i] = clone(existingArray[i]);
      } else {
         newObj[i] = existingArray[i]
      }
   }
   return newObj;
}

Answer: For example:
clone = function(obj) {
    if (!obj || typeof obj != "object")
        return obj;
    var isAry = Object.prototype.toString.call(obj).toLowerCase() == '[object array]';
    var o = isAry ? [] : {};
    for (var p in obj)
        o[p] = clone(obj[p]);
    return o;
}

improved as per comments
Comment: Will break for `null` (null.pop will throw). The first check should be   something like `if (typeof obj != "object" || !obj)`.
Comment: Also, questionable handling of inherited properties - "clone" in JavaScript has problematic semantics.


SQL Calculation of PRIMARY KEY (autoincrement)

Question: assuming I have an empty table "TABLE_1". Then I use;
 SET IDENTITY_INSERT TABLE_1 ON

to insert some data (including primary key).
Afterwards I deactivate IDENTITY_INSERT and want to insert other values (the default way, i.e. without the primary key). How does SQL calculate the new primary key value? Is it something like:
MAX(ID) + 1

Thanks in advance
Eugen
Comment: This question appears to be off-topic because it is about an internal implementation detail that you should worry about. Usually when someone asks a question like this, they are asking about some detail to a perceived solution to a problem. You might be better off telling us the actual problem you are trying to solve.
Comment: It's a **lot more complicated** than this! And don't use this `MAX()+1` approach yourself - it's **not concurrency safe** and you'll end up with duplicates!
Answer: I've done some testing:
CREATE TABLE tmp.test (
    ID INT IDENTITY PRIMARY KEY,
    val NVARCHAR(255)
)

INSERT INTO tmp.test (val) values ('run_1.1')

SET IDENTITY_INSERT tmp.test ON
INSERT INTO tmp.test (ID, val) values
(112, 'run_2.1'), (2, 'run_2.2'), (45, 'run_2.3')
SET IDENTITY_INSERT tmp.test OFF

INSERT INTO tmp.test (val) values ('run_3.1'), ('run_3.2')

select * from tmp.test

The result is:
ID  val
1   run_1.1
2   run_2.2
45  run_2.3
112 run_2.1
113 run_3.1
114 run_3.2

That means, no reseed is required :-), which is great.
P.S.: I am using SQL Server 2008
Comment: Good to know. Just learned something new!
Answer: Taken from SQL Server documentation:
http://technet.microsoft.com/en-us/library/ms188059.aspx
If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.


Valve (tube) amps and clean tone

Question: Is there any difference in clean tone sound between a valve/tube amp and a solid state amp? i.e., does having a valve in an amp affect the clean channel, or only the distorted channel?
Apologies for the newbie question, but I was just wondering if there is any advantage (or disadvantage) to having a valve amp if you are using the clean tone.
Answer: "Clean" tone is a relative term, especially when talking about tubes.
Nearly all amplification circuits introduce artifacts into the waveform; what you put in is not 100% exactly the same as what you get out. Most solid-state circuitry can achieve a waveform that is 99.5% "similar" or better; that is, they achieve less than .5% total harmonic distortion or THD. Some can achieve <.01%. This is, in the technical sense, a "clean tone", where output == more input, and this is generally preferable for most professional audio amplification needs. However, it can result in a disagreeable tone for an electric guitar (and other instruments); too much highs, too much mids, too "angular" a tone, etc.
Tube amps have a markedly higher THD; the circuit doesn't respond to the waveform as fast, and the ratio of peak input to peak output in the waveform diminishes earlier, but more gradually, than solid-state. In layman's terms, tubes "distort" the wave more than solid state at all signal levels, "coloring" the tone of the instrument, and they "clip" at lower levels than SS. But, tubes have a softer "peak" level than SS circuitry. which will simply "chop off" the waveform at the maximum gain level. Tubes instead "squish" the parts of the wave that exceed the max gain.
So, your answer is, at low signal levels that both circuit types can produce without clipping, there will be a slightly different tone produced by the tube amp, but unless you are comparing two amps side by side you would not detect the difference (and amps of all types will produce tonal variances regardless of tubes vs SS). At higher signal levels, the SS amp will still have "headroom" while the tube amp starts to "squish" the waveform peaks. In this grey area between clean and overdriven tone, you'll get a lot of different behaviors between SS and tube and between various circuit designs. Obviously, at "true" clipping levels, SS will produce a markedly different waveform than tube and the difference is quite noticeable until you push both amps into an extremely square wave.
Comment: It is not really possible to push a tube power amp "into an extremely square wave" anyway.
Answer: Have a look at this question - I think that although full solid state amps are slowly getting better at emulating Valve aps, there is a definite something about a Valve amp that works well with guitar, whereas a solid state amp is generally more clinical.
More obviously, when cranking up the drive/input gain, a Valve amp tends to produce a warmer fuzz/distortion than a solid state one. This goes for the clean channel as well as the overdrive channel.
All a matter of preference of course, but definitely distinct differences.
Comment: @KeithS - no. Although in my second paragraph I mention what happens when drive is increased, my entire answer is about the clean channel, not the distorted channel.
Answer: Turning up the master volume on a valve amp overloads the amps power-amp section which typically adds a musical compression and slight distortion to the sound while still being 'clean'. This aspect that also affects the perceived 'feel' of the amp, which is what people talk about when they talk about a spongy valve tone.
The power-amp section of a solid state amp (at least ones that don't use digital modelling to emulate valves) typically are designed not to distort the sound at all (as when they do it doesn't sound musical as it does with valves) and as such they tend to have a 'clear' or 'clinical' clean sound. This is not necessarily a bad thing, the Roland Jazz Chorus for example is a very popular solid state amp
Answer: As a studio engineer friend once told me "I can clean every bit of feeling right out of this music".  He was referring to modern solid state and digital techniques.  The other posts talk about the mechanical details of the signal. Maybe I pinpoint the visual as I have been experiencing a "dirty" VOX tube sound that I am trying to clean up.  The tube response is much smoother and mellower and because of that gives a "warmer" or fuller tone.  I'm trying to change tubes to get a crisper sound on the pre-amp side and add "head" room on the power side.  The sharper pre-amp signal sent to a power tube with more headroom will allow for a cleaner tone at more volume before the sound distorts (or crunches). I'm plying through a 4 watt amp at practice volumes.  The solution for performance is a more powerful amp that you can drive at the proper level to get the sound you want.  Example Carlos Santana medium drive on his amp to the edge of crunch- AC\DC Angus Young playing in the crunch zone.
Hope this helps...

Valve (tube) amps and clean tone


twitter developer console and twitter oauth tool

Question: I am trying to get a request token from twitter, and I've been having some problems with it.  I used twitter4J to see if it would work with that and it does, but when I use the twitter oauth tool to get a valid authorization header, and copy and paste it as the authorization header for http://api.twitter.com/oauth/request_token in the twitter developer console I get a 401 error ("failed to validate signature and token"). I have tried this same copy and paste method for other requests that require authentication and it works but it just won't work for this request. Any suggestions as to what is going on?
Answer: Ok I figured it out! The problem was that the oauth access token is included in the header when you use the twitter oauth tool, with the access token being that of the twitter account related to your application. But if you are using the request_token url you shouldn't already have that, and that is why it throws the error. Thus the twitter oauth tool is useless for a request to this url.


Libraries imported in one .py doesnt work for imported functions of anothers .py

Question: Hope you can help me on this, here is the problem:
I'm working in "x.py" in which I have imported a lot of functions from another file named "functions.py".
Also, I have some specific functions in other files (s1.py,s2.py lets say...), which I also called in my x.py.
The problem comes when I try to use a function or library from functions.py in order to help me with those specifics files where I have other functions (s1.py, s2.py). They just simply dont recognize the libraries which I already imported... ???
Work around I've been using: declare the libraries needed directly in s1.py and s2.py, but I don't like it to much, it seems like I'm duplicating that code.
Is there any way to get my s1.py and s2.py to recognize the imported libraries in x.py???
Comment: You will have to post some code, a [mcve] of the problem that people can copy and run on their envs to help you debug the problem. Specifically, your file structure, how functions are declared, how you import them, and what the exact error message is (what does "*dont recognize the libraries*" mean? is it a ModuleNotFoundError?).
Answer: Importing a module does not import all its imports by default. You do need to import functions in s1 and s2 even if you are already doing import x.
Or alternatively, you could do from x import functions inside s1 and s2. But personally I'm not sure if I would ever do that - it obfuscates things a bit, and one might say that code duplication is not a thing in the case of imports. Maybe it would make sense on a conceptual level: we import functions via x because the functions are specific to x. But in such case I would make x a package and put functions in that package (in which case the import statement would incidentally look the same). But if functions is not specific to x, i.e. it is expected to be useful for various modules unrelated to x, then don't import it via x.
If you're concerned about the performance impact of multiple imports, this explains that there is none.


generating a bash script

Question: How do I use Perl to create another file known as hello.sh?
I tried:
#*perl codes*
#Before this has perl's section of codes
#Now want to create shell script
open FILE , ">hello.sh" or die $!;
chmod 0755, "hello.sh";
print FILE
"#!/bin/sh
echo "Hello World!
";
close FILE;

But this is pretty redundant. It would be very hard to do this if I want to use IF-ELSE.
Any idea?
EDIT
I tried this
print FILE
"#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
";

As you can see, the Its detects as not a string,
Did I miss any syntax here?
Comment: Yes you can, no there's nothing difficult to it, and your comment makes no sense at all.
Comment: Perl can print anything to a file that you could type into a file, yes.
Comment: You're not printing your file's contents. It's just a string, not going anywhere.
Answer: You should print content to file handle FILE
open FILE , ">", "hello.sh" or die $!;
chmod 0755, "hello.sh";

print FILE <<'END';
#!/bin/sh
echo "Hello World!"
END

close FILE;

<<'END' .. is heredoc syntax which doesn't try to interpolate strings which perl would recognize as variables (prefixed with $ or @)
It also ensures that ' or " quotation marks don't need to be escaped with \
Comment: Thank you, this is what I am looking for, will google and study about it soon. But is that `q` could be anything?
Comment: yes, as long it isn't in content. I've renamed it to `END`
Comment: @mpapec It's worth noting that `unquoted(<<END)` or `double-quoted(<<"END"` will interpolate.
Comment: check @gpojd solution
Answer: You need to escape the quotation marks:
print FILE '#!/bin/sh
if [-d $1]; then
echo "It\'s a directory at $(pwd)"
else
echo $1 is not a directory
fi
';

Or use q:
print FILE q{#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
};

Or a heredoc:
print FILE <<'OUT';
#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
OUT

Comment: `Use of uninitialized value $1 in string` … also, `$(` is the real group ID of the process. Use a non-interpolating quote delimiter (`'...'`, `q{}`, `<<'OUT'`). Note: `$1` is the first argument in shell scripts.
Answer: This works:
open FILE , ">hello.sh" or die $!;
chmod 0755, "hello.sh";
print FILE "#!/bin/sh
echo Hello World!
";
close FILE;

generating a bash script


How do I force Anaconda's SCAP add-on to let me use a USB keyboard?

Question: The problem
I'm creating an RHEL 7.3 installation image with a custom kickstart file.
I can add this to my kickstart file to enable SCAP configuration during installation:
%addon org_fedora_oscap
content-type = scap-security-guide
profile = stig-rhel7-server-gui-upstream
%end

When I do, however, I end up with nousb in my kernel cmdline, which disables all USB interfaces, including keyboard and mouse.
(I've done the same thing before with an RHEL 7.2 image, and it "just works," so I know the basic approach is sound. But that's using an older and, apparently, less complete security profile.)
Now, I fully understand why: there's a rule that's specifically setting it. I need to "tailor" the rules so that the SCAP tool doesn't disable all my USB devices.
What I've figured out so far
According to Red Hat's kickstart documentation and the OSCAP Anaconda site, I can suspend this one rule by supplying my own tailoring file:

tailoring-path - Path to a tailoring file which should be used, given as a relative path in the archive.

So, I run scap-workbench, disable the affected rule, and save my changes as a tailoring.xml file

Then, I can add a line to the kickstart config, like this:
%addon org_fedora_oscap
content-type = scap-security-guide
profile = stig-rhel7-server-gui-upstream
tailoring-path = ssg-rhel7-ds-tailoring.xml
%end

Based on trial-and-error, I've also concluded that the tailoring.xml file has to be placed in /root/openscap_data (absolute paths absolutely don't work — you get a prominent show-stopping debugging prompt during installation).
What I can't figure out
Even after generating the tailoring file, I'm still getting a kernel with nousb when I do a fresh installation.

Am I really putting the tailoring.xml in the right place?
Is there a detailed log I can use to diagnose what the add-on is doing? (I've found only really basic information in /var/log/anaconda/journal.log.)
If the tailoring approach just fails for whatever reason, what is a clean and consistent way to apply a workaround for this issue, without throwing out the STIG auto-configuration altogether? (E.g. can I use another add-on module to clean up my kernel arguments after OSCAP breaks them?)
Answer: Based on this OpenShift blog post, you need to install some packages to have openSCAP log to syslog:
yum install html2text util-linux-ng

In terms of working around the issue itself, the check you mention basically does the following:
  sed -i "s/\(GRUB_CMDLINE_LINUX=\)\"\(.*\)\"/\1\"\2 nousb\"/" /etc/default/grub
bootloader
  /sbin/grubby --update-kernel=ALL --args="nousb"

So you can revert that particular rule's actions by removing nousb from the default grub options.
I can't, however, seem to find anything about why your tailoring is not working.
This post does however seem to report a similar issue to yours, and this RH solution - if you have access - might be of use (I do not have an account to view the solution itself, but its title is "Support for OpenSCAP tailoring in Satellite 6").
OpenSCAP's official guide on customiation does suggest you ensure you save your Work Bench customisations with:

File → Save customization only.

One small thing to note, too (from http://static.open-scap.org/scap-workbench-1.1/#_load_a_ready_made_customization_xccdf_tailoring_file_optional):

Only XCCDF 1.2 supports tailoring officially. The OpenSCAP project has an extension that allows tailoring files to be used with XCCDF 1.1 so SCAP Workbench supports that as well. The details are out of scope of this document but keep in mind that tailoring of an XCCDF 1.1 file might not work with scanners other than openscap.
Comment: Thanks! There are some useful leads here. You may be amused to learn that the RH solution is about three sentences, though; the first of which is "At the time of this writing, Satellite 6.1 does not support an OpenSCAP tailoring file." Gotta admire the moxy of sticking that behind a paywall. ;)
Answer: If you add a tailoring-path, you probably need to update the profile line
Defining tailoring-path doesn't automatically inject any new rules, it just adds another source to the search hierarchy. To actually use it, you need to invoke the "tailored" profile by name, instead of the original profile, e.g.:
%addon org_fedora_oscap
content-type = scap-security-guide
profile = stig-rhel7-server-gui-upstream-MYPROJECT-CUSTOMIZATIONS
tailoring-path = ssg-rhel7-ds-tailoring.xml
%end

The tailored profile name is the name Scap Workbench directs you to create when you save it. The "long form" is acceptable; you can just open the tailoring file with a text editor and copy it directly.


How to make a single instrument fill up a sound spectrum?

Question: I have an instrumental here (not particularly a fan of, but great reference for this question.)
This instrumental starts off with and contains a synth pluck with a simple melody. My interest in this synth pluck is how a single sound can fill out the sound spectrum all by itself.
What is the process behind achieving this in mixing? I suspect its a reverb with a long decay but i could be completely wrong.
How is it done?
Thank you!
Comment: I don't think the first sound does fill out the sound spectrum - it leaves a lot of space in the spectrum for other elements to come in around it. Perhaps the question is more how it sounds 'interesting' on its own?
Comment: Hiya, how's it going. *it wouldn't sound a fraction as wide...*  - Perhaps the relevant term is *soundstage*, rather than *spectrum*? 'Spectrum' is about the frequency content of a sound, which is actually quite restricted in this case.
Comment: It's nothing to do with gain-staging, it's how it fills the stereo field - similar yet different aspects of the sound are spread wide across the entire 'sound stage', the 'theatre of sound' you can create between a simple speaker pair. In this particular case it doesn't sound like the instrument itself is doing that, but the reverb is, which is how it appears to be pushed back behind the first dry vocal.
Comment: I think you should fix the question. It isn't about the _spectrum_ at all. If you want to fill the spectrum, you use noise.
Comment: Could well be the way the sound and the reverb are panned - which is probably where topo came in.
Comment: Hey again Topo. Well my logic regarding the sound is if i pull up a virtual instrument on my software, it wouldn't sound a fraction as wide so i would strongly suspect the sound has been altered to grasp a wider piece of the spectrum if maybe not in its entirety and im curious in how that's achieved. I think mixing may not be as popular on here as composition but I've received useful answers
Comment: Soundstage being gain staging? If that is the case that the contrast in a mix is so powerful thats pretty impressive. Thank you.
Answer: From the comments you seem to be asking not about the frequency spectrum, but about the stereo field.
Yes, this is probably done by adding pseudo-stereo information using a 'stereo reverb' plugin.
It conceivably COULD have been achieved by recording  the (marimba?) sound in a very reverberant room with stereo microphones, but I suspect it's a dry sample with artificial reverb applied.
Comment: Yes, it's doubtless a sample.  But a sample has to be originally created.  Maybe synthesized, maybe recorded.   Most marimba samples take pride in being recorded from a REAL marimba...
Comment: I don't think this was recorded with microphones lol. The grand grand majority of hip hop, pop and dance music producers depend solely on virtual instruments and by the texture of the sound i'm pretty sure it's from a virtual instrument too or synthesizer keyboard at the most. I think it could be reverb too. Thank you!
Answer: From my answer to your stereo reverb question

It's worth noting that (mono-in stereo-out) stereo reverb is one way
  to artificially create a stereo field from a mono input. Other
  stereoization methods include comb filtering with a delay on one of
  the stereo channels, complementary comb-shaped EQ curves for
  left/right, and special stereo chorus effects.

Here's an example of how to widen a sound with Ableton's stock chorus and reverb:


Show $\frac{1}{n}$ converges to $0$ using topological definition

Question: I need to use the following definition to show that:
$\frac{1}{n}$ converge to $0$ in $(\mathbb{R}, \mathcal{T}_{usual})$ and $(\mathbb{R}, \mathcal{T}_{lowerlimit})$
The defnition is:

Given $(X, \mathcal{T})$, $x_n \in X$ a sequence, $x_n \to x$ if $\forall U \in \mathcal{T}$, $x \in U$, there is $N \in \mathbb{N}$ s.t. $x_n \in U, \forall
 n \geq N$

I am having trouble producing the $N$

Show  $\frac{1}{n}$ converge to $0$ in $(\mathbb{R}, \mathcal{T}_{usual})$

Let $0 \in U, U \in \mathcal{T}_{usual}$. Since $\forall x \in U, \exists \delta > 0$ s.t. $B_\delta(x) \subseteq U$, therefore $0 \in B_\delta(0) \subseteq U$. Then let $x_N = \frac{1}{N} = \frac{\delta}{2} \implies N = \frac{2}{\delta}$, hence $x_n \in U, \forall n \geq N$
Here, I have no guarantee that $N \in \mathbb{N}$!!

Show  $\frac{1}{n}$ converge to $0$ in $(\mathbb{R}, \mathcal{T}_{lowerlimit})$

Let $0 \in U, U \in \mathcal{T}_{lowerlimit}$. Since $U = \bigcup\{[a,b)|a<b\}$, therefore there exists some $[a,b)$ such that $0 \in [a,b)$. Then let $x_N = \frac{1}{N} = \frac{|b-a|}{2} \implies N = \frac{2}{|b-a|}$, hence $x_n \in U, \forall n \geq N$
Again, no guarantee that $N \in \mathbb{N}$
How to fix these cases?
Comment: Take the ceiling
Comment: Say, $N\ge \frac 2{\delta}$ instead of equal to.  Then you can choose the samallest $N \in \mathbb N$ that meets the criteria.
Answer: You can take a natural number $N_0$ larger than the candidate real $N$. Larger $n$ only makes $\frac{1}{n}$ smaller anyway.
For the second one, it suffices to consider neighbourhoods of the form $[0,a)$, even (why?).
Answer: In $X$=$(\mathbb{R},\mathcal{T}_{usual})$:
Define $B_{r}(x)$ as the open ball with radius $r$ centered at $x$$\in$$X$.
We note that $B_{2}(0)$ contains ${(1/n)}_{n\in\mathbb{N}}$. Let $U\in\mathcal{T}_{usual}$ be a proper open subset of $\mathbb{R}$ containing $0$. Then there exists some open ball $B=B_{\epsilon}(0)$, $\epsilon>0$, such that $B\subseteq U$.
Hence, for all $n\geq N>\frac{1}{\epsilon}$, $x_{n}=\frac{1}{n}$$\in$$B$, and we are done.
For $X=(\mathbb{R},\mathcal{T}_{lowerlimit})$,the basis of the topology of $X$ has elements of the form $[x,y)$, so repeat as in the first case but observe that $1/n>0$ for all $n\in\mathbb{N}$.


What can cause delay in my worker thread Queue.get()?

Question: Note: This is closely related to my other topic here and here, but is an independent question and you needn't read them if you're not interested to..
I have some unexpected delays in processing items from the queue.  It seems to be related to the matplotlib GUI thread, because I can make the delay arbitrarily long by avoiding generating any GUI events, but for example if I create some mouse move events, I can get at the queue.  What is the cause of this delay and how to fix it?
# ~/repo/wim/mpl_q.py
import threading, Queue, time, random, sys

t0 = time.time()
t = lambda : time.time() - t0

def worker():
  while True:
    thing = queue.get()
    sys.stdout.write('({0}) hello {1}!\n'.format(t(), thing))
    queue.task_done()

queue = Queue.Queue()
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()

def say_hello(thing='world'):
  print '({0}) --> say_hello({1})'.format(t(), thing)
  queue.put(thing)

say_hello('world')
say_hello('cruel world')
say_hello('stack overflow')

import matplotlib.pyplot as plt
fig = plt.figure()

def event_handler(event):
  world = random.choice(['foo', 'bar', 'baz'])
  say_hello(world)

event_handler_ = lambda x: event_handler(x)
cid0 = fig.canvas.mpl_connect('key_press_event', event_handler)
cid1 = fig.canvas.mpl_connect('button_press_event', event_handler_)

plt.show()

Example of typical output , you can see the scripted items happen on time, but the user generated ones can come much later..
wim@wim-acer:~/repo/wim$ python mpl_q.py
(0.000166893005371) --> say_hello(world)
(0.000200986862183) --> say_hello(cruel world)
(0.000216960906982) hello world!
(0.000231027603149) --> say_hello(stack overflow)
(0.000247955322266) hello cruel world!
(0.00425505638123) hello stack overflow!
(7.80911588669) --> say_hello(foo)
(7.84842705727) hello foo!
(9.41998004913) --> say_hello(baz)
(11.4023530483) hello baz!
(14.3315930367) --> say_hello(foo)
(19.4317750931) hello foo!
(20.96124506) --> say_hello(bar)
(23.2277729511) --> say_hello(baz)
(23.2278220654) hello bar!
(29.0094120502) hello baz!

edit: I am using GTKAgg backend, and matplotlib version 1.1.0
Answer: I don't really know why, but the problem seems to go away if you declare matplotlib.use(backend) before importing pyplot:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

In an interactive session, the problem can also be avoided by turning on interactive mode:
import matplotlib.pyplot as plt
plt.ion()

Comment: I have noticed this aswell, actually because of your answer to my other question.. :)   however I don't much like the solution with matplotlib.use because it causes complications if matplotlib.pyplot has already been imported in an interactive session
Comment: @wim: In an interactive session, use `plt.ion()` instead.
Comment: `plt.ion()` makes `plt.show()` non-blocking, but it doesn't seem to have any effect on the delay issue
Comment: unutbu, do you know of any way to get the problem to go away with `GTKAgg` backend?
Comment: @wim: Hm. `plt.ion()` somehow fixes the delay issue for me. And I can't reproduce the GTKAgg backend issue either (though I did end up with get a different problem). I'm still using matplotlib version 0.99.0. Maybe that is the reason for the differences...


In drupal 7 how to add a link to a node which creates another node related to the previous being visible only if a user has not yet done so?

Question: I have a node #1 of content type A. If the user equals a certain role AND has not yet done the following, show a link within node#1 saying "create node of type B".
If the user clicks this link, he may create a new node of type B. Then, when looking at node#1 again, the link disappears (or changes), since the user has already created another node from within node#1.
If you would delete that last created node and visit node#1 again, you would again have the possibility to create a node of type B which would automatically be related to the respective node, in this case node#1.
How can you do that?
Answer: I can see couple of ways to do it.
1) add the module http://drupal.org/project/node_limit
2) Create a menu with node/add/contentA
3) add this block to the node of the type content A
4) to do the third step you would need to add alias to the content A nodes by following method
Setup a URL alias pattern for content A
Click on Configuration in the admin menu, and look for "URL Aliases".
One of the tabs is called "Patterns" - this is where you can adjust the automatic URL alias settings for your content. In the "Content Paths" section you'll see the default is set to "content[node:title]" -- just below that you'll want to set "Pattern for all Blog entry paths" to "contenta/[node:title]" and save your new configuration. This means all of your future Content A content will have URLs like: http://yoursite.com/contenta/your-contenta-title.
(Thanks to Jonathan Webb http://www.drupalgardens.com/content/block-not-showing)
That should do it.
This assumes that the user can only add one node.
EDIT : An update with the requirement mentioned in the comment
Instead of step 1 and 2 do the following
1) Enable php filter
2) Create a view of the type block with just one field may be nid of the node. Remove the label. Rewrite the out put to some thing like  so that nothing is displayed.
3) Add contextual filter of the type content:author and select provide default value and from the drop down select User ID from logged in user
4) In the header section add a field of the type gloal:textarea click on "Display even if view has no result" so that it would be displayed even if there is no result.
5) Select PHP code as the filter and paste the following code with the changes that suite your requirement such as changing the url to the one that adds your content type.
<?php
  $view = views_get_current_view();

   if (!count($view->result))
   {
       print "Add Node";
   }
?>

Follow step 3 and 4 to add the block to the node.
Comment: Thats not exactly what i was searching for. Every user may create a node of type b for each existing node of type a.
Comment: So if there is a user x and there are two contents of the type a then user x should be able to create 1 content of the type b for each of the existing 2 content 1 type.
Comment: exactly. sorry if i have not been clear before. but the goal is to have user group A to create nodes of type A. users of type B may "answer" those nodes each by creating a node of type B (response/answer) once per node of type A. so a node of type A can have several "answers" of type B, but each user B can only create one node B for each node of type A
Comment: I have edited the answer to make the changes you mentioned. Hope that helps
Comment: Thanks so much for your response! That might work but wouldnt it be nicer to control that model data from within a module instead of doing that in the view layer?
Comment: Yes it is always better to create a module. or you could do it in the node.tpl as well. Could call a db query to get the node with the content type and current user and then do the required thing from there. I think the best place to do it would be node.tpl.php
Comment: I dont think this is going to work in whole. I need to make sure that the logged in user has not yet created a node of type B to the currently viewed node of type A. I need to be able to see all nodes of type B which have been created, list those who are referenced to a node of type A and so on. I guess this will be a little more complex than views :)
Comment: Did the solution I mentioned with view work for you?


Comcast Business Gatway cg3000dcr kills VPN connections after about 3mb of transfer

Question: I use an L2TP/IPSEC vpn client behind a CG3000DCR Comcast Business Gateway Router, and while it establishes a connection initially, after about 3mb of data transfer, it stalls out, doesn't do any more transfer, but stays connected.
This has happened since the new Comcast router was installed. Neither the VPN client nor server (in TX) have changed. The connection works fine from my Comcast home connection without issue.
I've seen various solutions, most of which point to trying to talk Comcast into giving me a different modem. This one apparently has serious issues, and the different brand modems are apparently scarce.
I've tried the following as a workaround:

Set up port forwarding in the Comcast router for explicit ports that L2TP requires. No change
Put my PC in a DMZ, and try the same thing. After doing 3mb or so of transfers, it stalls out.

Are there any other workarounds I can use to get a reliable VPN connection while I fight with Comcast on this? Note: we have Static IP.
Comment: The irony here is that _all_ of the "business class" cable modem/router combos that I've seen for the past several years have been complete junk. I've had much better reliability with a "consumer grade" Surfboard and my own routers.
Comment: You can shed some light on exactly what is happening by running wireshark/tcpdump to view the VPN traffic (include icmp/icmpv6 in your filters) to see what is happening when the connection dies. Sometimes routers/firewalls can be sending back a useful message that goes unnoticed by software but can be seen within the ICMP packet(s) sent by the device.
Comment: See if firmware updates are available for the comcast router.  I have seen some cable modem issues that cause similar behavior that were resolved in newer firmware.
Comment: I know of no current settings on Comcast business modems (SBC or otherwise) that rate limits a connection, does inherent port filtering, or has any kind of timeout like that. Could this be another issue (protocol timeout on the VPN, packet loss, etc). A few missed keepalives can drop a VPN connection. Are there any relevant logs to show what you're seeing (vpn disconnect, timeout, auth errors?). So many different things can cause this, even an upstream router issue or BGP/OSPF/RIP protocol change
Comment: I've got wireshark installed, but don't know much about a trace. What do I need to include in the trace?
Comment: Just buy a proper WAN router and put your Comcast box in bridged mode to use it as a L1 media converter. Seriously, the old "crappy" FVS3xx Netgear stuff worked better than most of the trash from the ISPs does now. And my Pro-sumer Buffalo router with DD-WRT even support advanced concepts like VLAN tagging. You do know about the backdoors that ISPs put in their routers, right?
Answer: What about putting it in bridged mode, and using your own router to see if the problem still happens. My guess some kind of problem in the routing side of things, persistent NAT? Anyway, just about no one that I know uses carrier provided gear, mainly for security and manageability concerns. Even if you get something else, you should consider something business class, like a Meraki or similar.
Good luck!
Comment: +1 for that crucial observation about not using carrier-provided gear.  It's your infrastructure, make sure it's your kit that powers / enables / provisions / guards it.
Comment: We have a static IP, so we'd have to change that to go into bridged. Also, you have to have a Comcast engineer change to bridged, because the config is locked down to only have a few options available to the client.
I also understand that at any time, a Comcast account person can switch the bridged thing off, since it's not "standard."

I like your idea of another business class modem, but the company I'm supporting is not technical by nature, and generally counts on Comcast support.
Comment: Usually in bridged, you keep your address, it's just assigned to the router instead of the modem/router combo. I would say who cares about the Comcast Engineer, that's what they are paid to do, but you seem to have some aversion to that. If you're going to run a network, you may do well to care less how many people you have to involve to make it right. Nature of the beast. Finally, Comcast support is failing them, which is why you're here. Most small business I know would rather pay a little every month for a managed firewall through an MSP than go with their ISP. Con.t next
Comment: Anyway, even if it was just for a few days, putting it into bridged would have pinpoint the problem. Feel free to mail me if you want to know more, but I feel this is going to be the general consensus around these parts. Good Luck.
Comment: It's a difficult situation b/c the Comcast guy (who is here now) doesn't seem too cluefull. And the person who runs this shop (it's a coworking space; i'm just the only member who connects to a workplace through a vpn) is non-technical.
Comment: All the more reason to make the case for a managed firewall from an MSP if you ask me. If the one guy onsite that manages the network needs help, the business there should look at the value added by having someone knowledgeable who's able to give you a hand. Those ISP guys never really have a clue, and if they are going to continue to rely on them, that's what they get. This should fall on whomever the landlord is, assuming internet is provided as a part of the space. This should be an understood part of creating a co-working space, and should also involve QoS, Bandwidth mgmt. and shaping, etc
Answer: It may be caused by a router or your CG3000DCR gateway dropping a packet since this one is too large for him. At this time, the dropping equipment shoud send a notification but sometimes this notification can be dropped too, causing the transfer to stall.
To avoid this, you can try to :

set up a reduce MTU on your L2TP/IPSEC client
reduce the MTU directly on your network interface configuration

Hope this help.


Mixed-effect Binomial Regression - Interprete estimates of model and anova output for interaction term

Question: I use R for a mixed-effect binomial regression (GLM) to test for a difference in whether people voted (coded as 0/1) in an election based on race (6 categories) and religion (3 categories), see structure of dataset and output below.
Structure of dataset:

mixed-effect Binomial regression:

ANOVA - Test predictors relative to the full model:

Question: as shown in the output for the model there are some statistically significant interaction between race and religion. However, as I control the significance of the interaction term relative to the full model by performing an analysis of variance for the interaction term the overall effect of the interaction  seems not to be statistically significant. What is the correct way to interpret these results? Can there be statistically significant interactions between races/religions although the ANOVA shoes there are the interaction term is not statistically significant?
Answer: This is more or less the same problem as finding significant differences in a post hoc analysis, but not the omnibus test in a regular ANOVA.
The likelihood ratio test shows you that adding the interaction term does not significantly improve the model. What you should do with that information depends on your goal: If you want to compare combinations of race and religion rather than estimate their overall effect, then this is the right model. If you are trying to find a parsimonious model for voting, then you could leave out the interaction.
Answer: I agree with the answer by Frans. This kind of thing can easily happen with interactions involving factors with several levels, or in a simple ANOVA with a factor with several levels. The overall effect of the variable may not be "significant" while contrasts between some of the levels might be. This is completely normal. One school of thought says that if the overall level of significance for the variable does not meet the threshold then we should not look at individual contrasts. I don't really subscribe to that approach. As mentioned by Frans, a lot depends on the use for the model. If you have reason to believe that there should be an interaction, then leave it in and do not be too concerned about p-values reaching whatever threshold you choose.


Subnetting into 6 CIDR/24 network and 2 CIDR/27 networks?

Question: I am revising some questions for an exam and one of the questions was provide the ip numbers and a diagram for a company which has 3 branches. Paris/Berlin/Cairo (random locations I know) Now I belive I have figured out the answer but I would appreciate someone checking as my brain is fried and I think if this answer is wrong I won't be able to see that's its wrong.
You have 3 routers which means 6 networks All should be /24, the IP addresses should resemble 10.12."network number"."host number" ie 10.12.59.1, so that its a /24 that means the mask is going to be 255.255.255.0,  so my host ranges are, not including broadcast addresses

1-30
33-62
65-94
97-126
129-158
161-190
193-222
225-254

So I could use 6 of them for my 6 networks, 1 for each of the branches and 1 for the 3 networks joining the branches.
The Berlin branch network is extended with 2 additional VLANS. These networks should be sub-netted from 10.12.59.0 with a /27 structure. Now this is where I start to know I am weak in my knowledge. the mask for a CIDR/27 is 255.255.255.224 but I cant figure out how to implment a /27 numbering within a /24 network. Can anyone explain please?
Comment: @spacemanspiff - if he has a doubt or hesitation, would you prefer a teacher not ask for someone to double check? After working with teachers, I've learned their dirty secret...they're not infallible. :-)
Comment: You're the teacher and you need help with subnetting?
Answer: This is done with Variable Length Subnetting.
To do VLSN we just look at all our networks and arrange them in size. First the big ones then the smaller ones. You already have your /24 networks so to correct your subnets:
if you have 10.12.0.0 and you need 6 /24 networks and 2 /27, then we need to first accommodate the /24 networks:
So we get:
<code> Subnet 1:
10.12.0.0 (networkaddress)
10.12.0.1 (first host)
10.12.0.254 (last host)
10.12.0.255 (broadcast address)
Subnet 2:
10.12.1.0 (networkaddress)
10.12.1.1 (first host)
10.12.1.254 (last host)
10.12.1.255 (broadcast address)
Subnet 3:
10.12.2.0 (networkaddress)
10.12.2.1 (first host)
10.12.2.254 (last host)
10.12.2.255 (broadcast address)
Subnet 4:
10.12.3.0 (networkaddress)
10.12.3.1 (first host)
10.12.3.254 (last host)
10.12.3.255 (broadcast address)
Subnet 5:
10.12.4.0 (networkaddress)
10.12.4.1 (first host)
10.12.4.254 (last host)
10.12.4.255 (broadcast address)
Subnet 6:
10.12.5.0 (networkaddress)
10.12.5.1 (first host)
10.12.5.254 (last host)
10.12.5.255 (broadcast address)
</code>
Now we need to accommodate two /27 networks in one more /24 networks. Let's first see if two /27  fit into a /24:
<code>/27 = 32 IP's (1 network, 30 hosts, 1 broadcast).
/24 = 256 IP's (1 network, 254 hosts, 1 broadcast).
</code>
So we can fit in 8 /27 networks basically, but we only need two, our network address to put the /27 in is 10.12.6.0. So now you start as you would do normally:
<code>Subnet 7:
10.12.6.0 (networkaddress)
10.12.6.1 (first host)
10.12.6.30 (last host)
10.12.6.31 (broadcast address)
Subnet 8:
10.12.6.32 (network address)
10.12.6.33 (first host)
10.12.6.62 (last host)
10.12.6.63 (network address)
</code>
Good luck with your exam :)
Comment: I did...it's basic math you have a /24 network (10.12.6.0/24) you just  look how many times a /27 can fit in there (8 times 8*32=256). So you just subnet within your /24, starting with the /24 first ip. I mean it's not different from subnetting a /24, because that can basically be a subnet within a /23.
Comment: Sorry Can you just explain how you can fit 4 x /27 networks into a /24 I get confused combining the 2 - Thanks


How do browsers discover username and password on all web pages?

Question: How do browsers discover username and password on all web pages?
What is script that is used for determine username textbox and password for saving them?
Like search for element with type="password"?
Comment: As far as I know, this is just assumption made by browsers based on `` where name can be well known names like `user`, `username`, `email` etc. If you put in your web application `` it won't distinguish it from any other form and thus won't treat it as username/password form. Other assumptions could be taken into account like `type` of input etc. You may test it your self with simple web application form (i'm not sure that it will be testable with static local html).
Answer: Fire fox use from this script:
enter link description here


C#: comctl32.dll version 6 in debugger

Question: I'm using the WindowsAPICodePack for TaskDialog. When I try to show the dialog it says that it needs to load version 6 of comctl32.dll. So I added version 6 to the app.manifest and tried running it. Still no luck. I went to the Debug folder and ran the program without Visual Studio and it works fine. I'm guessing that Visual Studio isn't using the manifest file... I was wondering if there was a way to make it do this.
Comment: Could we add the exact error message into the question so that Google leads here for it? This had the correct answer for me but I only found vague mentions of it in other threads and had to eventually search for "EnableThemingInScope" to get here. Here's the error messages for Google's crawlers: "TaskDialog feature needs to load version 6 of comctl32.dll but a different version is current loaded in memory" with inner exception "Unable to find an entry point named 'TaskDialogIndirect' in DLL 'Comctl32.dll'."
Answer: Robpol86, your code is throwing SEHExceptions, because the signatures for ActivateActCtx and DeactivateActCtx are not correct. You have to use UIntPtr instead of uint for the lpCookie.
Therefore, the correct code for EnableThemingInScope.cs would be:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;

namespace Microsoft.WindowsAPICodePack.Dialogs
{
    /// http://support.microsoft.com/kb/830033
    /// <devdoc>
    ///     This class is intended to use with the C# 'using' statement in
    ///     to activate an activation context for turning on visual theming at
    ///     the beginning of a scope, and have it automatically deactivated
    ///     when the scope is exited.
    /// </devdoc>

    [SuppressUnmanagedCodeSecurity]
    internal class EnableThemingInScope : IDisposable
    {
        // Private data
        private UIntPtr cookie;
        private static ACTCTX enableThemingActivationContext;
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
        private static IntPtr hActCtx;
        private static bool contextCreationSucceeded = false;

        public EnableThemingInScope(bool enable)
        {
            cookie = UIntPtr.Zero;
            if (enable && OSFeature.Feature.IsPresent(OSFeature.Themes))
            {
                if (EnsureActivateContextCreated())
                {
                    if (!ActivateActCtx(hActCtx, out cookie))
                    {
                        // Be sure cookie always zero if activation failed
                        cookie = UIntPtr.Zero;
                    }
                }
            }
        }

        ~EnableThemingInScope()
        {
            Dispose();
        }

        void IDisposable.Dispose()
        {
            Dispose();
            GC.SuppressFinalize(this);
        }

        private void Dispose()
        {
            if (cookie != UIntPtr.Zero)
            {
                try
                {
                    if (DeactivateActCtx(0, cookie))
                    {
                        // deactivation succeeded...
                        cookie = UIntPtr.Zero;
                    }
                }
                catch (SEHException)
                {
                    //Hopefully solved this exception
                }
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")]
        private static bool EnsureActivateContextCreated()
        {
            lock (typeof(EnableThemingInScope))
            {
                if (!contextCreationSucceeded)
                {
                    // Pull manifest from the .NET Framework install
                    // directory

                    string assemblyLoc = null;

                    FileIOPermission fiop = new FileIOPermission(PermissionState.None);
                    fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                    fiop.Assert();
                    try
                    {
                        assemblyLoc = typeof(Object).Assembly.Location;
                    }
                    finally
                    {
                        CodeAccessPermission.RevertAssert();
                    }

                    string manifestLoc = null;
                    string installDir = null;
                    if (assemblyLoc != null)
                    {
                        installDir = Path.GetDirectoryName(assemblyLoc);
                        const string manifestName = "XPThemes.manifest";
                        manifestLoc = Path.Combine(installDir, manifestName);
                    }

                    if (manifestLoc != null && installDir != null)
                    {
                        enableThemingActivationContext = new ACTCTX();
                        enableThemingActivationContext.cbSize = Marshal.SizeOf(typeof(ACTCTX));
                        enableThemingActivationContext.lpSource = manifestLoc;

                        // Set the lpAssemblyDirectory to the install
                        // directory to prevent Win32 Side by Side from
                        // looking for comctl32 in the application
                        // directory, which could cause a bogus dll to be
                        // placed there and open a security hole.
                        enableThemingActivationContext.lpAssemblyDirectory = installDir;
                        enableThemingActivationContext.dwFlags = ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

                        // Note this will fail gracefully if file specified
                        // by manifestLoc doesn't exist.
                        hActCtx = CreateActCtx(ref enableThemingActivationContext);
                        contextCreationSucceeded = (hActCtx != new IntPtr(-1));
                    }
                }

                // If we return false, we'll try again on the next call into
                // EnsureActivateContextCreated(), which is fine.
                return contextCreationSucceeded;
            }
        }

        // All the pinvoke goo...
        [DllImport("Kernel32.dll")]
        private extern static IntPtr CreateActCtx(ref ACTCTX actctx);
        [DllImport("Kernel32.dll")]
        private extern static bool ActivateActCtx(IntPtr hActCtx, out UIntPtr lpCookie);
        [DllImport("Kernel32.dll")]
        private extern static bool DeactivateActCtx(uint dwFlags, UIntPtr lpCookie);

        private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;

        private struct ACTCTX
        {
            public int cbSize;
            public uint dwFlags;
            public string lpSource;
            public ushort wProcessorArchitecture;
            public ushort wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
        }
    }
}

Comment: Cheers, this is the correct answer. No need to change manifest with this.
Comment: +1 For correct answer. For future reference I had a similar broken uint cookie implementation from this msdn knowledge base article: https://support.microsoft.com/en-us/kb/830033 just for clarity: I could create the scope but then I got an SEH Exception on DeactivateActCtx. further debugging revealed that it was error code 6, which is ERROR_INVALID_HANDLE as the cookie could not be used to deactivate the context properly due its wrong type.
Comment: Thanks! I was having trouble with comctl32.dll when publishing ClickOnce, and this solved it
Answer: I recently ran into this problem when debugging code with the TaskDialogDemo in the CodePack. This is how I kind of fixed it. The problem with using this is if I open two or three dialogs it throws an SEHException, which I haven't figured out how to fix. So buyer beware.
Add Core\Interop\TaskDialogs\EnableThemingInScope.cs:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;

namespace Microsoft.WindowsAPICodePack.Dialogs {
    /// http://support.microsoft.com/kb/830033
    /// <devdoc>
    ///     This class is intended to use with the C# 'using' statement in
    ///     to activate an activation context for turning on visual theming at
    ///     the beginning of a scope, and have it automatically deactivated
    ///     when the scope is exited.
    /// </devdoc>

    [SuppressUnmanagedCodeSecurity]
    internal class EnableThemingInScope : IDisposable {
        // Private data
        private uint cookie;
        private static ACTCTX enableThemingActivationContext;
        [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources" )]
        private static IntPtr hActCtx;
        private static bool contextCreationSucceeded = false;

        public EnableThemingInScope( bool enable ) {
            cookie = 0;
            if ( enable && OSFeature.Feature.IsPresent( OSFeature.Themes ) ) {
                if ( EnsureActivateContextCreated() ) {
                    if ( !ActivateActCtx( hActCtx, out cookie ) ) {
                        // Be sure cookie always zero if activation failed
                        cookie = 0;
                    }
                }
            }
        }

        ~EnableThemingInScope() {
            Dispose();
        }

        void IDisposable.Dispose() {
            Dispose();
            GC.SuppressFinalize( this );
        }

        private void Dispose() {
            if ( cookie != 0 ) {
                try {
                    if ( DeactivateActCtx( 0, cookie ) ) {
                        // deactivation succeeded...
                        cookie = 0;
                    }
                } catch ( SEHException ) {
                    // Robpol86: I don't know how to fix this!
                }
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity" )]
        private static bool EnsureActivateContextCreated() {
            lock ( typeof( EnableThemingInScope ) ) {
                if ( !contextCreationSucceeded ) {
                    // Pull manifest from the .NET Framework install
                    // directory

                    string assemblyLoc = null;

                    FileIOPermission fiop = new FileIOPermission( PermissionState.None );
                    fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                    fiop.Assert();
                    try {
                        assemblyLoc = typeof( Object ).Assembly.Location;
                    } finally {
                        CodeAccessPermission.RevertAssert();
                    }

                    string manifestLoc = null;
                    string installDir = null;
                    if ( assemblyLoc != null ) {
                        installDir = Path.GetDirectoryName( assemblyLoc );
                        const string manifestName = "XPThemes.manifest";
                        manifestLoc = Path.Combine( installDir, manifestName );
                    }

                    if ( manifestLoc != null && installDir != null ) {
                        enableThemingActivationContext = new ACTCTX();
                        enableThemingActivationContext.cbSize = Marshal.SizeOf( typeof( ACTCTX ) );
                        enableThemingActivationContext.lpSource = manifestLoc;

                        // Set the lpAssemblyDirectory to the install
                        // directory to prevent Win32 Side by Side from
                        // looking for comctl32 in the application
                        // directory, which could cause a bogus dll to be
                        // placed there and open a security hole.
                        enableThemingActivationContext.lpAssemblyDirectory = installDir;
                        enableThemingActivationContext.dwFlags = ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

                        // Note this will fail gracefully if file specified
                        // by manifestLoc doesn't exist.
                        hActCtx = CreateActCtx( ref enableThemingActivationContext );
                        contextCreationSucceeded = (hActCtx != new IntPtr( -1 ));
                    }
                }

                // If we return false, we'll try again on the next call into
                // EnsureActivateContextCreated(), which is fine.
                return contextCreationSucceeded;
            }
        }

        // All the pinvoke goo...
        [DllImport( "Kernel32.dll" )]
        private extern static IntPtr CreateActCtx( ref ACTCTX actctx );
        [DllImport( "Kernel32.dll" )]
        private extern static bool ActivateActCtx( IntPtr hActCtx, out uint lpCookie );
        [DllImport( "Kernel32.dll" )]
        private extern static bool DeactivateActCtx( uint dwFlags, uint lpCookie );

        private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;

        private struct ACTCTX {
            public int cbSize;
            public uint dwFlags;
            public string lpSource;
            public ushort wProcessorArchitecture;
            public ushort wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
        }
    }
}

Then in Core\Interop\TaskDialogs\NativeTaskDialog.cs on line 93 (above HResult hresult = TaskDialogNativeMethods.TaskDialogIndirect) make the section look like this (in the end you will have three new lines):
// Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
HResult hresult;
using ( new EnableThemingInScope( true ) ) {
    hresult = TaskDialogNativeMethods.TaskDialogIndirect(
        nativeDialogConfig,
        out selectedButtonId,
        out selectedRadioButtonId,
        out checkBoxChecked );
}

Answer: This page describes how to add a custom manifest to your project in order to tell Windows to load the new  comctl32.dll (version 6.0):

Setting the correct manifest version

Does your manifest have the right dependency on comctl32.dll? Did you embed the created manifest?
Answer: I have the same issue with Visual Studio in Debug mode. So far I haven't found a workaround, it works fine in Release mode.

C#: comctl32.dll version 6 in debugger


How many integer solutions of $x_1$ + $x_2$ + $x_3$ + $x_4$ = 28 are there with

Question: How many integer solutions of $x_1$ + $x_2$ + $x_3$ + $x_4$ = 28 are there with
(a) 0 ≤ $x_i$ ≤ 12?
(b) −10 ≤ $x_i$ ≤ 20?
(c) 0 ≤ $x_i$, $x_1$ ≤ 6, $x_2$ ≤ 10, $x_3$ ≤ 15, $x_4$ ≤ 21?
I have tried.
a) To count the compliment value, so (31 choose 3) -  (15 choose 3)
b) Not quite sure where to begin
c) (31 choose 3)-(24 choose 3)-(18 choose 3)- (13 choose 3)- (9 choose 3)
Comment: What have you tried?
Comment: Hey, this site isn't used to give you the answers, we're here to help you work them out. You're more likely to get help if you have showed what you have attempted! Edit the post with your attempt and someone may help
Answer: Hint: Use principle of inclusion and exclusion. First you can find no of solutions corresponding to only the lower bound. Then you can subtract from this considering the lower bound to be one plus the upper bound.
That is, if you want $b\leq x_i\leq a$, solve independently for $b\leq x_i$ and subtract from this the cases when $a+1\leq x_i$
(You may also use generating functions but that might be tough since the upper limits are not same for all of the $x_i$).


Is $Y - E[Y|X]$ independent from $X$?

Question: For any two random variables $X$ and $Y$, is $Y - E[Y|X]$ independent from $X$? Intuitively I think it should be the case, since conditioning should include all the aspects of $X$ which are tangled with $Y$.
Answer: Those are always uncorrelated, indeed
$$ Cov(X,Y - \mathbb E[Y|X]) = Cov(X,Y) - Cov(X,\mathbb E[Y|X]) $$
Rewritting as expectations and using tower property and $X$ measurability of $X$, we get $$Cov(X,Y - \mathbb E[Y|X])= \mathbb E[XY] - \mathbb E[X]\mathbb E[Y] - \mathbb E[X\mathbb E[Y|X]] + \mathbb E[X]\mathbb E[\mathbb E[Y|X]]=0$$
But taking $X \sim \mathcal N(0,1)$, $\varepsilon = \pm 1$ with probability $\frac{1}{2}$ independent of $X$ and $Y=\varepsilon X$, you'll get $\mathbb E[Y|X] = 0$ almost surely, but $X$ and $Y$ are not independent (consider $X \in (0,1) , Y \in (1,2)$)
Answer: Suppose $Y \sim U(-1,1)$ and $X=Y^2$ then $E[Y \mid X] \equiv 0$, but $Y$ and $X$ are not themselves independent.
What is true is that $X$ and $Y-E[Y \mid X]$ are uncorrelated.
By the way, one can cook up a large family of examples just like this by considering any strictly increasing function $f : [0,\infty) \to \mathbb{R}$ (which are automatically Borel measurable), essentially any $Y$ with symmetric distribution about $0$, and $X=f(|Y|)$. (I use the word "essentially" because one must of course assume that $E[Y]$ exists.)

Is $Y - E[Y|X]$ independent from $X$?