Where can I find a sample for jQuery Pagination with AJAX for ASP.NET?

Question: I'm searching a clutterless way to paginate data with JQuery and Ajax on a ASP.net website.
I'm trying to make it work similiar to this, but it's not working because there's something wrong on javascript, but I can't find out how to fix it. I actually don't like the results so far, it's too complicate to maintain this code, don't you think?
The question: is there any clutterless way to do the same, using JQuery and Ajax for ASP.NET?
Below I'm sharing some code:
I've got a WebMethod on aspx page code-behind for bringing me sample data:
[WebMethod]
public static string GetEmployees(int pageIndex)
{
    JavaScriptSerializer serial = new JavaScriptSerializer();
    StringBuilder sb = new StringBuilder("[");
    serial.Serialize(new { Id = 1, Name = "Fred G. Aandahl" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 2, Name = "Watkins Moorman Abbitt" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 3, Name = "Amos Abbott" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 4, Name = "Jo Abbott" }, sb); sb.Append(",");
    //more lines here...
    sb.Append("]");
    return sb.ToString();
}

here's the ASPX page:

<form id="form1" runat="server">

Members

                Id	Name

                0	Sample

</form>

<form name="paginationoptions">

Items<input type="text" value="5" name="items_per_page" id="items_per_page" class="numeric"/>

Total links<input type="text" value="10" name="num_display_entries" id="num_display_entries" class="numeric"/>

Start /End point<input type="text" value="2" name="num_edge_entries" id="num_edge_entries" class="numeric"/>

Previous label<input type="text" value="Prev" name="prev_text" id="prev_text"/>

Next label<input type="text" value="Next" name="next_text" id="next_text"/>

    <input type="button" id="setoptions" value="Aceptar" />
</form>

The default.js
// This file demonstrates the different options of the pagination plugin
// It also demonstrates how to use a JavaScript data structure to
// generate the paginated content and how to display more than one
// item per page with items_per_page.
var emps;
/**
* Callback function that displays the content.
*
* Gets called every time the user clicks on a pagination link.
*
* @param {int}page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object
*/
function pageselectCallback(page_index, jq) {

    //read data for pagination from webmethod GetEmployees

    var data = '{"pageIndex":' + page_index + '}';
    $.ajax({ type: 'Post',
        url: 'Default.aspx/GetEmployees',
        data: data,
        contentType: "application/json;charset=utf-8",
        dataType: 'json',
        success: function(msg) {
            emps = eval(msg.d);

            $.each($('#Searchresult tr:gt(0)'), function(i, n) {
                $('#Searchresult')[0].deleteRow(n.rowIndex);
            });

            // Get number of elements per pagionation page from form
            var items_per_page = $('#items_per_page').val();
            var max_elem = Math.min((page_index + 1) * items_per_page, emps.length);
            var newcontent = '';
            for (var i = page_index * items_per_page; i < max_elem; i++) {

                var emp = emps[i];
                newcontent += '
' + emp.Id + '	' + emp.Name +     '
';
            }

            // Replace old content with new content
            $('#Searchresult').html(newcontent);

            //can't make it work
            //var optInit = { callback: pageselectCallback }; // getOptionsFromForm();
            //$("#Pagination").pagination(emps != null ? emps.length : 0, optInit);

        },
        error: function(msg) {
            alert("error:" + msg.statusText);
        }
    });

    // Prevent click eventpropagation
    return true;}

// The form contains fields for many pagiantion optiosn so you can
// quickly see the resuluts of the different options.
// This function creates an option object for the pagination function.
// This will be be unnecessary in your application where you just set
// the options once.
function getOptionsFromForm() {
    var opt = { callback: pageselectCallback };
    // Collect options from the text fields - the fields are named like their option     counterparts
    $("input:text").each(function() {
        opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) :     this.value;
    });
    // Avoid html injections in this demo
    var htmlspecialchars = { "&": "&", "<": "<", ">": ">", '"': """ }
    $.each(htmlspecialchars, function(k, v) {
        opt.prev_text = opt.prev_text.replace(k, v);
        opt.next_text = opt.next_text.replace(k, v);
    })
    return opt;
}

// When document has loaded, initialize pagination and form
$(document).ready(function() {
    // Create pagination element with options from form
    var optInit = getOptionsFromForm();
    $("#Pagination").pagination(emps!=null?emps.length:0, optInit);

    // Event Handler for for button
    $("#setoptions").click(function() {
        var opt = getOptionsFromForm();
        // Re-create pagination content with new parameters
        $("#Pagination").pagination(emps != null ? emps.length : 0, opt);
    });

});

Answer: I'd like to share my approach. Bear in mind that I have no knowledge of ASP.NET, but I think these steps will work regardless the language is.
First I create a page that work without JavaScript enabled. The pagination will be a link to current page with page number passed in either URI segment or in a get parameter. This way, the page is still usable without JavaScript enabled in the browser.
Next step is to add a progressive enhancement to those who have JavaScript enabled in the browser. I add a simple if in both controller and the view to determine if the request is a normal request or AJAX request. If it a normal request, serve the page completely. If it an AJAX request, only give part of the page, in this case the table or list part.
The jQuery code to change pagination into AJAX will be like this:
jQuery(function($){
  $(".pagination").click(function(){
    //determine the URL
    var url = $(this).attr("href");
    $.get(url,
      { nbRandom: Math.random() },
      function(data){
        $("#container").html(data);
      });
  });
});

The code above will replace the content of
 with the AJAX response (it will be contain only table part).
Remember to use GET if it will only fetch the data, and use POST if the request will change something (add/edit, delete, login, etc). nbRandom in the parameter is just a hack to prevent caching in IE. It use a parameter name that not used in the server side page.
This is my way to implement AJAX pagination in my application. I hope you can get the concept and implement your own.


How many different casts are possible if $6$ actors apply for $3$ unfilled male roles in a play given that Tom is selected and Joe is not?

Question: Questions There are 3 unfilled male roles in a play, 6 actors including Tom and Joe are auditioning for the
roles, how many different casts including Tom but not Joe?
I thought that since Tom is in and not Joe, the correct equation would be to just do $C_4^2$ since there is 2 spots left with 4 people available. However, it's saying that the answer is 36. Can someone please explain?
Answer: Tom has one of the three roles, and Joe does not, leaving 4 others to vie for 2 remaining roles, so there are ${4 \choose 2}=6$ different ways to complete the set of three persons that get a role.
Assuming the roles are different, there are $3!=6$ ways to assign the $3$ roles to those $3$ people, so that gives a total of $6*6=36$ different casts.
Answer: Tom can select his rôle in $3$ ways. The second rôle can then be casted in four ways, since Tom is out, and the third rôle in three ways. This gives $3\cdot 4\cdot 3=36$ possible castings.


Alterar url das páginas com ajax e carregar em outro browser

Question: Estou com o seguinte problema, estou desenvolvendo uma aplicação web em java e gostaria de saber como faço para alterar a URL de uma página quando clico em um link do menu. Por exemplo:
Acesso um site www.exemplo.com.br esse é o link da principal e lá tem um outro link contato, quando eu clicar nele, gostaria que ficasse www.exemplo.com.br/contato. Além disso, queria poder copiar essa URL e abrir em um outro browser e ir direto para contato.
Um exemplo disso é o Gmail, quando clicamos para ler um email a url altera e se fizermos um copy past em outro browser vai direto para o email.
É possível fazer isso como ajax ? Se não for qual seria a melhor opção ?
Comment: Isso na verdade é uma mistura de History API e roteamento. Não tenho conhecimento se é possível fazer isso em Java. Ou você esta se referindo a Javascript?
Comment: Em javascript se é possível. Eu consigo carregar o conteúdo que eu quero em um div, mas queria fazer esse esquema da url como descrevi em cima ou senão qual a melhor forma pra se fazer isso ?
Comment: estás a usar Java ou JavaScript?
Comment: Neste caso, atualize sua questão. Java e Javascript são duas coisas completamente diferente, apesar do nome.
Comment: Estou utilizando javascript
Answer: Como citou que está utilizando jQuery, recomendo o plugin da History API:
History
Caso não deseje usar um plugin, recomendo este artigo que trata em detalhes como trabalhar com a API:
history.pushState and jQuery
O principal método desta API é o history.pushState. Ele pede 3 argumentos, embora o segundo não seja utilizado em alguns (todos?) browsers.
O primeiro argumento, é um objeto Javascript associado com o novo estado da aplicação. Este objeto é parâmetro do evento popstate, disparado quando um novo estado é navegado.
O segundo é o título do novo estado.
O terceiro é a URL do novo estado. Esta URL pode ser relativa ou absoluta e deve estar no mesmo domínio. O browser não irá executar uma chamada HTTP para este endereço, embora no caso da reinicialização do browser, ela pode ser chamada, e neste caso, sua aplicação deve tratar.
O evento popstate, ao contrário do que o nome sugere, não é disparado quando um estado é removido, e sim quando o estado do browser é alterado. Como dito, este evento possui um único parâmetro, que é o objeto associado com o estado.
Veja mais sobre esta API na documentação da Mozilla: Manipulating the browser history.
Como esta utilizando jQuery, recomendo utilizar um plugin, ao invés de gastar tempo reinventando a roda.
Comment: History API, com essa api eu consigo copiar a url e passar por exemplo para outra pessoa acessar, ou seja, seguindo aquele mesmo princípio do gmail ?
Comment: Sim, ela fornece os recursos necessários para isto. O próprio Gmail utiliza ela (é a defacto API para isto).


How to add groups of files?

Question: I am trying to add the shareKit files like in the photo:

...but Xcode will only let me do the drag and drop only for single files! How can I solve this?
Comment: You turn it into a static library you can update one code for all projects that have the static library import (import into many projects not just one). Quite hard to get working but when its done it is very helpful.
Comment: Could you not create a static library out of this `ShareKit` files/folders and then just add it as if it was a framework.
Comment: but this is not only for ShareKit, its for every project I want to import so I need to fix it
Answer: What you need to do is simple:
1) Right click the sharekit folder in the first project and you will see show in finder. Click that.
2) That will lead to the folder in your directory.
3) Next pull the whole directory into second project. Make sure you copy the files over.
Hope this helps...
Comment: I tried that but the folders are blue not yellow, and if you call the files they won't be recognised. you would need to drag all the files in but there are more than 20 folders other folders in that one
Comment: Remove the folder that you just added.. And redo what i told to do again but this time, when you add the folder and it says copy over, there is a option below that says create groups for any added folders.. click that instead of the other... hope this helps...
Answer: In Xcode 4 it is different than older Xcode you have in the screenshot. To copy between projects, you have to open them in the same workspace (the same window). So

open the first project
drag the second one from finder to the same Xcode workspace
now drag the files you need
remove the second project from your workspace.

Lakesh's approach might have a risk in fact, that sometimes file structure you see in xcode might differ from what is actually on filesystem.
You might want to try ShareKit 2.0, it is already packaged as a static lib and has updated sharers to match newest api's. If you decide to use it, make sure to follow install wiki guide literally.

How to add groups of files?


Passar dados HTML para PDF preenchivel

Question: Fala galera, to com um problemão aqui pra vocês me ajudarem.
Tenho um PDF preenchivel (com campos que posso preencher) e tenho tambem um formulário em HTML. O que preciso fazer é pegar os valores dos inputs e mandar para esse template em PDF preenchendo nos campos adequados.
O problema é que não faço ideia de como fazer isso. Já pesquisei na internet e nada.
Comment: Dá uma olhadinha sobre XML, talvez isso possa te ajudar a transformar esses dados em um formulário organizado
Answer: Fala Sallazar, tudo bem?!
Eu já utilizei duas formas para editar PDF's.
Uma delas é editar no próprio front-end utilizando as bibliotecas jsPDF e/ou html2canvas, ambas são javascript.
O html2canvas é usado para converter todo o conteúdo HTML - que pode estar estilizado - em uma imagem.
O jsPDF é responsável por gerar o PDF.
Eu utilizei as duas bibliotecas porque possuía um imagem PNG resultado de uma conversão PDF -> PNG; Defini essa imagem como background do meu body e fiz todas as edições necessárias via HTML e CSS. Após isso, converti todo meu conteúdo HTML estilizado pelo CSS em uma imagem através do html2canvas e então manipulei o resultado com o jsPDF para gerar o PDF. Por ser um PDF gerado a partir de uma imagem, o arquivo final ficou bem grande (>=5Mb);
A outra forma é utilizar o ZendPdf para carregar o seu PDF e fazer as edições com o PHP e a biblioteca. Desta maneira você consegue criar e editar o PDF, mantendo o texto em formato de texto e o arquivo ganha alguns kbytes em relação ao template.
Existem bastante tutorial na internet para as duas formas. Eu recomendo utilizar o ZendPdf.
Comment: Massa, vou dar uma olhada nesse ZendPdf. Agora, estou usando JSP no projeto e não PHP, da pra fazer?
Comment: Com o JSP você pode utilizar o jsPDF mas entra no caso que mencionei acima. Você precisará converter seu PDF em uma imagem, defini-la como `background-image` de todo o conteúdo que deseja exibir no pdf e fazer as alterações.
Comment: Eu pesquisei sobre criação de PDF's em java e achei essa solução: https://www.baeldung.com/java-pdf-creation
Comment: Caso eu tenha sanado sua dúvida e realmente ter te ajudado, vote como melhor resposta para que a pergunta seja fechada xD **Abraços Sallazar**!!!

Passar dados HTML para PDF preenchivel


Data getting lost between 2 ViewDidLoad calls

Question: Inside a UIViewController class, I have a tableView who gets called like this by clicking on a navBar button:
<code>-(IBAction) addButtonPressed:(id)sender {
    CreateQuestionController *createQuestionViewController = [[CreateQuestionController alloc] initWithNibName:@"CreateQuestionController" bundle:nil];
    [self.navigationController pushViewController:createQuestionViewController animated:YES];
    [createQuestionViewController release];
}
</code>
This method gets called nowhere else in my code. Well, when I click this navBar button and the view shows up I find out that the ViewDidLoad method gets called twice (which is normal in this case) BUT the data I enter here gets lost. Here's my code:
<code>- (void)viewDidLoad
{
    [super viewDidLoad];
    textView.text=@"Type your question here";
    NSLog(@"Question text:%@", textView.text);
}
</code>
Log:
<code>2011-07-11 10:56:35.727 HelpMe[1343:207] Question text:Type your question here
2011-07-11 10:56:35.728 HelpMe[1343:207] Question text:(null)
</code>
What's going on?
Thank you
Edit:
Other symptoms:
- Cannot push another view
- Cannot change the image of a button
Comment: no memory warnings, I added a NSLog inside - (void)didReceiveMemoryWarning
Comment: I'd suggest setting a breakpoint to see where the second call comes from.
Comment: Did you set the view property of you view controller.
Comment: @dasdom: I did set the View property. @omz: I tried to put a breakpoint inside ViewDidLoad, but cannot figure out what calls it the second time. First time it gets called, ok, then a bunch of assembly commands and it executes again ViewDidLoad. Am I setting the breakpoint at the wrong place?
Comment: Did you override the `initWithNibName:` method in `CreateQuestionController`? If so, can you post the code?
Comment: @pgb: no I didn't overwrite it
Comment: Did you rule out `addButtonPressed:` being called more than once?
Comment: @pgb: We figured out why the method is getting called twice. It's because my nib's got more than one view. It doesn't explain the real problem which is the data loss
Comment: Even if there are several views in the nib, viewDidLoad should be called once. But anyway, if addButtonPressed: is somehow called twice, you'll see weird problems because it'll try to play two animations at once (in pushViewController: animated:).
Comment: @SVD: addButtonPressed is called only once. So that's not the reason viewDidLoad is getting called twice.
Comment: thanks everyone, problem solved. My nib file organization was wrong
Answer: My problem was in my nib file. I deleted my controller and assigned all my outlets to the File's owner


spring kafka 1.3.9 commit offset manually on error at container level

Question: I am using MANUAL_IMMEDIATE ack mode, Spring-kafka 1.3.9 (Can't change to Java 8), and committing offsets when processing is complete in Listener code. I am using Custom deserializer and its working fine unless I encounter Deserialization exception. Then onwards kafka gets stuck. I have handled this in by Deserializer, like instead of throwing the exception(When deserialization exception happens) I get a new instance of deserialized object and set the original message (which caused the deserialization exception) in a field(exceptionData) and let it pass to the Listener code(annotated with @KafkaListener).
In the Listener code I check if the field exceptionData is NULL or not and accordingly decide 'Good Message' or 'Bad Message' , Because I need to handle 'Bad Messages' too.
Now I want to know is there any way to handle all these from container level. Where I stuck is I don't get the Consumer reference in this version of Spring-kafka 1.3.9. I need to commit offset on error, any error.
Answer: No; it is not possible to get the consumer with that version. The ConsumerAwareErrorHandler was added in 2.0.
Comment: So in short we cannot manually commit offset on error with Spring-kafka 1.3.9, right?
Comment: Not in the error handler, no. You will have to handle the error within the listener instead.


Error Handling while calling dynamic methods C#

Question: I have a console application with main method as follows:
public static void Main(string[] commandString)
{
    try
    {
        var asm = Assembly.Load("CAT");
        var t = asm.GetType("CAT",true,true);
        var _Adjudication = Activator.CreateInstance(t);
        t.InvokeMember("NAMEME", BindingFlags.InvokeMethod, null, _Adjudication, new object[] { "Fluffy", 5});
    }
    catch (Exception ex)
    {
        Environment.Exit(99);
    }
}

CAT class is as below :
public class CAT
{
    public void NAMEME(string name, int age)
    {
       try
       {
           throw new Exception();
       }
       catch (Exception ex)
       {
           throw ex;
       }
    }
}

I have an error stating "Exception was unhandled by user code" when I run this program. The error is caught by the Catch block of the NAMEME method.
How do I get the exception to hit the catch block of my Main method?
PS : I am using .NET Framework 4.0
PPS: I was able to handle it by capturing the TargetInvocationException error
Comment: I can't reproduce. It works for me
Comment: You should use throw instead of throw ex
Comment: Of course it will catch in the NAMEME method first.  It will then throw and be caught in the Main method.  Continue to step through your code using F10.
Comment: i got the same problem for dynamic class, can anyone tell me the problem

http://stackoverflow.com/questions/38816233/c-sharp-user-defined-exception-handling-for-erroe-from-dll-get-exception-was-unh?noredirect=1#comment65000685_38816233
Answer: This actually works, I copied all the source code and I have it running locally just fine. There are a few typoes in your code provided, but I assume they do not exist in your actual source on your dev box as you said you get the exception to hit in the CAT class. In order for it to hit the next catch in the main app, you need to continue once the exception is thrown -- it will then land where you'd expect it to.
Comment: Then you must have not given us the full story or something is missing. I literally copied and pasted your code (minus the typo) and then stepped through it as expected.
Comment: Yep, same here, can't repro
Comment: In debug mode, I can 'continue' it. But when I run the exe via command line parameters, it wont 'continue' to exit with the error code of 99.
Comment: Okay, I had to get rid of all the actual code in my CAT class as it's work-related.. But the scenario is the same. I invoke a method that throws an exception. File not found / IO .. whatever. The catch block in the CAT class captures it. But Main doesn't get to catch it
Comment: Try the code as you posted it: it works as you'd expect (both to me and to @DavidPine , at least), so there's something in what you have "got rid of" that is making it not work, and we can't guess it.


how to handle async error in ib_insync with python3.7?

Question: Sorry I may ask a stupid question but I am just a beginner in python and algotrading. I am now using Python 3.7 and ibapi with ib_insync to try connect TWS. However, as Python 3.7 use async as a keyword so when I try to code with ib_insync:
from ib_insync import *

ib = IB()
ib.connect('127.0.0.1', 7496, clientId=1)

contract = Forex('EURUSD')
bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='30 D', barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)

df = util.df(bars)
print(df['date', 'open', 'high', 'low', 'close'])

It end up like this:
File "C:/Users/leung/Documents/MONEY/Algotrade/venv/test1.py", line 1, in <module>
    from ib_insync import *
  File "C:\Users\leung\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ib_insync\__init__.py", line 24, in <module>
    from .ib import *
  File "C:\Users\leung\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ib_insync\ib.py", line 11, in <module>
    from ib_insync.client import Client
  File "C:\Users\leung\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ib_insync\client.py", line 10, in <module>
    from ibapi.client import EClient
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 963, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 906, in _find_spec
  File "<frozen importlib._bootstrap_external>", line 1280, in find_spec
  File "<frozen importlib._bootstrap_external>", line 1254, in _get_spec
  File "<frozen importlib._bootstrap_external>", line 1235, in _legacy_get_spec
  File "<frozen importlib._bootstrap>", line 441, in spec_from_loader
  File "<frozen importlib._bootstrap_external>", line 594, in spec_from_file_location
  File "C:\Users\leung\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ibapi-9.73.7-py3.7.egg\ibapi\client.py", line 60
    self.async = False
             ^
SyntaxError: invalid syntax

Process finished with exit code 1

I know I need to change the name async to other name. I tried to modify the file client.py in ibapi but it seems not work at all. Which part of code I should change in order to get it work?
Answer: Install newest version (API_Version=9.75.01) of IB API SW - this issue is fixed there. It is Python 3.7 dependent - same code worked well running Python 3.6 for me.
Answer: I stumbled upon same error in API 973.07. In my case I use MacOS, so file path looks different from your Windows environment, but idea is the same. To fix the issue I just commented out line 60 in file IBJts/source/pythonclient/build/lib/ibapi/client.py to look like:
#        self.async = False

Not sure if it will affect anything else, but at least I can compile and properly install library via:
python3 setup.py install

PS in line 123 os the same file there is a comment
#TODO: support async mode

Hopefully my change doesn't break anything
Comment: I tried but it doesn't work, at the end I fixed the problem by use python 3.6


como modificar essa programação para que aceite letras e numeros?

Question: Private Sub TNumero_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

If (KeyAscii < 44 Or KeyAscii > 57) Then

    If KeyAscii <> 8 Then
    If KeyAscii <> 13 Then

    KeyAscii = 0

    MsgBox "É permitido somente números!", vbCritical, "ERRO"

End If
End If
End If

If KeyAscii = 45 Or KeyAscii = 46 Or KeyAscii = 47 Then
    KeyAscii = 0
    MsgBox "É permitido somente números!", vbCritical, "ERRO"
End If

End Sub

Answer: O KeyAscii é representação em decimal do ASCII. Você pode consultar uma tabela ASCII e fazer as alterações necessárias.
Creio eu que isto seria suficiente, em teoria, nem sei que linguagem é essa, então pode ter algo errado:
Private Sub TNumero_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

If (KeyAscii < 48 Or (KeyAscii > 57 And KeyAscii < 65) Or (KeyAscii > 90 And KeyAscii < 97) Or KeyAscii > 122) Then

    If KeyAscii <> 8 Then
    If KeyAscii <> 13 Then

     KeyAscii = 0

    MsgBox "É permitido somente números!", vbCritical, "ERRO"

End If
End If
End If

O objetivo do KeyAscii < 48 Or (KeyAscii > 57 And KeyAscii < 65) Or (KeyAscii > 90 And KeyAscii < 97) Or KeyAscii > 122 é que valores que estão fora do intervalo de 0-9, A-Z e a-z seja apresentado a mensagem.


Vue.js input validation w VeeValidate - How to avoid onInput action while invalid

Question: I am validating a input field ( required , min length 3 ) with VeeValidate plugin.. it's working fine
but how I can avoid the onInput action to be called ( to avoid commit in store when the input becomes invalid ( as soon as input aria-invalid switch to false )
shortly said : Is there anyway to switch calling/not Calling onInput: 'changeTitle' when the input field aria-invalid is false/true ?
thanks for feedback
ChangeTitleComponent.vue
    <template>

        Change the title of your shopping list here
        <input name="title" data-vv-delay="1000" v-validate="'required|min:3'" :class="{'input': true, 'is-danger': errors.has('required') }" :value="title" @input="onInput({ title: $event.target.value, id: id })"/>

{{ errors.first('title') }}

    </template>

vuex/actions.js
    import * as types from './mutation_types'
    import api from '../api'
    import getters from './getters'

    export default {
      ...
      changeTitle: (store, data) => {
        store.commit(types.CHANGE_TITLE, data)
        store.dispatch('updateList', data.id)
      },

      updateList: (store, id) => {
        let shoppingList = getters.getListById(store.state, id)
        return api.updateShoppingList(shoppingList)
        .then(response => {
          return response
        })
        .catch(error => {
          throw error
        })
      },
      ...
    }

UPDATE
I tried to capture the input value with @input="testValidation) and check for a valid input value (required)
if valid ( aria-invalid: false) then I emit the input value, but the props are not updated in the parent component and the vuex  action 'changeTitle' is not triggered
    <template>

        Change the title of your shopping list here
        <input name="title" ref="inputTitle" data-vv-delay="1000" v-validate="'required'" :class="{'input': true, 'is-danger': errors.has('required') }" :value="title" @input="testValidation({ title: $event.target.value, id: id })"/>

{{ errors.first('title') }}

    </template>

Comment: Why not trigger the action from `testValidation`?
Comment: I'll give a try...  don't understand why the onInput is not executed when the emit(input) is triggered...
Answer: like you access the errors collection in the VUE template, you can also access the same errors collection in your testValidation method
so replace
const ariaInvalid = this.$refs.inputTitle.getAttribute('aria-invalid')

with
 const ariaInvalid = this.$validator.errors.has('title')

grtz


wikibase-docker won't start on Azure container instance

Question: It's possible to run a wikibase/mediawiki instance locally using docker-compose: https://www.mediawiki.org/wiki/Wikibase/Docker.
This works on my macbook without trouble, but now I'm trying to get it running on Azure as a Container Instance (ACI).
I don't want the MariaDB as a container, so I've created an AzureDB for that.
Other than that I've modified the docker-compose file as follows, according to https://docs.docker.com/cloud/aci-integration/:
version: '3.8'

x-common-variables: &wikibase_variables
  DB_SERVER: ${DB_SERVER}
  MW_ADMIN_NAME: ${MW_ADMIN_NAME}
  MW_ADMIN_PASS: ${MW_ADMIN_PASS}
  MW_ADMIN_EMAIL: ${MW_ADMIN_EMAIL}
  MW_WG_SECRET_KEY: ${MW_WG_SECRET_KEY}
  DB_USER: ${DB_USER}
  DB_PASS: ${DB_PASS}
  DB_NAME: ${DB_NAME}
  WIKIBASE_HOST: ${WIKIBASE_HOST}

services:
  wikibase:
    image: "${WIKIBASE_BUNDLE_IMAGE_NAME}"
    container_name: "wikibase"
    restart: unless-stopped
    ports:
      - "80:80"
    volumes:
      ## This shares the configuration with jobrunner
      - mydata:/var/www/html:rw

      ## Uncomment this next line to mount your own LocalSettings.php file
      #- ./LocalSettings.php:/var/www/html/LocalSettings.d/LocalSettings.override.php

    networks:
      default:
        aliases:
          - ${WIKIBASE_HOST}
          - wikibase-docker.svc
    environment:
      <<: *wikibase_variables
      WIKIBASE_PINGBACK:
      MW_WG_ENABLE_UPLOADS:

volumes:
  mydata:
    driver: azure_file
    driver_opts:
      share_name: my-docker-volumes-fs
      storage_account_name: myvolumesa

All environment variables are defined in a .env file. Where DB_SERVER=my-mariadb-server.mariadb.database.azure.com:3306.
Now if I try to run docker compose up (docker-compose is not supported in the aci context) using the aci context, it fails without any logging (not in the terminal, nor in the Azure portal).
When trying to run just the wikibase container with:
docker run --env-file .env -v myvolumesa/my-docker-volumes-fs:/var/www/html:rw -p 80:80 wikibase/wikibase-bundle:1.36.3-wmde.5

I get this output:
[+] Running 2/2
 ⠿ Group distracted-villani  Created                                                                                4.5s
 ⠿ distracted-villani        Created                                                                                353.3s
wait-for-it.sh: waiting 300 seconds for kbga-mariadb-server.mariadb.database.azure.com:3306
wait-for-it.sh: kbga-mariadb-server.mariadb.database.azure.com:3306 is available after 0 seconds
wait-for-it.sh: waiting 300 seconds for kbga-mariadb-server.mariadb.database.azure.com:3306
wait-for-it.sh: kbga-mariadb-server.mariadb.database.azure.com:3306 is available after 0 seconds
Could not open input file: /var/www/html/maintenance/install.php
2022-08-03T11:21:15.3026758Z stderr F

I suspect a problem with volume permissions, but I'm not sure how to fix it. Has anyone successfully spun up a wikibase-docker on Azure, or does anyone know how to get this working? Thanks!
Answer: I figured out how to fix this error: Turns out I didn't need to specify the volume mapping to /var/www/html. When I removed this and the volume specification, it successfully installed.
I'm still kind of confused why locally it needs a volume but not on ACI, but I'm happy it's running.
The working docker-compose.yml:
version: '3.8'

x-common-variables: &wikibase_variables
  DB_SERVER: ${DB_SERVER}
  MW_ADMIN_NAME: ${MW_ADMIN_NAME}
  MW_ADMIN_PASS: ${MW_ADMIN_PASS}
  MW_ADMIN_EMAIL: ${MW_ADMIN_EMAIL}
  MW_WG_SECRET_KEY: ${MW_WG_SECRET_KEY}
  DB_USER: ${DB_USER}
  DB_PASS: ${DB_PASS}
  DB_NAME: ${DB_NAME}
  WIKIBASE_HOST: ${WIKIBASE_HOST}

services:
  wikibase:
    image: "${WIKIBASE_BUNDLE_IMAGE_NAME}"
    container_name: "wikibase"
    restart: unless-stopped
    ports:
      - "80:80"
    networks:
      default:
        aliases:
          - ${WIKIBASE_HOST}
          - wikibase-docker.svc
    environment:
      <<: *wikibase_variables
      WIKIBASE_PINGBACK:
      MW_WG_ENABLE_UPLOADS:
volumes:
  mydata:
    driver: azure_file
    driver_opts:
      share_name: my-docker-volumes-fs
      storage_account_name: myvolumesa


Redirect Logged In User to Associated Company Show Page

Question: I have a UserSessionsController:
  def create
    @company = Company.find(params[:user_id])

    if login(params[:email], params[:password])
      redirect_back_or_to(users_path, message: "Logged in successfully.")
    else
      flash.now.alert = "Login Failed."
      render action: :new
    end
  end

I want to redirect the logged in user to the associate company's show page. Any ideas on what should replace users_path?
I'm just brainstorming with the @company bit.
Answer: From redirect_back_or_to method name, I'll assume you're using Sorcery gem. Please provide such info in your questions if you want to get an accurate answer.
A quick look at methods source code shows that it's just a helper method around redirect_to controller method.
Therefore, you can just change your line from:
redirect_back_or_to(users_path, message: "Logged in successfully.")

To:
redirect_back_or_to(@company, message: "Logged in successfully.")

Again, assuming your Company resource isn't nested...


For each user return rows where user bought same item n times within 10 minutes in MariaDB

Question: MariaDB version 10.2.21
I have a table that looks like:
    user_id  item_id      start_time            end_time
1    412374   2349    2020-01-01 04:01:44     2020-01-01 04:01:51
2    271274   2519    2020-01-01 04:02:41     2020-01-01 04:03:33
3    271274   2519    2020-01-01 04:05:37     2020-01-01 04:06:14
4    349729   6979    2020-01-01 04:10:44     2020-01-01 04:10:49
5    79011    2785    2020-01-01 04:54:38     2020-01-01 04:55:06
6    68486    5395    2020-01-01 05:39:23     2020-01-01 05:40:03
7    68486    5395    2020-01-01 05:55:23     2020-01-01 05:59:03

Within 10 minutes => row 2's end_time and row 3's start_time is within 10 minutes. Even though row 1 end_time and row 2 start_time are within 10 minutes I do not want it since they are different user.
row 6,7: user_id is the same and bought same item however row 6 end_time ~ row 7 start_time is over 10 minutes therefore I do not want them.

desired table after filter:
    user_id  item_id      start_time            end_time
1    271274   2519    2020-01-01 04:02:41     2020-01-01 04:03:33
2    271274   2519    2020-01-01 04:05:37     2020-01-01 04:06:14

Thanks in advance!
Comment: 5.8? Are you sure? Do you mean 8.0.X? You need extra clarity as to what you're trying to eliminate and the exact criteria for this.
Comment: When I run SHOW VARIABLES LIKE "%version%"; it tells me that version is 10.2.21-MariaDB... Are they compatible with each other?
Comment: 5.8 never really existed as a release so its hard to gauge its compatibility. MySQL and MariaDB have some compatibility, however for a question its very helpful if the real version is shown.
Comment: Yes, thanks for the feed back I've updated.
Answer: You can use an EXISTS query to check for a transaction on the same user_id and item_id within a 10 minute period:
SELECT *
FROM sales s1
WHERE EXISTS (SELECT *
              FROM sales s2
              WHERE s2.id != s1.id
                AND s2.user_id = s1.user_id
                AND s2.item_id = s1.item_id
                AND (s2.start_time BETWEEN s1.end_time AND s1.end_time + INTERVAL 10 MINUTE
                  OR s1.start_time BETWEEN s2.end_time AND s2.end_time + INTERVAL 10 MINUTE
                    )
              )
ORDER BY id

Output:
id  user_id     item_id     start_time              end_time
2   271274      2519        2020-01-01 04:02:41     2020-01-01 04:03:33
3   271274      2519        2020-01-01 04:05:37     2020-01-01 04:06:14

Demo on dbfiddle
Comment: @Ambleu that's right, and then the two time comparisons check whether either s1's start time is within 10 minutes of s2's end time, or whether s2's start time is within 10 minutes of s1's end time.
Comment: hey, I just want to make things clear. Reason for "OR" inside where clause in subquery which compares s2.start_time with s1's end_times then s1.start_time with s2's end_time is because s2.start_time with s1's end_times would not contain s2_start_time itself right?
Comment: @Ambleu it's because you don't know which of `s1` or `s2` occurs first, so you have to compare both `end_time` values with both `start_time` values. Otherwise you would only get one of the rows in the output.
Comment: Thanks Nick for answering. I'm still quite confused isn't query comparing s1 row to all s2 where there id do not match?
Answer: Slightly different form of output side by side rather than list:
  SELECT t1.*, t2.*
  FROM tbl t1
  JOIN tbl t2
     ON t1.id!=t2.id
        AND t1.user_id = t2.user_id
        AND t1.item_id = t2.item_id
        AND (t1.start_time BETWEEN t2.start_time - INTERVAL 10 MINUTES AND t2.end_time + INTERVAL 10 MINUTES
            OR t1.end_time BETWEEN t2.start_time - INTERVAL 10 MINUTES AND t2.end_time + INTERVAL 10 MINUTES)


Android - get X and Y coordinates of dynamically drawn bitmaps

Question: I am making an Android app with OpenStreetMaps (using osmdroid).
On this map, markers are shown (the long/lat and other data for these markers are retrieved from a json file). These markers are OverlayItems and are all shown correctly on the MapView. The X and Y coordinates for these bitmaps are calculated by getting a projection of the mapview and then from the geopoint's X and Y in combination with the bitmaps width/2 and height/2 the bitmap is drawn on his correct location on the worldmap.
Long story short: the X and Y values for the bitmaps are calculated dynamically.
My question is, I'm writing code that should occur when the user has clicked (=made a touch event) on a marker-bitmap. For this, I need to check if the event's X and Y is within the bounds of the bitmap.
How can I do this?
Unfortunately, there doesn't seem to be an easy bitmap.getX or .getY, which is basically what I need.
This is the code for drawing the bitmaps (happens in the @Override draw()) if it could be of any use:
for(OverlayItem p: waypointMarkers){
                IGeoPoint in = p.getPoint();
                Point out = new Point();
                mapview.getProjection().toPixels(in, out);

                Bitmap bm = BitmapFactory.decodeResource(getResources(),
                        R.drawable.marker);

                bitmaps.put(bm, p);

                canvas.drawBitmap(bm,
                        out.x - bm.getWidth()/2,    //shift the bitmap center
                        out.y - bm.getHeight()/2,   //shift the bitmap center
                        null);

            }

The bitmaps.put(bm, p); is a HashMap with Bitmap, OverlayItem pair. Later in my code, I'm looping through the keys of this HashMap and there is where I want to check for the bitmap's X and Y.
for(Bitmap b: bitmaps.keySet()){
            if (x >= xOfBitmap && x < (xOfBitmap + yourBitmap.getWidth())
                    && y >= yOfBitmap && y < (yOfBitmap + yourBitmap.getHeight())) {
                //found this on StackOverflow, if this is true than user has clicked somewhere on the bitmap
            }

Thanks in advance.
Comment: `a HashMap with Bitmap, OverlayItem pair.`. Can't you calculate x,y again from the OverlayItem? As you did before.
Comment: Unfortunately no, the OverlayItems currently have no link with the Bitmaps. The OverlayItems purely contain string values with names etc and a geopoint for the global location.

I'm currently trying with a class that contains int X, int Y, and Bitmap which is created before the drawing of the bitmap, so those objects should contain the X and Y.

But no luck as of yet, think it has something to do with the int/float conversion (one digit after the comma altered on a world map is immediately an entirely other location)
Comment: Sorry. I do not understand why you cant calculate x,y again. But if not then use something like  bitmaps.put(bm, p, out.x, out.y); Why would you need an int/float conversion by the way?
Answer: You could have a look at OSMBonusPack Marker.
As it implements the touch event detection, looking at its source code (hitTest method) will give you a working example.
And maybe you can just use it, if it matches your need.


E: Malformed entry 7 in list file /etc/apt/sources.list.d/google-cloud-sdk.list (Suite) E: The list of sources could not be read

Question: Getting this error when trying to sudo apt-get update. E: Malformed entry 7 in list file /etc/apt/sources.list.d/google-cloud-sdk.list (Suite)
E: The list of sources could not be read.
I tried to run sed to remove and no luck.
Please help.
Okay, after following the first 5 steps in the link: cloud.google.com/sdk/docs/quickstart-debian-ubuntu I received the following output:
Your Google Cloud SDK is configured and ready to use!

Commands that require authentication will use email@example.com by default
Commands will reference project post-a-prayer by default
Compute Engine commands will use region us-west2 by default
Compute Engine commands will use zone us-west2-a by default

Run gcloud help config to learn how to change individual settings
This gcloud configuration is called [postaprayerdns]. You can create additional configurations if you work with multiple accounts and/or projects.
Run gcloud topic configurations to learn more.
Some things to try next:

Run gcloud --help to see the Cloud Platform services you can interact with. And run gcloud help COMMAND to get help on any gcloud command.
Run gcloud topic --help to learn about advanced features of the SDK like arg files and output formatting

Okay. I was able to get into the google-cloud-sdk.list file and edit it using sudo nano /etc/apt/sources.list.d/google-cloud-sdk.list
From there I edited the .list file and deleted line 7 (which stated clear)
I edited these instructions to solve this error: https://askubuntu.com/questions/332669/unable-to-edit-etc-apt-sources-list-file
sudo nano /etc/apt/sources.list.d/google-cloud-sdk.list

`
Comment: What did you do that led up to this error? https://cloud.google.com/sdk/docs/quickstart-debian-ubuntu
Comment: sudo apt-get update as well as any other commands to install anything. I recently upgraded to 18.04
Comment: I get the following when when entering $ sudo -H gedit /etc/apt/sources.list.d/google-cloud-sdk.list
No protocol specified
Unable to init server: Could not connect: Connection refused

(gedit:28434): Gtk-WARNING **: 02:42:15.498: cannot open display: :0
Comment: I upgraded recently to 18.04 from 17.?.
Comment: Did you follow the steps in the document link that I added to my first comment?
Comment: Sorry. I missed going to the link there. Checking steps now. . .
Comment: The zone name doesn't match what I had set in gcloud.
Comment: Hi John, I was able to delete the problem line and it solved my problem. Thank you so much for your help. Is there anything else I should do in this case?
Answer: Solved. Used Nano command to edit *.list file, deleted corrupt entry 7, and then saved.
Summary:
sudo nano /etc/apt/sources.list.d/google-cloud-sdk.list

From there I edited the .list file and deleted line 7 (which stated clear)
I edited these instructions to solve this error: https://askubuntu.com/questions/332669/unable-to-edit-etc-apt-sources-list-file
sudo nano /etc/apt/sources.list.d/google-cloud-sdk.list


Prove that $(n+1)(n+2)(n+3)$ is $O(n^3)$

Question: Problem

Prove that $(n+1)(n+2)(n+3)$ is $O(n^3)$

Attempt at Solution

$f(n) = (n+1)(n+2)(n+3)$
$g(n) = n^3$
Show that there exists an $n_0$ and $C > 0$ such that $f(n) \le Cg(n)$ whenever $n > n_0$
$f(n) = n^3+6n^2+11n+6 = n^3(1 + 6/n + 11/n^2 + 6/n^3)$
$f(n) \le C*g(n)$ is
$n^3(1 + 6/n + 11/n^2 + 6/n^3) \le C*n^3$ is
$(1 + 6/n + 11/n^2 + 6/n^3) < C$

That's as far as I got.  Should I plug in a value for n to find C?  And then, would that value I plugged in for n be $n_0$?
Any help is appreciated.
Thank you in advance.
Comment: +1. You've got the key idea: 4. With that, you can easily generalize to prove that a degree $k$ polynomial is $O(n^k)$. Just use the triangular inequality and $1/n^j\leq 1$ for $n\geq 1$.
Answer: Your multiplication isn't quite correct. You should get
$$(n + 1)(n + 2)(n + 3) = (n + 1)(n^2 + 5n + 6) = n^3 + 6n^2 + 11n + 6$$
Now proceeding as you did, we get
$$f(n) = n^3 (1 + \frac{6}{n} + \frac{11}{n} + \frac{6}{n^3})$$
Note that if $n \geq 1$, then $1/n \leq 1$; likewise, $1/n^2 \leq 1$ and $1/n^3 \leq 1$. Hence, try choosing
$$C = 1 + 6 + 11 + 6$$
Comment: Thank you for catching that mult. error!
Answer: Note that $3+\frac9n+\frac6{n^2}$ decreases as $n$ increases, so you might as well use the smallest possible value of $n$. You can't use $0$, so take $n=1$: for all $n\ge 1$,
$$3+\frac9n+\frac6{n^2}\le 3+\frac91+\frac6{1^2}=18\;.$$
In other words, if you take $n_0=1$ and $C=18$, you have $|f(n)|\le C|g(n)|$ for all $n\ge n_0$.
Your definition requires strict inequalities where I have non-strict ones, but that's easily adjusted for: take $n_0=0$ and $C=19$.
However, your calculation of $f(n)$ can't be right: $(n+1)(n+2)(n+3)$ does not have $n$ as a factor, and $3n^3+6n^2+9n$ does. I'll leave it to you to correct the algebraic error and then try to replicate the reasoning above with the corrected expression.
Answer: You are almost there.
Remember that big-O (and little-O) statements
apply for all large enough $n$,
not for all $n$.
So, in
$(3 + 9/n + 6/n^2) < C$,
give some lower bound for $n$,
say $n > 3$.
Then $9/n < 3$ and
$6/n^2 < 2/3$,
so
$3 + 9/n + 6/n^2 < 3+3+2/3 < 7$,
so $C=7 $ works for $n > 3$.
Note that, as the lower bound for $n$ gets larger
(for example, see what you get for $n = 100$),
the bound on $C$ gets closer to $3$,
its best value.
But it never reaches $3$.
But you only need $a$ bound, not the best bound.
Comment: I really like the way you did this: So, in (3+9/n+6/n2)3. Then 9/n<3 and 6/n2<2/3, so 3+9/n+6/n2<3+3+2/3<7, so C=7 works for n>3.  Thumbs up! +1
Answer: If you are not interested in the optimal constant you can notice that for $n \geq 3$, all three terms are smaller than $2n$. This gives $(n+1)(n+2)(n+3) \leq 8n^3$.


how to change week num to iso week in SQL

Question: I have data that looks like this:

CustomerID
Trans_date

C001
01-sep-22

C001
04-sep-22

C001
14-sep-22

C002
03-sep-22

C002
01-sep-22

C002
18-sep-22

C002
20-sep-22

C003
02-sep-22

C003
28-sep-22

C004
08-sep-22

C004
18-sep-22

after processing using this query:
WITH CTE (customerID,FirstWeek,RN) AS (
        SELECT customerID,MIN(DATEPART(week,tp_date)) TransWeek,
        ROW_NUMBER() over(partition by customerID ORDER BY DATEPART(week,tp_date) asc ) FROM all_table
        GROUP BY customerID,DATEPART(week,tp_date)
    )

    SELECT CTE.customerID, CTE.FirstWeek,
         (select TOP 1 (DATEPART(week,c.tp_date))
            from all_table c
                where c.customerID = CTE.customerID AND DATEPART(week,C.tp_date) > CTE.FirstWeek
                    )   SecondWeek
    FROM CTE
    WHERE RN = 1

the result is like this

CustomerID
firstweek
secondweek

C001
36
37

C002
36
39

C003
36
40

C004
37
39

but the results will be appropriate when using the weeknum in excel. but what i hope  the result is isoweek format which will look like this

CustomerID
firstweek
secondweek

C001
35
37

C002
35
37

C003
35
39

C003
36
37
Comment: Well [`DATEPART` supports `ISO_WEEK` in addition to `WEEK`](https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql).
Comment: Can you explain what your query should accomplish in your own words?
Comment: @RhythmWasaLurker so just change week to iso_week?
Answer: Have create a small fiddle to help: db<>fiddle
And as I understand I would just use min and max values of weeks grouped by customer
Comment: https://dbfiddle.uk/a7Yr0Nx7 - fiddle link
Answer: Datepart has an isowk parameter.
So instead of
DATEPART(week,...

use
DATEPART(isowk,...


Error bars in ggplot in middle of bin

Question: I'm trying to make a bar plot in ggplot with 2 values for each bin (fold change values from RNA-Seq and qPCR experiments):
Gene    FC  expt    se
a   1.02    RNA-Seq 0
b   2.79    RNA-Seq 0
c   1.63    RNA-Seq 0
d   0.84    RNA-Seq 0
e   0.81    RNA-Seq 0
f   1.45    RNA-Seq 0
g   1.27    RNA-Seq 0
h   1.72    RNA-Seq 0
i   2.52    RNA-Seq 0
a   0.84    qPCR    0.16
b   1.92    qPCR    0.15
c   1.14    qPCR    0.78
d   0.47    qPCR    0.76
e   0.95    qPCR    0.26
f   0.32    qPCR    0.51
g   0.92    qPCR    0.39
h   0.97    qPCR    0.61
i   1.73    qPCR    0.77

My RNA-Seq values don't have error bars. As such I want to plot a barchart with:

Error bars that only extend up
Error bars only for q-PCR bars

I'm not sure where my code (or input format) is going wrong:
df <- read.table("stack.txt", header=TRUE)
limits <- aes(ymax = FC + se, ymin = FC)
dodge <- position_dodge(width = 0.9)

ggplot(data=df, aes(x=Gene, y=FC)) +
geom_errorbar(limits, position = dodge, width = 0.25) +
geom_bar(aes(fill=expt),colour="black", stat="identity", position = dodge)

Which produces:

As you can see, the error bars are in the middle of each bin, rather than being onto of each bar. Any suggestions/comments would be hugely appreciated!
Comment: `position_dodge(width = <...>)`
Comment: @Roland It's the same question, but the data and answers are different it would seem. At least as far as I can see they don't help me much, whereas the answer provided below does
Answer: When you add the group parameter to the aes, you will get the desired result:
ggplot(data=df, aes(x=Gene, y=FC, fill=expt, group=expt)) +
  geom_bar(colour="black", stat="identity", position = position_dodge(width = 0.9)) +
  geom_errorbar(aes(ymax = FC + se, ymin = FC, group=expt),
                position = position_dodge(width = 0.9), width = 0.25)

this gives:

Error bars in ggplot in middle of bin


igraph's "assortativity" function returns NaN if all attributes are identical. Why?

Question: I am trying to use igraph's assortativity function. It returns positive values if more similar nodes have similar attributes and negative values otherwise.
Indeed, if I randomly generate attributes for a graph, this is the case:
gg<-random.graph.game(50,0.3,"gnp",directed=T)
V(gg)$group<-sample(1:7,50,replace=T)
assortativity(gg, as.numeric(V(gg)$group))
[1] 0.002059966
V(gg)$group
 [1] 1 4 7 2 6 5 4 3 3 5 5 1 4 1 3 3 2 4 1 3 7 7 1 1 2 3 6 2 7 4 2 4 1 6 1 2 2 5 2 1 7 1 1 3 6 1 3 6 7 2

This all looks right and makes sense. However, for my dataset, I have a network for a particular situation where all the attributes are identical. Theoretically, this should be high homophily/assortativity. But to the contrary, it returns NaN. Does anyone know why this is and what the remedy could be?
V(gg)$group<-7
assortativity(gg, as.numeric(V(gg)$group))
[1] NaN

EDIT: I have found a solution to this, although I cannot explain why this is the case. It seems to be something about the whole number/integer. If I add .001 as a constant to each number in the graph's attribute, to get 7.001 instead of 7, it returns the expected assortativity coefficient of "1". See below:
gg<-random.graph.game(50,0.3,"gnp",directed=T)
V(gg)$group<-7
assortativity(gg, as.numeric(V(gg)$group)+rnorm(1,0,.001))
[1] 1

Answer:
However, for my dataset, I have a network for a particular situation where all the attributes are identical. Theoretically, this should be high homophily/assortativity.

Assortativity is the Pearson correlation between values at the endpoints of edges. Note that Pearson correlation is normalized. If all values are the same, the expression leads to 0/0, which on a computer leads to NaN.

That said, I notice that you are using an attribute named "group". Is this representing the index of a group in some clustering? Are you trying to compute the tendency of vertices to connect to others within the same group? If so, you should be using assortativity_nominal() instead of assortativity().
It makes no sense to treat a group index as a numerical quantity. It should only be used to determine whether two vertices are within the same group. This is precisely what assortativity_nominal() does.
The R/igraph documentation needs some work, but you can read more about what these functions do here:

https://igraph.org/c/html/latest/igraph-Structural.html#igraph_assortativity
https://igraph.org/c/html/latest/igraph-Structural.html#igraph_assortativity_nominal

Note that what R/igraph version 1.4 and earlier compute is the normalized version of the measure described in the above reference pages. This is what is usually referred to as "assortativity" in the literature.
Comment: "group" is a misnomer. It was a variable denoting something quantitative (although the value is from a Likert so maybe there's some sort of issue there still)


R split string at last whitespace chars using tidyr::separate

Question: Suppose I have a dataframe like this:
df<-data.frame(a=c("AA","BB"),b=c("short string","this is the longer string"))

I would like to split each string using a regex based on the last space occuring.
I tried:
library(dplyr)
library(tidyr)
df%>%
  separate(b,c("partA","partB"),sep=" [^ ]*$")

But this omits the second part of the string in the output. My desired output would look like this:
   a              partA  partB
1 AA              short string
2 BB this is the longer string

How do I do this. Would be nice if I could use tidyr and dplyr for this.
Answer: We can use extract from tidyr by using the capture groups ((...)).  We match zero or more characters (.*) and place it within the parentheses ((.*)), followed by zero or more space (\\s+), followed by the next capture group which includes only characters that are not a space ([^ ]) until the end ($) of the string.
library(tidyr)
extract(df, b, into = c('partA', 'partB'), '(.*)\\s+([^ ]+)$')
#   a              partA  partB
#1 AA              short string
#2 BB this is the longer string

Answer: You may turn the [^ ]*$ part of your regex into a (?=[^ ]*$) non-consuming pattern, a positive lookahead (that will not consume the non-whitespace chars at the end of the string, i.e. they won't be put into the match value and thus will stay there in the output):
df%>%
  separate(b,c("partA","partB"),sep=" (?=[^ ]*$)")

Or, a bit more universal since it matches any whitespace chars:
df %>%
  separate(b,c("partA","partB"),sep="\\s+(?=\\S*$)")

See the regex demo and its graph below:

Output:
   a              partA  partB
1 AA              short string
2 BB this is the longer string


Irreducibility over $\mathbb{Q}[\sqrt[n]{p}]$

Question:
Let $p$ be a prime and $n=p+1$.
Then prove or disprove whether $x^{2p}+nx+n$ is irreducible over $\mathbb{Q}[\sqrt[n]{p}]$.

This question appeared in our quiz today. But I couldn't even prove that the polynomial is irreducible over $\mathbb{Q}[x]$. Provided that I can prove that the polynomial, which I will call $f$ from now on, is irreducible over $\mathbb{Q}[x]$, we will have
$$[\mathbb{Q}(\alpha,\sqrt[n]{p}):\mathbb{Q}]\le [\mathbb{Q}(\alpha):\mathbb{Q}][\mathbb{Q}(\sqrt[n]{p}):\mathbb{Q}]=2p(p+1)$$
,where $\alpha$ is a root of $f$. But we also have $p+1=[\mathbb{Q}(\sqrt[n]{p}):\mathbb{Q}]\mid[\mathbb{Q}(\alpha,\sqrt[n]{p}):\mathbb{Q}]$
, similarly we also have $2p\mid [\mathbb{Q}(\alpha,\sqrt[n]{p}):\mathbb{Q}]$.Thus either
$[\mathbb{Q}(\alpha,\sqrt[n]{p}):\mathbb{Q}]=p(p+1)$ or $2p(p+1)$. Maybe some further pondering will actually show us that the polynomial is indeed irreducible over the field $\mathbb{Q}[\sqrt[n]{p}]$.
But I am yet unable to prove that the polynomial is irreducible over $\mathbb{Q}[x]$. I can't see any immediate way to apply Eisenstein.
Comment: Over $\Bbb{Q}$ for most values of $p$ the integer $n$ has a suitable prime factor $p$ such that  $p^2\nmid n$, and Eisenstein kicks in. There are exceptions such as the Mersenne primes. The case of $p=2^q-1$, $q$ an odd prime can be handled using $2$-adic [Newton's polygon](https://en.wikipedia.org/wiki/Newton_polygon), which is sorta like "Eisenstein on steroids".
Comment: @JyrkiLahtonen  "Eisenstein on steroids" -- I'll have to remember that phrase.
Comment: @KCd exactly, if I can do show that this polynomial is irreducible over Q, then maybe I can  do some degree of extension argument to show that a root of the polynomial has degree 2p over the extension field, which would do the job.And sure I will let you know when the instructor reveals the solution.
Comment: I wonder if there was a typographical error in the quiz (not that the problem as written is wrong, but it doesn't seem like a quiz-level problem). From my experience, the "only" way such problems can be solved in a quiz at the level of your course (your tags include "field theory", not "algebraic number theory") is that you first show the polynomial is irreducible over $\mathbf Q$ and then use a field extension argument to show it remains irreducible over a larger field like $\mathbf Q(\sqrt[n]{p})$, perhaps since the polynomial has degree relatively prime to the degree of the field extension.
Comment: @TakamotoYuji it's good that she was honest with the students about what she had done, but bad that she put a problem on a test  without first solving it fully using only methods covered in the course.
Comment: If it's a quiz problem then you probably were expected to do it in just a few minutes.  Are you *sure* you're remembering the problem correctly?
Comment: @KCd Yes, I do have the question paper with me. None of the people I know had solved it during or after the quiz.
Comment: When you find out from your instructor how it was expected to be solved as a quiz problem, please include that here or tell us if the problem had a mistake.
Comment: @KCd The instructor said that she tried to "generalize" a problem from Artin(for $p=2$), while "hoping" that a somewhat similar solution exists. So in short, she didn't think through the problem and just put it on the quiz. QED
Answer: Not really a quiz-appropriate solution, but...
Irreducibility over $\mathbb{Q}$:
Let $g(x)$ be a factor of $f(x) = x^{2p}+nx+n$ of degree $d$. Every root $\alpha$ of $g(x)$ satisfies $\alpha^{2p}+n\alpha+n = 0$, so
$$\alpha^{2p} = n(-1-\alpha).$$
Multiplying over all roots of $g$ gives
$$ g(0)^{2p} = \prod_{g(\alpha)=0} \alpha^{2p} = \prod_{g(\alpha)=0} n(-1-\alpha) = n^d g(-1).$$
Also, $g(-1)$ divides $f(-1) = (-1)^{2p}+n(-1)+n = 1$, and by the above equation $g(-1)$ is positive, so $g(-1) = 1$. So we have $$g(0)^{2p} = n^d.$$
If $p\not\mid d$, then $n$ is a perfect $p$th power. But this gives a contradiction, since $n = p+1$ is too small to be a $p$th power.
If $p\mid d$ and $g(x)$ is a nontrivial factor, then $d = p$. So $g(0)^{2p} = n^p$, which means $n$ is a perfect square. But then $p= m^2-1 = (m-1)(m+1)$ for some integer $m$. This contradicts the primality of $p$, unless $m=2$ and $p=3$.
So we have proven that the polynomial is irreducible for $p \ne 3$. For $p=3$, the above reasoning gives that $d=3$, $g(-1) = 1$, and $g(0) = \pm 2$ for each factor $g(x)$, which reduces the possible factorizations to two cases:
$$x^6 + 4x+4 = (x^3 + ax^2+ax + 2)\cdot(x^3 + bx^2 + bx + 2)$$
or
$$x^6 + 4x+4 = (x^3 + cx^2 + (c-4)x - 2)\cdot(x^3 + dx^2 + (d-4)x - 2).$$
Each of these cases can be shown to be impossible by comparing the coefficients for the $x^5$ and $x^1$ terms on both sides.

Irreducibility over $\mathbb{Q}(\sqrt[n]{p})$:
Consider an algebraic field extension $L/\mathbb{Q}$, and let $\sigma$ be any automorphism of $L$. Note that if $f(x) \in \mathbb{Q}[x]$ factors into two monic irreducible factors over $L[x]$ as
$$ f(x) = g_1(x)\cdot g_2(x),$$ then we can get another factorization of $f(x)$ by applying $\sigma$ coefficientwise to both sides:
$$ f(x) = \sigma(f(x)) = \sigma(g_1(x))\cdot\sigma(g_2(x)).$$
Since the irreducible factorization is unique up to order, $\sigma$ permutes the $g_i(x)$. If moreover $L$ is a Galois extension of $\mathbb{Q}$, then the subgroup of automorphisms that fix $g_1(x)$ and $g_2(x)$ has index 1 or index 2 in the Galois group of $L/\mathbb{Q}$. By the fundamental theorem of Galois theory, this implies that the coefficients of $g_1(x)$ and $g_2(x)$ either all lie in $\mathbb{Q}$ or all lie in the same quadratic subfield of $L$. If $f(x)$ is irreducible over $\mathbb{Q}$, then only the second case is possible.
Applying to this problem: Let $K= \mathbb{Q}(\sqrt[n]{p})$ and let $L$ be the Galois  closure of $K$, i.e. $L$ is the splitting field of $x^n - p$. In your post you basically showed that $$[\mathbb{Q}(\alpha, \sqrt[n]{p}) : K] = p \quad\text{ or }\quad [\mathbb{Q}(\alpha, \sqrt[n]{p}) : K]=2p,$$
i.e. $f(x)$ splits into two factors of degree $p$ or is irreducible over $K$.
The same basic idea applies to $L$ as well. The case $p=2$ is straightforward; for $p\ne 2$ we have $\sqrt{p} \in K$, so $x^n-p$ can be factored as
$$x^n-p = (x^{n/2}-\sqrt{p})(x^{n/2}+\sqrt{p})$$
over $K$. The degree of the splitting field of each factor can only have prime factors that are at most $\frac{n}{2} = \frac{p+1}{2} < p$, so the degree of $L$ is relatively prime to $p$. Hence by the same reasoning as in your post and by the argument above, $f(x)$ splits into two factors of degree $p$ or is irreducible over $L$.
Thus if $f(x)$ factors over $L$, it splits into two factors with coefficients in a quadratic subfield of $L$. If moreover $f(x)$ factors over $K$, then the quadratic field must be a subfield of $K$ as well, i.e. it must be $\mathbb{Q}(\sqrt{p})$, the only quadratic subfield of $K$.
In summary, $f(x)$ is reducible over $K$ if and only if it splits into two conjugate factors of degree $p$ over $\mathbb{Q}(\sqrt{p})$.
In that case we could then write $$f(x) = (a(x) + b(x)\sqrt{p})\cdot(a(x) - b(x)\sqrt{p}) = a(x)^2 - p \cdot b(x)^2.$$
This says that $f(x)$ would need to be perfect square modulo $p$. But $f'(x) \equiv n \pmod{p}$ is relatively prime to $f(x)$, so $f(x)$ is squarefree modulo $p$. Hence $f(x)$ is not reducible over $K$.


How to add data locally in many columns?

Question: someone can help me here ? How do I add data locally in many columns ?
I have tried but...
Below my code,
I tried to create more var like : "var salary = document.forms.MedList.salary.value; var test = document.forms.MedList.test.value;
localStorage.setItem(name, data, salary, test);
" etc, but It does not work...
I have to change my doShowAll function or something like this ?
function SaveItem() {

var name = document.forms.MedList.name.value;
var data = document.forms.MedList.data.value;
localStorage.setItem(name, data);
doShowAll();

}
function doShowAll() {
if (CheckBrowser()) {
    var key = "";
    var list = "
Nome	Estoque
\n";
    var i = 0;
    for (i = 0; i <= localStorage.length - 1; i++) {
        key = localStorage.key(i);
        list += "
" + key + "	\n"
                + localStorage.getItem(key) + "
\n";
    }
    if (list == "
Nome	Value
\n") {
        list += "
empty	\nempty
\n";
    }
    document.getElementById('list').innerHTML = list;
} else {
    alert('Cannot store Med list as your browser do not support local storage');
}

}
Comment: What do you mean 'many columns'? Local storage is key value pairs. You can have anything as the value, it's usually best to create an object, do a json stringify on it and store that.
Comment: I'm not entirely clear on what you're trying to do but like @Magrangs said, Localstorage is just key value pairs.  If you need to store multiple values in one key, put them inside an array and loop through them.  Also, you can't loop through localStorage like that, as it's not an array.  You'd want to do something like `for (var key in localStorage)` which loops through an object and it's keys.
Comment: Example
Column1:    Column2:  Column3:   Colunm4:
Datex          Datex1      -----            ------
Can't I do this with local storage ?
Comment: Brett84c Yeah, I want to store multiple values... How can I do it ?
Answer: Your best bet is to create an object and store that e.g.
var myObject = {
 name: document.forms.MedList.name.value,
 data: document.forms.MedList.data.value
}

localStorage.setItem("yourKey", JSON.stringify(myObject));

When you want to grab it out you can do:
var myObject = JSON.parse(localStorage.getItem("yourKey"));

and then access the name and data respectively:
myObject.name
myObject.data

If you wanted to store multiple values under one key, the value can be an array:
e.g.
var myObject = {
 name: document.forms.MedList.name.value,
 data: document.forms.MedList.data.value
}

var myObject2 = {
 name: document.forms.MedList2.name.value,
 data: document.forms.MedList2.data.value
}

localStorage.setItem("yourKey", JSON.stringify([myObject, myObject2]));

Comment: Think of local storage like a dictionary. You can have anything as the value, an array if you like
Comment: I get it.. I think haha, but I'm triyng here and does not work in my code... How do I use many keys inside for ?


Excel VBA - iterating through a list of entries to stack data from a table moving to multiple columns

Question: I'm trying to modify a previously written VBA script within an excel document. The aim of the script is basically to iterate through each column to produce on a single worksheet the relevant data to be parsed into a different program. It tries to clean the data (e.g. remove any -- etc.) and works fine.
For example it

Sub StackData()
    Dim SummaryTable As Range
    Dim OutRow As Long
    Dim r As Long, c As Long

    On Error Resume Next
    Set SummaryTable = Range("A1", Range("A1").End(xlDown).End(xlToRight))
    SummaryTable.Select
    'Convert the range

    Application.ScreenUpdating = False

    For c = 2 To SummaryTable.Columns.Count
        Set OutWs = Sheets.Add
        OutWs.Name = Replace("out" & Left(SummaryTable.Cells(1, c), 5), " ", "")
        OutWs.Range("A1:C1") = Array("Id", "FundWgt", "Fund")
        OutRow = 2
            For r = 2 To SummaryTable.Rows.Count

                If IsNumeric(SummaryTable.Cells(r, c)) Then

                    OutWs.Cells(OutRow, 1) = SummaryTable.Cells(r, 1)
                    OutWs.Cells(OutRow, 2) = SummaryTable.Cells(r, c)
                    OutWs.Cells(OutRow, 3) = SummaryTable.Cells(1, c)
                    OutRow = OutRow + 1

                Else
                    'do nothing
                End If
            Next r
    Next c
End Sub

The output that comes out per sheet

The issue has become is that we need to have two sets of data in the worksheet - a fund and its benchmark.
The data now looks

And I need the output to look like

I've tried a few things but I can't get it - I tried to make a summary worksheet where I declare the fund and benchmark here

but can't figure out the next step
Apologies if I've missed this elsewhere. I'm a bit new to this so any help appreciated!
Comment: Where do different benchmarks go? Are they stacked on top of each other with repeating ids?
Comment: Benchmarks shouldn't be printed separately, only when outputted concurrently for funds
Comment: This is certainly doable, but your screenshot of data is virtually useless for doing proper troubleshooting. It cannot be copy/pasted into a worksheet. One can try an OCR program, or manually enter it. Having to do either of these is discouraging to those who might assist you. To make the data useful edit your question to post it as text, perhaps using this [Markdown Tables Generator](https://www.tablesgenerator.com/markdown_tables), or possibly upload a workbook (with sensitive information removed) to some public website and post a link in your original question
Comment: Also, it seems from your data that for each ID you have five funds and three benchmarks.  Should your final table, therefore, have 150 rows?  If not, how are you doing the selections?
Answer: Thanks, understand and will try next time to do so.
For what it's worth I was able to figure out how to do it (might not be most efficient but seems to get it done).
Sub StackData()
'   Before running this, make sure you have a summary table with column headers.
'   The output table will have three columns.
    Dim SummaryTable As Range, found As Range, b As Range
    Dim OutRow As Long
    Dim r As Long, c As Long, bc As Long
    Dim OutWs As Worksheet
    Dim dataDate As String, benchmark As String

    Worksheets("Weights (Stocks)").Range("A7", "U7").Copy
    Worksheets("Weights (Stocks)").Range("A10").PasteSpecial xlPasteValues
    Worksheets("Weights (Stocks)").Range("A10:B10") = Array("SEDOL", "Company Name")
    dataDate = Worksheets("Weights (Stocks)").Range("A6")

    On Error Resume Next
    Set SummaryTable = Worksheets("Weights (Stocks)").Range("A10", Range("A10").End(xlDown).End(xlToRight))
    SummaryTable.Select
    'Convert the range

    Application.ScreenUpdating = False

    For c = 3 To SummaryTable.Columns.Count - 4 '-4 reflects benchmarks
        Set OutWs = Sheets.Add
        OutWs.Name = Replace("o_" & Left(SummaryTable.Cells(1, c), 18) & Right(dataDate, 8), " ", "")
        OutWs.Range("A1:F1") = Array("SEDOL", "CompanyName", "Fund", "Weight", "Benchmark", "BmkWgt")
        OutRow = 2
        Set found = Sheets("Mandates").Columns("A").Cells.Find(what:=SummaryTable.Cells(1, c), LookIn:=xlValues, lookat:=xlWhole)
        benchmark = found.Offset(, 1).Value
        Set b = Sheets("Weights (Stocks)").Rows("10").Cells.Find(what:=benchmark, LookIn:=xlValues, lookat:=xlWhole)
        bc = b.Column
            For r = 2 To SummaryTable.Rows.Count
                    If IsNumeric(SummaryTable.Cells(r, c)) Or IsNumeric(SummaryTable.Cells(r, bc)) Then

                        OutWs.Cells(OutRow, 1) = SummaryTable.Cells(r, 1)
                        OutWs.Cells(OutRow, 2) = SummaryTable.Cells(r, 2)
                        OutWs.Cells(OutRow, 3) = SummaryTable.Cells(1, c)
                        OutWs.Cells(OutRow, 4) = SummaryTable.Cells(r, c)
                        OutWs.Cells(OutRow, 5) = SummaryTable.Cells(1, bc)
                        OutWs.Cells(OutRow, 6) = SummaryTable.Cells(r, bc)
                        OutRow = OutRow + 1
                    Else
                        'do nothing
                    End If
            Next r
    Next c
End Sub


Is it possible to ride on windsurfing inside tube (tubular wave)?

Question: Surfing inside a tube "is surfing's single greatest act; the supreme maneuver, the ultimate conquest." Can it be done using windsuring (= board with rig) ?
Answer: Yes it is possible : A windsurfer getting barreled? kai_lenny making it happen for the first time at Pe'ahi!
Answer: It's practically impossible. I don't think one could find a perfect wave with a perfect running tube big enough to cover your rig. Besides that a windsurfer won't be able to control velocity, balance and projection (critical for that insane tube riding) inside a huge tube like that.


Trying to access FOR loop variables within inner class, it is a scope question

Question: First of all thanks for taking time to look at my question
I have an array of editText and an array of doubles, I have a listener for the editText, whenever I enter a new value into the editText I would like to update the value in the double array
So I thought I could use a for loop to scan through all the editText and in each iteration, it would update the elements in the double array,
right now I have the code as follows
however, in the method "public void onTextChanged" when I try to use x from the "FOR" loop it is giving me an error saying that x in accessed within inner class and must be declared final, but I do not want x to be final, can somebody help me find a way to do this?
In other posts people suggested setting x as global variable, and maybe in the for loop when x reaches a certain value reset it to 0?
Thank you in advance
public class Test1 extends AppCompatActivity {
//In Test1 activity scope
    EditText editText1;
    EditText EditText2;
    EditText EditText3;
    String Results;
//I have my double array
   double doubleArray[] = new double[] {
            0.0,
            0.0,
            0.0,
    };
//declare the doubles that will be assigned in the double array
    double double1 = 0.0;
    double double2 = 0.0;
    double double3 = 0.0;
/*My editText array, here is where I'm struggling,
I don't know how and where to create an editText array,
or if I'm using the correct syntax, also I feel that
editText1,2,and 3 should not be initialized here*/
EditText[] editTextArray = new EditText[] {
            (EditText)findViewById(R.id.editText1),
            (EditText)findViewById(R.id.editText2),
            (EditText)findViewById(R.id.editText3),
};
//In the onCreate method
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_Test1);
    for (int x = 0; x < editTextArray.length; x++) {
            editTextArray[x].addTextChangedListener(new TextWatcher(){
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    try {
                        Results = editTextArray[x].getText().toString();
                        if (Results.equals("")) {
                            Results = "0.0" ;
                            doubleArray[x] = Double.parseDouble(Results);
                        }
                        else {
                            doubleArray[x] = Double.parseDouble(Results);
                        }
                        LetsFillTheVariables();
                    }
                    catch(NumberFormatException e){}
                }
            });
    }

    private void LetsFillTheVariables() {
        double1 = doubleArray[0];
        double2 = doubleArray[1];
        double3 = doubleArray[2];

    }

}

Answer: You can create a temporary final variable:
for (int x = 0; x < editTextArray.length; x++) {
    final int idx = x;
    editTextArray[idx].addTextChangedListener(new TextWatcher(){
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                Results = editTextArray[idx].getText().toString();
                if (Results.equals("")) {
                    Results = "0.0" ;
                    doubleArray[idx] = Double.parseDouble(Results);
                }
                else {
                    doubleArray[idx] = Double.parseDouble(Results);
                }
            }
            catch(NumberFormatException e){}
        }
    });
}

Comment: Thank you for your response, theshyelf, I think it will work, but I may have a bigger problem on this subject, I will edit my code in the post


Programmatically set class on extended field type

Question: Earlier I created an extended version of the Node class. I called it AbleNode and it extended BaseNode. In order to set all nodes to this node type I added this to my custom .module file
function ablecore_entity_type_build(&$entity_types){
    if(isset($entity_types['node'])){
        $entity_types['node']->setClass('Drupal\ablecore\Plugin\Node\AbleNode');
    }
}

This works fine but I'm not sure how to do this with an extended field type. Here is the code for my field class that is extending the BaseFileFieldItemList class
<?php
namespace Drupal\ablecore\Plugin\Field\FieldType\FileFieldItemList;
/**
 * @file AbleNode.php
 */
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList as BaseFileFieldItemList;

class AbleFileFieldItemList extends BaseFileFieldItemList {
    public function style($image_style) {
        $image_style = \Drupal\image\Entity\ImageStyle::load($image_style);
        if (!empty($image_style)) {
            return $image_style->buildUrl($this->getEntity()->getFileuri());
        } else {
            return false;
        }
    }
}

I see how I was able to turn all nodes into AbleNodes, but I'm not sure how to make all FileFieldItemLists into AbleFileFieldItemLists. Is there a hook I can use to setClass on the field whenever I encounter it? Keep in mind that I'm not trying to create a brand new field, I just want to give more functionality to existing field types.
Answer: This is untested, but I'm pretty sure you just need to change the list class for the field types using hook_field_info_alter():
function ablecore_field_info_alter(&$info) {
  foreach ($info as &$field) {
    if ($field['list_class'] == '\Drupal\file\Plugin\Field\FieldType\FileFieldItemList') {
      $field['list_class'] = '\Drupal\ablecore\Plugin\Field\FieldType\AbleFileFieldItemList';
    }
  }
}


Get Child Data from large XML file

Question: I have an large XML file (26,434 lines) that I'm working with.
Excerpt XML:
<row name="Scorned Syndicate" shortName="-SS-" allianceID="1778325832" executorCorpID="98020631" memberCount="29" startDate="2010-08-14 00:29:00">
    <rowset name="memberCorporations" key="corporationID" columns="corporationID,startDate">
        <row corporationID="98020119" startDate="2011-02-09 04:52:00" />
        <row corporationID="98020631" startDate="2011-02-23 23:55:00" />
    </rowset>
</row>

By searching here I've found how I can get the alliance name and short name but now I want the corporationID
$xml = new XMLReader();
$xml->XML( $xmlString );

while( $xml->read() ) {
  if( 'row' === $xml->name ) {
        echo $xml->getAttribute('name') . ' '. $xml->getAttribute('shortName').'
';

        $xml->next();
    }
}

I researched enough to know I need to utilize a streaming reader for efficiency but not sure how to get the last part of my data.
Answer: When you use the next() function in the XMLReader the subtrees are skipped. Your while statement should advance it through automatically. If you need to see output before the entire file is parsed you might consider ob_flush, otherwise it would be better to create an array so that the format is more customizable.
Comment: Thanks, I removed `$xml->next();` and added `$xml->getAttribute('corporationID');` and worked like a charm.

Get Child Data from large XML file


Commerce Product with diffrent prices for different shops

Question: Working with Drupal 7 on a comparison site where a product is sold at different price rates at different physical shops. Now there about 300 of these shops. Going by Commerce default setup, I would have to create 300 product types or products and also create 300 product display nodes, which will be insane.
Since the product name, image, (and other attribute is going to be the same, I thought to create a single product display content type that has a price field and create a single product type with all the default fields except price. So with the content type, several product display nodes can be created that then references the single product type. Great right? But the price field in the product type is locked (you cannot delete it).
What other more civilized process is available to achieve my goal, as I need the Add to cart button on each product so as to be able to add to cart and compare the prices onwards.
I have seen a similar question (Drupal Commerce: How to handle billions of product combinations?) go unanswered, hopefully commerce has matured these past three years. Thank you.
Answer: To resolve the product display <-> product issue, I'd be using Inline Entity Form to embed the product form right into the product display node form. However, that doesn't address your need to have hundreds of unique prices corresponding to different physical locations. That's another issue entirely that we would typically refer to as pricelist functionality.
We do have a Commerce Pricelist module, but since "Store" wasn't a core entity type in Drupal 7, there is no pricelist variant correlating to a store. You'll likely need to enhance that module yourself to make it "simple" for end users. Other options would be dependent on your greater site IA ... and it's worth noting that store based product availability and pricing would be better suited to Drupal 8 if there's any chance at all at upgrading.
Comment: Thanks @ryan-szrama I will look into the pricelist module


How to track mail correspondances

Question: Does anybody know if it is possible to find out if an email in my Inbox is a repsonse to a mail I have sent earlier?
Example: I send an email to person A with a question. When person A responds I would like to link my original mail to his response. My aim is to save the entire mail correspondance in a custom folder.
I have tried adding a MailItem.UserProperty to the E-mail object but apparently it doesn't get send.
An alternative solution I have thought about is to add an invisble text within the mail body that I can search when the response is recieved (assuming my original mail will be included in the response).
Comment: Possible duplicate of [Retrieving all Outlook messages in same thread](http://stackoverflow.com/questions/18350338/retrieving-all-outlook-messages-in-same-thread).
Answer: The MailItem class provides the following properties for tracking conversations:

ConversationID - a string that uniquely identifies a Conversation object that the MailItem object belongs to.
ConversationTopic - a string representing the topic of the conversation thread of the Outlook item. It is the normalized subject of the message, the subject without the prefix strings.
ConversationIndex - a string that indicates the relative position of the item within the conversation thread.

As you may see the conversation grouping depends on the subject line.
You can use the GetConversation method of the MailItem class to get a Conversation object that represents the conversation to which this item belongs. Be aware, GetConversation returns Null (Nothing in Visual Basic) if no conversation exists for the item. No conversation exists for an item in the following scenarios:

The item has not been saved. An item can be saved programmatically, by user action, or by auto-save.
For an item that can be sent (for example, a mail item, appointment item, or contact item), the item has not been sent.
Conversations have been disabled through the Windows registry.
The store does not support Conversation view (for example, Outlook is running in classic online mode against a version of Microsoft Exchange earlier than Microsoft Exchange Server 2010). Use the IsConversationEnabled property of the Store object to determine whether the store supports Conversation view.

For example:
<code> public void DemoConversation()
 {
   object selectedItem = Application.ActiveExplorer().Selection[1];
   // This example uses only
   // MailItem. Other item types such as
   // MeetingItem and PostItem can participate
   // in the conversation.
   if (selectedItem is Outlook.MailItem)
   {
      // Cast selectedItem to MailItem.
      Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;
      // Determine the store of the mail item.
      Outlook.Folder folder = mailItem.Parent as Outlook.Folder;
      Outlook.Store store = folder.Store;
      if (store.IsConversationEnabled == true)
      {
          // Obtain a Conversation object.
          Outlook.Conversation conv = mailItem.GetConversation();
          // Check for null Conversation.
          if (conv != null)
          {
             // Obtain Table that contains rows
             // for each item in the conversation.
             Outlook.Table table = conv.GetTable();
             Debug.WriteLine("Conversation Items Count: " + table.GetRowCount().ToString());
             Debug.WriteLine("Conversation Items from Table:");
             while (!table.EndOfTable)
             {
                Outlook.Row nextRow = table.GetNextRow();
                Debug.WriteLine(nextRow["Subject"] + " Modified: " + nextRow["LastModificationTime"]);
             }
             Debug.WriteLine("Conversation Items from Root:");
             // Obtain root items and enumerate the conversation.
             Outlook.SimpleItems simpleItems = conv.GetRootItems();
             foreach (object item in simpleItems)
             {
                // In this example, enumerate only MailItem type.
                // Other types such as PostItem or MeetingItem
                // can appear in the conversation.
                if (item is Outlook.MailItem)
                {
                   Outlook.MailItem mail = item as Outlook.MailItem;
                   Outlook.Folder inFolder = mail.Parent as Outlook.Folder;
                   string msg = mail.Subject + " in folder " + inFolder.Name;
                   Debug.WriteLine(msg);
                }
                // Call EnumerateConversation
                // to access child nodes of root items.
                EnumerateConversation(item, conv);
             }
          }
       }
    }
 }

 void EnumerateConversation(object item, Outlook.Conversation conversation)
 {
     Outlook.SimpleItems items = conversation.GetChildren(item);
     if (items.Count > 0)
     {
        foreach (object myItem in items)
        {
           // In this example, enumerate only MailItem type.
           // Other types such as PostItem or MeetingItem
           // can appear in the conversation.
           if (myItem is Outlook.MailItem)
           {
              Outlook.MailItem mailItem = myItem as Outlook.MailItem;
              Outlook.Folder inFolder = mailItem.Parent as Outlook.Folder;
              string msg = mailItem.Subject + " in folder " + inFolder.Name;
              Debug.WriteLine(msg);
           }
           // Continue recursion.
           EnumerateConversation(myItem, conversation);
        }
     }
  }
</code>

How to track mail correspondances


Problem getting xml in a rails3 app

Question: I'm having a pretty weird problem : requesting data with xml format in a rails 3 app works on my local environment but on my hosted environment, I get a NoMethod Error. More precisely :
undefined method `type' for nil:NilClass
Here is the method I'm talking about :
def getclosest
    radius = params[:radius].gsub(",",".").to_d
    origin = [params[:lat].gsub(",",".").to_d,params[:lng].gsub(",",".").to_d]

    @groceries = Grocery.within(radius, :origin => origin)

     respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @groceries }
        end
    end

This method is called when I go to the url : http://www.mysite.com/groceriesclosest/myradius/mylat/mylng
The .html works but the .xml doesnt and I get the error described above.
However, in my local environment, when I go to http://localhost:3000/groceriesclosest/radiues/lat/lng.xml it works fine
Any idea what's going wrong on my hosted version ? Btw, I'm using Mongrel as webserver.
Thanks !
Edit
Some precisions : first, the data set in "prod" is the same as locally and second, it's the line format.xml  { render :xml => @groceries } that causes the error.
Here is part of the application trace :
app/controllers/groceries_controller.rb:92:in block (2 levels) in getclosest
app/controllers/groceries_controller.rb:90:in getclosest
And some part of the full trace :
Comment: is your data set different in prod? Which line results in error?  Can you post the stack trace?
Comment: Data sets are the same. I edited the message to answer your questions. Let me know if you need more from the trace. Thanks !
Answer: Got the same error in the following line:
respond_with Article.all.comments

this works in console but not in my xml response.
I solved it by changing that line to
respond_with Article.all.comments.all

which gives the same response in the console though.
So maybe you could try something like
render :xml => @groceries.all

instead.

Problem getting xml in a rails3 app


Weak operator topology and matrix representation

Question: For simplicity let $H$ be the separable Hilbert space and $(e_i)_i$ be a fixed orthonormal basis. Weak operator topology on $B(H)$ is usually defined using seminorms $|(Tu,v)|$ where $u,v$ are vectors in $H$. Let us denote $\mathcal{T}$ the topology induced by the seminorms $|(Te_i,e_j)|$. I believe this is also the topology induced by all $|(Tu,v)|$ where $u,v$ are finite linear combination of $e_i$'s. What is the relation between $\mathcal{T}$ and WOT? Do they agree on norm bounded sets? I guess yes because
$||(Tu,v)|-|(Tu_0,v_0)||\leq|(Tu,v)-(Tu_0,v_0)|=|(Tu-Tu_0,v)+(Tu_0,v-v_0)|$
$\leq||T||\cdot||u-u_0||\cdot||v||+||T||\cdot||u_0||\cdot||v-v_0||$
So for any fixed $u,v$ and $\epsilon>0$, if $u_0,v_0\in \text{span}\{e_i\mid i\in\mathbb{N}\}$ are close enough to $u,v$ and there is a uniform bound on $||T||$, then $|(Tu_0,v_0)|\leq \epsilon$ implies $|(Tu,v)|\leq 2\epsilon$.
Now since we fix a basis $(e_i)_i$ we can regard operators as infinite matrices and $(Te_i,e_j)$ is the $j,i$-th entry. Therefore if the above calculation is correct then on bounded sets WOT can be viewed as "entrywise convergence topology". This looks more comfortable and intuitive for me, for example it becomes even clearer that unit ball is compact because we can view it as a subspace of $[-1,1]^{\mathbb{N}^2}$ (I found that I don't know how to argue it is a closed subspace without using the fact that it is same as WOT). Similarly strong operator topology may be viewed as "columnwise convergence topology".
Answer: The answer is no.  Although $\mathcal T$ coincides with the WOT on bounded sets, as observed by the OP, these topologies
do not coincide over the whole of
$B(H)$.
One very nice point of view from which to understand this question is the theory of duality.  Suppose $B$ is a complex
vector space (I am using the letter $B$ here because the application will be for $B=B(H)$).   Suppose also we are given
a set   $\Phi $  of linear functionals on $B$.
One may then define a topology $\mathcal T$ on $B$ using the seminorms
$$
  T\in B\mapsto |\varphi (T)|\in \mathbb R,
  $$
for every $\varphi $ in $\Phi $.
It is evident that every $\varphi $ in $\Phi $ is $\mathcal T$-continuous and hence also every linear combination of functionals in
$\Phi $.
The key fact is that nothing else is continuous!  In other words, the topological dual of $(B,\mathcal T)$ is precisely
the linear span of $\Phi $ within the algebraic dual of $B$.
Taking $B=B(H)$ and $\Phi $ the set of linear functionals of the form
$$
  T\in B(H)\mapsto \langle Te_i, e_j\rangle ,
  \tag{1}
  $$
we may ask whether or not a linear  functional of the form
$$
  T\in B(H)\mapsto \langle Tu, v\rangle ,
  \tag {2}
  $$
is $\mathcal T$-continuous,  for given vectors $u$ and $v$ in $H$.
The answer will be negative if $u$ and $v$ are
infinite linear combinations of basis elements since one may easily prove that  (2) is not a finite linear combination
of functionals as in (1).
Comment: I am aware that they don't agree on the whole $B(H)$...Just want to be certain that they agree on bounded sets since it does not seem to be mentioned anywhere.
Comment: Well, then I guess I misunderstood your question.  But again, yes, you are correct about the two  topologies coinciding on bounded sets.


Expectation of a Random Subset of the Roots of Unity.

Question: Let $p$ be a prime.  If $1_A(x)$ denotes the indicator function of the set $A\subset\mathbb{Z}/p\mathbb{Z}$ and $$\hat{1}_A(t):=\frac{1}{p}\sum_{n=1}^p 1_A(n)e^{2\pi i \frac{nt}{p}}$$ denotes the Fourier transform of $1_A$, then what can be said about $$\mathbb{E}\left( \sup_{t\neq 0} |\hat{1}_A(t)|\right)?$$  Do we have an upper bound of the form $O\left(\frac{\log p}{\sqrt{p}}\right)$ as $p$ goes to infinity?
Alternate wording:  For each subset $A$ of the $p$ roots, let $Sum(A)$ to denote the sum of the elements in $A$, and look at $A^t:=\{a^t:\ a\in A\}$ for integers $0<t<p$.  Then, what is the expectation of the maximum of the sum over $t$?  How well can we bound $$\mathbb{E}_A\left(\sup_{t} \ \left|Sum\left(A^t\right)\right|\right).$$
Remarks: This question originated from an optional homework problem in my Arithmetic Combinatorics class.  I tried some fairly long and drawn out things that did not work.  Also, note that since $p$ is prime, taking the power for $0<t<p$ corresponds exactly to the automorphisms.
Comment: This might be a silly question, but how do you take the sup of a set of complex numbers ?
Comment: Just an aside regarding terminology: It might be good to be cautious with the use of the terms "characteristic function" and "Fourier transform" here. Indeed, in probability the use of the term "[characteristic function](http://en.wikipedia.org/wiki/Characteristic_function_%28probability_theory%29)" is interestingly enough a Fourier transform and, the term "[indicator function](http://en.wikipedia.org/wiki/Indicator_function)" is used for functions like $1_A$ that are usually referred to as "characteristic functions" in other branches.
Comment: @JoelCohen: Sorry! My mistake, I forgot some critical absolute value bars.
Comment: Disregard my comment last night, I was thinking of a similar but different problem.
Answer: A simple probabilistic approach works. In fact, I get a bound of $O(\sqrt{p \log p})$ on the expectation of $\sup_t |Sum(A^t)|$.
Step 1: In this step, let's assume $t=1$, and bound the random variable $Sum(A)$ where $A$ is a uniformly random subset of the roots of unity $\{ 1, \zeta, \ldots, \zeta^{p-1} \}$. Let $X_i$ be the complex random variable that counts the contribution of $\zeta^i$ to the sum; i.e., $X_i$ equals $\zeta^{i}$ if $A$ contains it, and zero otherwise.
Since the $X_i$'s are independent, we may think of bounding their sum using the Chernoff-Hoeffding bound. There is a slight annoyance that our random variables are complex-valued; one simple fix is to bound the real and imaginary parts separately, and then combine them using the triangle inequality. Doing this calculation, we find that the probability that $|Sum(A) - E[Sum(A)]| = |Sum(A)|$ exceeds $2c \sqrt{p \log p}$ is at most $\exp \left(- \frac{2 c^2 p \log p}{4p} \right) = p^{-c^2/2}$.
Step 2: For any fixed $t$, the set $B = A^t$ is again a uniformly random subset of the roots of unity, since the $t$-power map simply permutes the roots. So the above analysis, holds if we replace $A$ by $A^t$ (where $t$ is any fixed number). Then, by the union bound, the probability that $\sup_t |Sum(A^t)| \geq 2c \sqrt{p \log p}$ is at most $(p-1) \cdot p^{-c^2/2} = o(1/p)$, choosing $c$ large enough.
This tail inequality can be easily be converted to a bound on the expectation.


Image misaligned in buttons in firefox

Question: I'm trying to convert some divs to buttons. They work fine on ie and chrome but on firefox even though I set the images and divs to the same size the images are still bigger than the divs. The images also don't touch the left border of the div as they should even though they do in the other browsers. I have tried setting a browser specif css rule but it doesn't appear to have any affect. Does any one know how i can solve this? By the way I have only converted the first div to a button at the moment.
The page that I'm having a problem with is hear (the button is near the bottom of the page and is titled "Fears/phobias"):
http://www.swanleyhypnotherapist.co.uk/
Comment: Put the minimum that demonstrated the problem into fiddle. Might end up with some help
Comment: I understand this doesn't answer your question directly, but from a semantics point of view, it would be more appropriate to use the `` tag instead of the `button` tag.
Comment: Thanks. I didn't do that to start with because im sure when I did this before at school it didn't work. Though it appears to do now. Thanks.
Comment: Can you use background images? Better yet, CSS sprites? Then it wouldn't matter what kind of element you wanted to use (DIV, BUTTON, A, etc.), as long as you can give the element a `display: inline-block` or `display: block` attribute. Adjusting the position of the background image (x, y) should be trivial. To move the text away from the background image (if there's a visual collision), use `text-indent` to adjust the distance between background image and text. Obviously, if you simply want the entire background to be an image, you needn't worry about `text-indent`.
Comment: In my version of FireFox (19.0) that button - and all buttons - appear to be fine.
Comment: Also in my version of FireFox (19.0) that button - and all buttons - appear to be fine.
Answer: button.graphic {
    padding: 0,
    margin: 0,
    boder: 0
}

for a start, you seriously need to post code...

Image misaligned in buttons in firefox


Obter posição de wxTextCtrl

Question: Como faço para obter a posição (x e y) de um WxTextCtrl?
Não achei nada a respeito nem na documentação.
Answer: Use o método GetPosition() disponível na wxWindow. Está na documentação. Você não achou provavelmente porque ainda não entende bem herança de orientação a objeto. Uma classe tem tudo o que foi criado nela mais o que herdou das classes superiores, então tem que olhar a documentação das classes que fazem parte da classe que está usando. É claro que tem documentação que coloca tudo, fica mais fácil mas não é o caso desta biblioteca, então você tem que percorrer a hierarquia.
Comment: Estava procurando apenas na classe wxTextCtrl, sinal que devo estudar mais, rs.

Obter posição de wxTextCtrl


Use taxonomy path-alias

Question: I've been working playing with the Facet API Search lately and I liked a lot the option that Facet API provides to use the alias of the taxonomies in the URL.
I was wondering if there is a chance to do the same in the Views. eg to be able to use the taxonomy alias as a token to construct a link. What I would like to achieve is to be able to construct in the Views a URL that can take me to a Faceted Search page so I can pre-filter it.
I know that is a bit redundant to be doing it, but for the project I work on, is something that was specifically requested. In the Views, there is no way to be able to get the alias of a taxonomy as a field. The only things I've seen so far, is to mimic the re-writing of taxonomy using PHP code here and here .
I tried to find a module that would help use the alias but nothing had come up. Also, here in the forum, I had found similar issues but nothing related to my question about taxonomies.
How to filter a View with Taxonomy alias
Get a node alias as a field value
Answer: Nevermind, I managed to do this via a module I wrote.
To whom it may concern, the idea is to create a hook override for the hook field formatter.

Use taxonomy path-alias