Erro no Scaffolding durante geração da View

Question: Estou criando um projeto novo usando EF Power Tools e estou com o seguinte erro:

Error
  There was an error running the selected code generator:
  'A configuration for type 'TST2.Models.Course' has already been added.
  To reference the existing configuration use the Entity() or ComplexType() methods.

Consigo contornar o erro (Gerando a View sem um context), mas preciso entender o que fiz de errado.
Segue minha entidade:
public class Course
{
    public Course()
    {
        this.StudentGrades = new List<StudentGrade>();
        this.People = new List<Person>();
    }

    public int CourseID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public int DepartmentID { get; set; }
    public virtual Department Department { get; set; }
    public virtual OnlineCourse OnlineCourse { get; set; }
    public virtual OnsiteCourse OnsiteCourse { get; set; }
    public virtual ICollection<StudentGrade> StudentGrades { get; set; }
    public virtual ICollection<Person> People { get; set; }
}

Código para Mapping :
public class CourseMap : EntityTypeConfiguration<Course>
{
    public CourseMap()
    {
        // Primary Key
        HasKey(t => t.CourseID);

        // Properties
        Property(t => t.CourseID)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(t => t.Title)
            .IsRequired()
            .HasMaxLength(100);

        // Table & Column Mappings
        ToTable("Course");
       Property(t => t.CourseID).HasColumnName("CourseID");
       Property(t => t.Title).HasColumnName("Title");
        Property(t => t.Credits).HasColumnName("Credits");
        Property(t => t.DepartmentID).HasColumnName("DepartmentID");

        // Relationships
        HasMany(t => t.People)
            .WithMany(t => t.Courses)
            .Map(m =>
                {
                    m.ToTable("CourseInstructor");
                    m.MapLeftKey("CourseID");
                    m.MapRightKey("PersonID");
                });

        HasRequired(t => t.Department)
            .WithMany(t => t.Courses)
            .HasForeignKey(d => d.DepartmentID);

    }
}

Código Contexto:
 public class SchoolContext : DbContext
 {
    static SchoolContext()
    {
        Database.SetInitializer<SchoolContext>(null);
    }

    public SchoolContext()
        : base(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True")
    {   }

    public DbSet<Course> Courses { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
    public DbSet<OnlineCourse> OnlineCourses { get; set; }
    public DbSet<OnsiteCourse> OnsiteCourses { get; set; }
    public DbSet<Person> People { get; set; }
    public DbSet<StudentGrade> StudentGrades { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CourseMap());
        modelBuilder.Configurations.Add(new DepartmentMap());
        modelBuilder.Configurations.Add(new OfficeAssignmentMap());
        modelBuilder.Configurations.Add(new OnlineCourseMap());
        modelBuilder.Configurations.Add(new OnsiteCourseMap());
        modelBuilder.Configurations.Add(new PersonMap());
        modelBuilder.Configurations.Add(new StudentGradeMap());
    }
}

Answer: Isso é realmente um erro e me perturbou por um bom tempo, Eu resolvi da seguinte forma só assim funcionou comigo.
Tem que mudar onde esta assim por exemplo:
public DbSet<OnsiteCourse> OnsiteCourses { get; set; }

Para:
public IDbSet<OnsiteCourse> OnsiteCourses { get; set; }

Muda o DbSet para IDbSet depois da um Clean e um Rebuild e tenta gerar a view, que vai funcionar. Sem precisar mexer com o Mappings.
Answer: Esta mensagem de erro:

'A configuration for type 'TST2.Models.Course' has already been added. To reference the existing configuration use the Entity() or ComplexType() methods.

Quer dizer que esta configuração:
public class CourseMap : EntityTypeConfiguration<Course>
{ ... }

Já existia, e que o Power Tools não irá gerá-la novamente.
É apenas uma orientação. Não uma mensagem de erro. A configuração está correta.
Comment: O Power Tools gerou esses modelos. Utilizando o scaffolding para criar uma View, aparece a mensagem de erro. Não estou tentando gerar novamente, estou criando uma View em cima do modelo do Power Tools.
Comment: Sim, mas a geração da View tenta criar a configuração novamente, possivelmente porque tenta criar algum passo com *Controller* também. Se você quer gerar só a *View*, use o *Scaffolding* do Visual Studio, que está nos menus do botão direito.
Comment: Então, é exatamente isso que vc descreveu que estou fazendo. E o erro insiste em impedir a ação. Como eu disse, se eu não selecionar um data context, ele consegue criar a View. É uma forma de contornar mas não de solucionar o erro.
Comment: Entendi. Bom, eu posso melhorar a resposta, mas você vai ter que abandonar esses arquivos de configuração da entidade.
Answer: Tente limpar o ComponentModelCache, o cache consertará no próximo rebuild.

Feche o Visual Studio
Delete a pasta ComponentModelCache
C:\Users\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
Reinicie o Visual Studio

Obs: 14.0 é para versão visual studio 2015.
Também funciona pras outras versões


compiler error when using #include "filename"

Question: I read that

#include filename causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

A short example is below. Compiling with g++ main.cpp f.h f.cpp gives compiler error. The program runs correctly after I remove the #include in f.cpp. I have two questions.

What is the cause of error in the original program?
Does #include filename really just replace the directive with the content of the quoted file?

I ask the second question because the program also runs correctly when I replace the problematic line with int f(); (which is the exact content of f.h).
Thank you.

f.h
int f();

f.cpp
#include "f.h" // problem
int f() { return 1; }

main.cpp
#include <iostream>
#include "f.h"
int main() {
    std::cout << f() << std::endl;
}

The error message of running g++ main.cpp f.h f.cpp with original program is
f.cpp: In function 'int f()':
f.cpp:2:5: internal compiler error: in ggc_record_overhead, at ggc-common.c:1013
 int f() { return 1; }
     ^
0x8ae8eb ggc_record_overhead(unsigned long, unsigned long, void*, char const*, int, char const*)
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/ggc-common.c:1013
0xc4af71 ggc_internal_alloc_stat(unsigned long, char const*, int, char const*)
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/ggc-page.c:1317
0xa48462 get_combined_adhoc_loc(line_maps*, unsigned int, void*)
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/libcpp/line-map.c:136
0xa9a5ff gimple_set_block(gimple_statement_base*, tree_node*) [clone .isra.8]
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple.h:1489
0xa9a5ff lower_stmt
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple-low.c:239
0xa9a5ff lower_sequence
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple-low.c:206
0xa9b481 lower_gimple_bind
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple-low.c:415
0xa9b5c6 lower_function_body
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple-low.c:118
0xa9b5c6 (anonymous namespace)::pass_lower_cf::execute() [clone .lto_priv.4979]
        /apps2/tools/gcc/4.9.2/gcc-4.9.2-src/gcc/gimple-low.c:184
Please submit a full bug report,
with preprocessed source if appropriate.
Please include the complete backtrace with any bug report.
See <http://gcc.gnu.org/bugs.html> for instructions.

UPDATE:
I found that g++ main.cpp f.cpp f.h fails because there is a file f.h.gch in my directory. The program compiles correctly after I cleanup that .gch file.
(I'm sorry that I did not provide this information before as I just noticed it.)
However, g++ main.cpp f.cpp f.h generates f.h.gch. So if I compile twice consecutively, it'll be an error.
Following Donghui's advice, removing f.h from g++ also compiles correctly. And, it does NOT generate the f.h.gch file.
My question is likely a duplicate of What is a .h.gch file?
Comment: "What is the cause of error in the original program? " What does the error message tell you?
Comment: Yes, #include filename replaces the directive with the content of the quoted file. The code you've shown should work. Something else (that you didn't show) caused the "problem". Tell us more. In particular, how did you compile? What was the error message?
Comment: @DonghuiZhang Thank you. I have now included the error message.  It says "internal compiler error", which I don't quite understand.
Comment: @juanchopanza I have now included the error message, thanks.
Comment: "Internal compiler error" is always a compiler bug. You might be able to work around it, but it's still the compiler's fault.
Comment: @PeteBecker Thank you. As in my update, the compiler error was caused by a `.gch` file in my directory. I have now marked the question as a duplicate.
Answer: In your g++ command, remove f.h.
Comment: @Donghui Thank you for the response. As in my update, the compiler error was caused by a `.gch` file in my directory. I have now marked the question as a duplicate.
Comment: That might work around the compiler bug, but there's nothing inherently wrong with the code and the command line as written. Yes, compiling a header is usually a mistake, but there's nothing illegal there.


searching a Char letter by letter

Question: Trying to search for patterns of letters in a file, the pattern is entered by a user and comes out as a String, so far I've got it to find the first letter by unsure how to make it test to see if the next letter also matches the pattern.
This is the loop I currently have. any help would be appreciated
    public void exactSearch(){
    if (pattern==null){UI.println("No pattern");return;}
    UI.println("===================\nExact searching for "+patternString);
    int j = 0 ;
    for(int i=0; i<data.size(); i++){

        if(patternString.charAt(i) == data.get(i) )
        j++;
        UI.println( "found at " + j) ;

    }
}

Comment: sorry wasn't clear i need to find all this instances that occur not just one
Comment: do you want the positions of where the words matches a `pattern`, or you just a need a `list` of all the `substrings` that match your `pattern` ?
Comment: just the position, for example if my pattern was ABC, and the data was AAACABCCCABC, it would print out "found at 4, found at 8
Comment: you mean found at 4 and 9 . correct?
Answer: You need to iterate over the first string until you find the first character of the other string. From there, you can create an inner loop and iterate on both simultaneously, like you did.
Hint: be sure to look watch for boundaries as the strings might not be of the same size.
Comment: how would i iterate over the first string
Comment: The main idea is to have two loops; in the outer loop you'll do what you're doing, but compare your data.get(i) only to patternString.charAt(0), since all you need to know is whether it matches the first character of the pattern.
The moment you find it, then you will start your inner loop, where you'll test both strings (data and patternString) together, using a new index (the index will be the same for both strings).
Comment: int j = 0;
        int i = 0;
        while (i < data.size()) {

            if (patternString.charAt(0) == data.get(i)) {
                if (patternString.charAt(j) == data.get(i)) {
               j++;
               i++ ;
               if (j == patternString.length()) {
                UI.println("Found pattern "
                                   + "at index " + (i));
            }
            }

            else { i++;}

}
}
Comment: You're getting closer! The index of the outer loop (i), however, should be increased only on the outer loop, otherwise it will move the character position. Try doing a table of values for some simple string, and watch carefulling how the two indexes behave in each loop. I would start with something small, like pattern: "ab" and data string: "cabcab".
Answer: You can try this :-
String a1 = "foo-bar-baz-bar-";
String pattern = "bar";

int foundIndex = 0;

while(foundIndex != -1) {
    foundIndex = a1.indexOf(pattern,foundIndex);
    if(foundIndex != -1)
    {
        System.out.println(foundIndex);
        foundIndex += 1;
    }

}

indexOf - first parameter is the pattern string,
second parameter is starting index from where we have to search.
If pattern is found, it will return the starting index from where the pattern matched.
If pattern is not found, indexOf will return -1.
Comment: that would work if i only needed to find it once however it needs to search letter by letter and find all instances not just one :) thanks for the help though
Comment: Looks like I couldnot understand you question properly. If data is "foo-bar-baz-bar-" and pattern is "bar", can you please tell me what should be the output ? Also is your pattern a regex  or simple string ?
Answer: String data = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = data.indexOf(pattern);

while (foundIndex > -1) {
    System.out.println("Match found at: " + foundIndex);
    foundIndex = data.indexOf(pattern, foundIndex + pattern.length());
}

Answer: Based on your request, you can use this algorithm to search for your positions:
1) We check if we reach at the end of the string, to avoid the invalidIndex error, we verify if the remaining substring's size is smaller than the pattern's length.
2) We calculate the substring at each iteration and we verify the string with the pattern.
        List<Integer> positionList = new LinkedList<>();
        String inputString = "AAACABCCCABC";
        String pattern = "ABC";

        for (int i = 0 ; i < inputString.length(); i++) {

            if (inputString.length() - i < pattern.length()){
                break;
            }

            String currentSubString = inputString.substring(i, i + pattern.length());
            if (currentSubString.equals(pattern)){
                positionList.add(i);
            }
        }
        for (Integer pos : positionList) {
            System.out.println(pos); // Positions : 4 and 9
        }

EDIT :
Maybe it can be optimized, not to use a Collection for this simple task, but I used a LinkedList to write a quicker approach.
Comment: the inpurtstring is a list so cant be substringed
Comment: I'm sure you can create a String from a list, or adapt this solution.

searching a Char letter by letter


Apache2 using insane amounts of memory

Question: On a server with 30GB of memory serving somewhat high-volume traffic.
For some reason recently Apache2 has started running threads with insane memory usage. 500MB-750MB per thread is not uncommon right now.
php.ini has memory_limit = 128M (php7.0 default).
Apache prefork config is on defaults.
The result is that we're running with only ~1GB of free memory.
What am I missing?
We have Nginx proxying requests and it's processes are more like ~60MB per thread. Here is a screenshot of running top
Top Screenshot
Any insight as to what could be driving this is appreciated!
Answer: From that top output it looks like Apache processes have 20-50MB "res" (resident) in memory. The "virt" isn't memory you need to worry about, generally, it can be mapped files and isn't actual RAM used.
I can see that you have 28GB of memory "cached". This is typically cached files. This is a good thing, it saves the OS from having to go to the disk to access files.
I think you may benefit from the "Linux Ate My RAM" website.
What exactly is the problem this is causing? Does your system every report "out of memory", or processes fail because of lack of RAM?
Comment: The cached memory thing makes sense now. Sorry - I'm not much of an infrastructure guy. Biggest challenge is having nginx 504 timeouts recently - trying to narrow down the possible performance bottlenecks.
Comment: For your 504's, you might try to capture `netstat -aeenp` as root periodically during these times.  Count the number of connections in time wait, close wait, etc.  This is sometimes hard to spot in logs.  If that is the issue, I can offer suggestions for a way around it.
Comment: It's a common misunderstanding. Suggest you gather information and post a question about the timeouts. curl showing the problem, applicable logs, and configurations would be key information to share.
Comment: You probably mean MB, not KB up there, since the numbers are in kilobytes already.
Comment: Thanks @TollefFogHeen, I wasn't sure what the units were
Comment: @TollefFogHeen - Wouldn't 668084 under VIRT translate to 668MB since it's in KB in `top` already?
Comment: @Aaron - Great suggestion. I will look at this and let you know if I have any questions.
Comment: @Wes, correct, but VIRT isn't very interesting, you want to look at RES. See the answer and links. :-)
Comment: @TollefFogHeen Thanks for helping me understand that. Looking at the RES numbers, it seems much more normal. Not an infrastructure guy but that's definitely helpful.

Apache2 using insane amounts of memory


How to play a particular portion of an audio file in Cocos2d

Question: I am playing an audio file named 'myTrack.mp3' with SimpleAudioEngine as:
<code>[[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"myTrack.mp3" loop:NO];
</code>
The audio if of the length of 00:17 seconds, and my plays the whole file. But now I need to play only the portion between time 00:08 and 00:14. Is it is possible in Cocos2d?
Thanks.
Answer: I am not familiar with SimpleAudioEngine but with the standard AVQueuePlayer you can do:
1) seekToTime. e.g. (<code>[_player seekToTime:CMTimeMakeWithSeconds(8.0, 1.0)]</code>)
2) then add time observer to the player:
<code> _timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, 1.0)
                                                  queue:NULL
                                             usingBlock:^(CMTime time) {
                                                 check current duration and stop the playback.
                                             }];
</code>
Comment: And if I remember correctly CocosDenshion uses AVAudioPlayer behind the scenes for (background) music playback. Don't think it's accessible through the simple interface, must be in CDAudioManager or similar.
Comment: Sorry, but what is the 'timeObserver' object type? And while adding those lines, I am getting Mach-O linker error: 'Undefined symbols for architecture i386:'. Can u help me pls?
Comment: id timeObserver. finally you can do [_player removeTimeObserver:_timeObserver] and set it to nil. strange issue with i386. what symbols?


Unable to set the data property xxx as the parent data structure is not set

Question: I currently use geofield to set latitude and longitude but rules gives me this error:

0 ms Unable to modify data "user:field-coordonnees:lon": Unable to set the data property lon as the parent data structure is not set.

So values are not set and I do not understand why, it's just a set data.
The value exists because I can see it in a "Show a message on the site". I've also tried to cast the value as Integer, nothing has changed.
Any idea ?
Configuration:

Geofield Map 7.x-2.3
Geofield 7.x-2.3
geoPHP 7.x-1.7
Answer: I've found the issue.
In fact insted of set a lat and a lon value, I had to use "Create geofield values from lat/lon".
Answer: If you see this error it's most likely that the developer forgot to add a proper check (or try/catch block) for his entity_metadata_wrapper() call. Better report this to the module you were using on the drupal.org/geofield page.


How can i prove that a cartesian product is isomorphic to another cartesian product

Question: $\def\<#1>{\left<#1\right>}\def\Z{\mathbb Z}\<\Z_6, \oplus> \times \<\Z_{10},\oplus>$ is isomorphic to $\<\Z_2, \oplus> \times \<\Z_{30}, \oplus>$
i know i have to prove that with the chinese remainder theorem but i cant see how.
I denote the group operation by $*$. $(x,y)*(z,w)=(a,b)$ from the first cartesian product. and $(t,s)*(u,v)=(a', b')$ from the second direct product
now $F(a,b)=(a',b')$ but what is $F$ here?
Thanks for any help!!!
Answer: This is the direct sum of two abelian groups (integers modulo n under addition).
$$\mathbb Z_m \oplus \mathbb Z_n \cong \mathbb Z_{mn}\text{ if and only if } \gcd(m, n) = 1$$
$\gcd(2, 3)$, so $\mathbb Z_6 \cong \mathbb Z_2\oplus \mathbb Z_3$ and $\gcd (3, 10) = 1$, so $\mathbb Z_{30} \cong \mathbb Z_3\oplus \mathbb Z_{10}.$
That gives us $$\mathbb Z_6\oplus \mathbb Z_{10} \cong \mathbb Z_2\oplus \mathbb Z_3 \oplus \mathbb Z_{10} \cong \mathbb Z_2 \oplus \mathbb Z_{30}$$
Comment: thanks for your fast answer!
Comment: Doesn't the Chinese Remainder Theorem say that $\Bbb Z_m \times \Bbb Z_n \cong \Bbb Z_{mn}$ iff $gcd(m,n)=1$? As opposed to $\Bbb Z_m \oplus \Bbb Z_n$?


How to attach token in a custom form field

Question: I have a custom form in Drupal 8. I need to attach tokens for fields of my form. Basically I want to add "Browse tokens" option for each field of my form.
Answer: token.module has various examples, for example this:
// Add the token tree UI.
$form['email']['token_tree'] = array(
  '#theme' => 'token_tree_link',
  '#token_types' => array('user'),
  '#show_restricted' => TRUE,
  '#weight' => 90,
);

This displays a link for tokens for the type user (and global tokens).
You can also use the #element_validate callback token_element_validate together with also adding #token_types to have it validated.
Comment: I am using '#theme' => 'token_tree_link',
      '#token_types' => array('user'),
      and i want to display only Users token not other tokens, What should i use? I have tried '#show_restricted' => TRUE,It doesn't make any difference.
Comment: As noted in @Calar's answer, limiting the options only to those defined by  `#token_types` can be achieved with `'#global_types' => FALSE,`
Answer: This is a copy from the "token.module".
function token_theme() {
  $info['token_tree_link'] = [
    'variables' => [
    'token_types' => [],
    'global_types' => TRUE,
    'click_insert' => TRUE,
    'show_restricted' => FALSE,
    'show_nested' => FALSE,
    'recursion_limit' => 3,
    'text' => NULL,
    'options' => [],
  ],
  'file' => 'token.pages.inc',
  ];

  return $info;
}

To avoid displaying the "global tokens" you need:
'global_types' => FALSE,

Code as a render element (don't forget the #(!)):
// Add the token tree UI.
$form['email']['token_tree'] = array(
 '#theme' => 'token_tree_link',
 '#token_types' => array('user'),
 '#show_restricted' => TRUE,
 '#global_types' => FALSE,
 '#weight' => 90,
);

Answer: $form['token_help'] = [
  '#theme' => 'token_tree_link',
  '#token_types' => ['user'],
];

https://www.drupal.org/documentation/modules/token


Deriving survival from hazard function

Question: EDIT: It was a simple typo (+ instead of *), but the values still aren't quite right. Leaving the original in case others find it useful
I'm fairly new to working with survival functions so this might just simply be a misunderstanding of how the function works. I've been tasked with showing a manual calculation for Cox deriving the survival probability from the hazard function (so even though it exists, I can't just call the built in function). My understanding is:
The survival function should be derivable from the hazard function via
S(t)=exp{−∫h(x)dx} --from time = 0 to time = t
and the hazard function at any given time can be found using
h(t)=h0(t)*exp(b1x1+b2x2+...+bpxp) - where b is the coefficient for each covariate (first column)
I've used the lifelines package in Python to fit a cox-regression model to my data and gotten the covariates
    coef    exp(coef)   ...
DM  0.04    1.04
HF  0.50    1.65
PVD 0.29    1.34
DEMENTIA    0.31
AGE_AT_MOD_START
MODALITY_NON-OPTIMAL START HD   -0.69   0.50
MODALITY_OPTIMAL START HD   -1.36   0.26
MODALITY_OPTIMAL START PD   -1.24   0.29

And it has a baseline_hazard and baseline_cumulative_hazard function that can be called to get h0(t).
Lifelines has a built in function for calculating survival (predict_survival_function) which I've been using to check my work, but my answers have been quite off. I created an example patient and basically just plugged it into the h(t) equation above.
baseline hazard
0.0 0.000000
1.0 0.000000
2.0 0.000000
3.0 0.000000
4.0 0.000101
... ...
1822.0  0.077646
1823.0  0.077646
1824.0  0.077646
1825.0  0.000000
1826.0  0.000000

DM  HF  PVD DEMENTIA    AGE_AT_MOD_START    MODALITY_NON-OPTIMAL START HD   MODALITY_OPTIMAL START HD   MODALITY_OPTIMAL START PD
0   1   0   1   0       85                  1                              0                         0

h(4) = 0.000101+exp(0.04*0+0.50*1+0.29*0+0.31*1+0.04*85+....-1.24*0) = 20.90534 (uh oh)
I tried with cumulative baseline hazard as well, since baseline hazard is 0 for the days where no deaths occured, though my understanding is that the hazard formula just uses the baseline hazard, not the cumulative one. I'm positive the problem is inside the e^(covariates*variables) part- even just checking
h(0) = 20.90524
S(0) = 8.3362e-10
Is clearly wrong, since S(0) should be close to 1.0. The glaring potential offender is that I just plugged in age (85) directly since it was already numerical, but should all values be normalized or something? I've looked all over but I haven't seen an example of anyone doing the calculations, it's all just 'call a function' nowadays (which, fair, I'd do the same if I was allowed). Any insight would be appreciated.
For comparison, the build in survival function results
4.0 0.999724
6.0 0.999448
8.0 0.998897
9.0 0.998344
10.0    0.997792
... ...
1820.0  0.155034
1821.0  0.155034
1822.0  0.125425
1825.0  0.125425
1826.0  0.125425

Comment: Instead of `h(4) = 0.000101+exp(0...`, do you mean `h(4) = 0.000101* exp(0` ? Note the `*`
Comment: oh my god, it really was just a simple typo. You're correct, I plugged in + instead of * in my actual script that ran the calculations. That's incredibly embarrassing, thanks for catching it!
Comment: Double-check the way that your software reports the baseline hazard. In R it is sometimes reported for a hypothetical "average" case, not for a true baseline case (e.g., continuous predictors at 0, categoricals at reference levels).
Answer: I'm the author of lifelines. For prediction, we normalize the inputted values against the training dataset's mean.
So
h(4) = 0.000101 * exp(0.04*(0 - mean(DM))+0.50*(1 - mean(HF))+ ... )

Let me know if that clears things up.

Edit: This might be confusing for future readers, so let me make something more clear. We normalize by the mean interally, and this is abstracted from the end user. We do it for numerical stability reasons, but we "add it back" later. This doesn't not change the final prediction results.
Answer: The math on deriving the survival function from the hazard function is not that complex and I would recommend an exploration in a spreadsheet setting.
First, per this source, for example, confirming your equation, quoting:

${S_Y(y) = exp(−H_Y(y))}$
where:
${H_Y(y) = \int_0^y h_Y(t)dt}$
The function ${H_Y(y)}$ is called the cumulative hazard function or the integrated hazard function. Like the hazard function, the cumulative hazard function is not a probability. However, it is also a measure of risk: the greater the value of ${H_Y(y)}$, the greater the risk of failure by time ${y}$.

Now, we can approximate the cited integration by the use of numerical methods to enable the estimation of the survival function. Per this source, for example, to quote:

Trapezoidal rule of integration
The trapezoidal rule of integration approximates the function {f(x)} to be integrated by a first order polynomial {f_1(x) = a_0 + a_1 x}. If we chose {(a, f(a))} and {(b, f(b))} as the two points to approximate {f(x)} by {f_1(x)} we can solve for {a_0} and {a_1}, leading to
\begin{array}{rcl} I & \approx & \int_{a}^{b} (a_0 + a_1x)dx\\ & = & a_0(b-a) + a_1 \bigg(\frac{b^2 - a^2}{2}\bigg)\\ & = & \frac{(b-a)}{2}(f(a) + f(b)) \end{array}
To be more accurate, we usually divide the interval {[a, b]} into {n} sub-intervals, such that the width of each sub-interval is {h = (b - a)/n}. In this case, the trapezoidal rule of integration is given by
${\text {I } \approx \frac{(b-a)}{2n}[f(a) + 2(\sum_{i=1}^{n-1} f(a+ih)) + f(b)]}$

In the current case, you have empirical measures or estimates of the function, ${f(a+ih)}$ (or, per above ${h_Y(t)}$ ).
Comment: The first link does not seem to lead to anything useful. Could you update it and include a description so that in case the link changes (again) we can easier locate the underlying content? Thank you!

Deriving survival from hazard function


How do you play really short notes on the acoustic guitar?

Question: I was wondering how it is possible to play very short notes on the acoustic guitar. Lets say 1/32. If you pick the string it is vibrating for some time.
So what are the options to make it short?

Tap the string after so it stops vibrating
Pick the string with less force
Do something else
Answer: Several options - release the fretting finger, but only enough to stop the string vibrating - not off completely. Touch the string with another finger from the fretting hand. Touch the string with a finger or palm of the picking hand.Play the next note on the same string, so the original has to stop.After playing the note (with a pick), put the pick back touching the string.
Tapping the string is not going to work - it'll probably make a different sound. Picking gently will make a held note last less time, but not what you want.
Of course, a 1/32 note will vary in length as to the tempo of the song.


How to print cn.replace("cn=", "") as  using EL

Question: I am turnig my jsp code:
<%

    for (int i = 0; i < list.size(); i++) {
        Entry var = (Entry) list.get(i);
        out.println(var.getCn().replace("cn=", ""));
        String cn = var.getCn();
        out.println("<form method=\"get\" action=\"Controller\">"
                + "<input type =\"hidden\" name=\"act1\" value = \"" + cn.replace("cn=", "") + "\">"
                + "<button type=\"submit\" name=\"act\"  value=\"SHOW\" id=\"act\" >Show</button>"
    }

into JSTL:
  <c:forEach var="item" items="${list}">

        <c:out value="${item.getCn()} "></c:out>

        <c:set var="item" value="${item.getCn()}"></c:set>
          <input type ="hidden" name="act1" value ="??????????????">
        <button type="submit" name="act"  value="SHOW" id="act">Show</button>
</c:forEach>

I don't know how to pass the parameter "value", easily uploadable through cn.replace("cn=", "") with jsp, to my servlet.
Answer: First remove the below line:
<c:set var="item" value="${item.getCn()}"></c:set>

It's overriding the <c:forEach var="item">.
As to the concrete question, you can just use singlequotes to represent a string in EL.
<input ... value="${item.cn.replace('cn=', '')}">

Do note that on javabean properties you don't necessarily need to specify the whole method name as in ${item.getCn()}. You can just use ${item.cn}.
See also:

Our EL wiki page
Places where JavaBeans are used?

Unrelated to the concrete problem, also note that this is still prone to a XSS attack hole if it concerns user-controlled input, but your original scriptlet approach was too.
Answer: I believe you can just use the variable item the same way you used cn on your scriplet. Try something like this:
value ="${item.replace('cn=', '')}"
I'm not sure if you'll have problems with two variables named item in your JSP, you might want to change the name of one of them just in case. This would be the whole code:
<c:forEach var="item" items="${list}">

        <c:out value="${item.getCn()} "></c:out>

        <c:set var="cn" value="${item.getCn()}"></c:set>
          <input type ="hidden" name="act1" value ="${cn.replace('cn=', '')}">
        <button type="submit" name="act"  value="SHOW" id="act">Show</button>


Nginx / git / fastcgi server not working

Question: I set up all the needed components for a Git server on Nginx using FastCGI and followed the combined suggestions of a few tutorials to end up with this configuration:
server {
  listen 80;
  listen [::]:80;

  server_name example.com www.example.com;

  return 301 https://example.com$request_uri;
}

server {
  listen 443 ssl;
  listen [::]:443 ssl;

  root /path/to/site;
  index index.html;

  server_name example.com www.example.com;

  # ... Some ssl stuff here ...

  location ~ /git(/.*) {
    auth_basic "Access denied";
    auth_basic_user_file /path/to/auth;

    client_max_body_size 0;

    fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend;

    include fastcgi_params;

    fastcgi_param GIT_HTTP_EXPORT_ALL "";
    fastcgi_param GIT_PROJECT_ROOT /path/to/site/git;
    fastcgi_param PATH_INFO $1;
    fastcgi_param REMOTE_USER $remote_user;

    fastcgi_pass unix:/var/run/fcgiwrap.socket;
  }
}

Using the window git client however, attempting to do anything to the repository found at https://example.com/git/test.git results in the following error on the client:
fatal: repository 'https://example.com/git/test.git/' not found

And this error on the server:
2016/01/07 16:59:05 [error] 5155#0: *579 FastCGI sent in stderr: "Not a git repository: '/path/to/site/git/test.git'" while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: example.com, request: "GET /git/test.git/info/refs?service=git-receive-pack HTTP/1.1", upstream: "fastcgi://unix:/var/run/fcgiwrap.socket:", host: "example.com"

Which is odd, because in the /git/test.git folder I had ran the git init --bare command previously so the repository is definitely there. I also tried chmod 0777 test.git -R in case it wasn't able to read the repository or something, but that had no effect.
I have tried many variants of the sameish configuration but I just do not understand what is going wrong here, so any help would be appreciated.
Comment: Did you manage to solve this finally? I'm having the same issue, and cannot find the answer :(
Comment: Finally it worked for me. Made a stupid mistake in the directory name. LOL.
Answer: Try running this in your git project folder
(/path/to/site/git/test.git)
git --bare init
git update-server-info

This should prep the git directory and create the necessary files. You are just missing the second step, I think.


JSP page won't move the another page after user enters the input

Question: I'm trying to move from one JSP page to another , but after the user hits the name and the password , it just stays the the same page . Here's the complete code:
Here's index.jsp: I'm starting from this page
<%@ page language="java" contentType="text/html; charset=windows-1255"
    pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>

<form action="LoginServlet" method="POST">
        First Name: <input type="text" name="firstName" size="20">

        Last Name: <input type="text" name="lastName" size="20">

        <input type="submit" value="Submit">
</form>

Here's is student.jsp : I want to move to this page
<%@ page contentType="text/html; charset=utf-8" language="java"%>
<jsp:useBean id="userBean" class="UserBean" scope="session" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet"  type="text/css" href="css/style2.css" />
<title>Student Access Details</title>

        Student name:
        <%= userBean.getFirstName() %> <%= userBean.getLastName() %>

        University ID:
        <%= userBean.getUid() %>

        Address:
        <%= userBean.getAddress1() %>

            <%if(userBean.getAddress2() != null)
                {%>
                <%= userBean.getAddress2() %>
<%}%>
            <%= userBean.getCity() %>

            <%= userBean.getPostCode() %>

        Contact:
        Tel: <%= userBean.getPhone() %>

            Email: <%= userBean.getEmail() %>

I'm using Tomcat ,JDBC , XAMPP and MySQL .
When I run from the browser this line : http://localhost:8080/MyFirstServlet
I enter this page and I hit homer & simpson :
Then I just stay at the same page , here :

Any idea what I'm doing wrong ? Thanks !
Comment: What servlet code got executed and what not?
Comment: This is broken on multiple levels, the first being treating servlets like they're thread-safe and exclusive per-user/connection/etc.
Comment: @DaveNewton sorry but I didn't understand exactly , what did I do wrong ?
Comment: Dave is right, the servlet class design is totally wrong, but that doesn't explain why it is seemingly not invoked. The design is a different problem which can be better understood by carefully reading this answer: http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909
Answer: Your validate(...) method will always return false for homer & simpson , try other username/password
Comment: You didn't edit it on stackoverflow, if you're using IDE try to debug it.
Answer: use proper action in the HTML code  action parameter in HTML form  for the form submit where it should go
Instead of  change the action parameter value and try
<form action="LoginServlet" method="POST">

use this
<form action="student.jsp" method="POST">


C# MVC 5 - \\ Executar query com resultado de outra query

Question: Pessoal estou vindo do PHP e aprendendo C# MVC enquanto migro as aplicações que tenho.
Me deparei com o seguinte problema que não consigo achar uma solução:
Essa é minha classe  que gera o menu dinamicamente no sistema:
public class WebEstMenuAplicacao
{
    private ConexaoOracle bd;

    public List<WebEstMenu> MenuSistema(int gru_in_codigo)
    {
        using (bd = new ConexaoOracle())
        {
            var strQuery = "select " +
                             " t.men_in_codigo, " +
                             " t.men_st_descricao," +
                             " t.men_st_caminho," +
                             " t.men_st_icone," +
                             " t.men_st_status" +
                           " from " +
                             " MGESTOQUE.WEB_EST_SYSMENU t ";
            //strQuery += string.Format(" t.gru_in_codigo= ('{0}')", gru_in_codigo);
            var retorno = bd.ExecutaComandoComRetorno(strQuery);
            return ReaderEmListaMenu(retorno);
        }
    }

    public List<WebEstMenu> ReaderEmListaMenu(OracleDataReader reader)
    {
        var tabAplicacao = new List<WebEstMenu>();
        while (reader.Read())
        {
            var tempoObjeto = new WebEstMenu()
            {
                men_in_codigo = int.Parse(reader["men_in_codigo"].ToString()),
                men_st_descricao = reader["men_st_descricao"].ToString(),
                men_st_caminho = reader["men_st_caminho"].ToString(),
                men_st_icone = reader["men_st_icone"].ToString(),
                men_st_status = int.Parse(reader["men_st_status"].ToString())
            };
            tabAplicacao.Add(tempoObjeto);
        }
        reader.Close();
        return tabAplicacao;
    }
}

Esse é meu controller:
public ActionResult Index()
{
    if (tempData.vORG_IN_CODIGO > 0)
    {
        var appWebEstMenu = new WebEstMenuAplicacao();
        var webEstMenu = appWebEstMenu.MenuSistema(tempData.vGRU_IN_CODIGO);

        if (webEstMenu == null)
        {
            return HttpNotFound();
        }

        return View(webEstMenu);

    }
    else
    {
        TempData["msg"] = "";
        return RedirectToAction("Index", "Login");
    }
}

Esse código gera o menu no meu sistema verificando o nível de acesso do colaborador. Até esse momento eu consegui normalmente, mas não estou conseguindo implementar a verificação do submenu. Onde ele deve percorrer o LIST do MENU e pesquisar os itens de submenu. E depois retornar os dois models para minha view.
Tabela de SubMenu
select t.sub_in_codigo,
       t.men_in_codigo,
       t.sub_st_descricao,
       t.sub_st_icone,
       t.sub_in_status,
       t.sub_st_url
from
 MGESTOQUE.WEB_EST_SYSSUBMENU t

Answer: Seu objeto tabAplicacao é a lista que contém os seus Menus. Dessa forma, se você precisa percorrê-la, você pode fazer dessa forma:
Ex.:
var tabAplicacao = new List<WebEstMenu>();
var subMenusList = new List<SubMenu>();

foreach(WebEstMenu menu in tabAplicacao)
{
     // 1. Select na tabela de sub-menus, utilizando o código do menu em questão.
     menu.men_in_codigo
     // 2. Captura os sub-menus retornados pela busca.
     // 3. Adiciona-os em uma nova lista de sub-menus. (Este objeto deve ser passado para a sua View).
}

Comment: Italo obrigado pela resposta, consegui ter uma ideia e resolver meu problema.
Answer: Depois de quebrar a cabeça, consegui achar uma solução:
Criei uma nova classe herdando a classe MENU:
Classe MENU
    namespace Estoque.Dominio
{
    public class WebEstMenu
    {
        public int men_in_codigo { get; set; }
        public string men_st_descricao { get; set; }
        public string men_st_caminho { get; set; }
        public string men_st_icone { get; set; }
        public int men_st_status { get; set; }
    }
}

Classe SubMenu
    namespace Estoque.Dominio
{
    public class WebEstSubMenu : WebEstMenu
    {
        public int Sub_in_codigo { get; set; }
        public string Sub_st_descricao { get; set; }
        public string Sub_st_icone { get; set; }
        public string Sub_st_url { get; set; }
    }

}

Criei a classe de aplicação onde executa as querys do MENU e SUBMENU, populando minhas classes de domínio.

   public class WebEstAplicacao
    {
        private ConexaoOracle bd;

       public List<WebEstSubMenu> MenuSistema(int gru_in_codigo)
               {
                   using (bd = new ConexaoOracle())
                   {
                       var strQuery = "select " +
                                        " t.men_in_codigo, " +
                                        " t.men_st_descricao," +
                                        " t.men_st_caminho," +
                                        " t.men_st_icone," +
                                        " t.men_st_status" +
                                      " from " +
                                        " MGESTOQUE.WEB_EST_SYSMENU t ";
                       //strQuery += string.Format(" t.gru_st_nome = LOWER('{0}')", gru_st_nome);
                       var retorno = bd.ExecutaComandoComRetorno(strQuery);
                       return ReaderEmListaMenu(retorno);
                   }
               }

               //
               public List<WebEstSubMenu> ReaderEmListaMenu(OracleDataReader reader)
               {
                   var tabAplicacaoMenu = new List<WebEstSubMenu>();
                   var appWebSubMenu = new WebEstSubMenuAplicacao();

                   while (reader.Read())
                   {
                       var tempoObjeto = new WebEstSubMenu()
                       {
                           men_in_codigo = int.Parse(reader["men_in_codigo"].ToString()),
                           men_st_descricao = reader["men_st_descricao"].ToString(),
                           men_st_caminho = reader["men_st_caminho"].ToString(),
                           men_st_icone = reader["men_st_icone"].ToString(),
                           men_st_status = int.Parse(reader["men_st_status"].ToString())
                       };
                       tabAplicacaoMenu.Add(tempoObjeto);
                        using (bd = new ConexaoOracle())
                        {
                            var strQuery = "select " +
                                          "  t.sub_in_codigo," +
                                          " t.men_in_codigo," +
                                          " t.sub_st_descricao," +
                                          " t.sub_st_icone," +
                                          " t.sub_in_status," +
                                          " t.sub_st_url" +
                                          " from MGESTOQUE.WEB_EST_SYSSUBMENU t";
                            strQuery += " where ";
                            strQuery += string.Format(" t.men_in_codigo = {0}", int.Parse(reader["men_in_codigo"].ToString()));
                            //strQuery += string.Format(" t.gru_st_nome = LOWER('{0}')", gru_st_nome);
                            var retorno = bd.ExecutaComandoComRetorno(strQuery);
                                while (retorno.Read())
                                {
                                    var tempoObjetoSub = new WebEstSubMenu()
                                    {
                                        men_in_codigo = int.Parse(reader["men_in_codigo"].ToString()),
                                        men_st_descricao = reader["men_st_descricao"].ToString(),
                                        men_st_caminho = reader["men_st_caminho"].ToString(),
                                        men_st_icone = reader["men_st_icone"].ToString(),
                                        men_st_status = int.Parse(reader["men_st_status"].ToString()),
                                        Sub_in_codigo = int.Parse(retorno["sub_in_codigo"].ToString()),
                                        Sub_st_descricao = retorno["sub_st_descricao"].ToString(),
                                        Sub_st_icone = retorno["Sub_st_icone"].ToString(),
                                        Sub_st_url = retorno["sub_st_url"].ToString()
                                    };
                                         tabAplicacaoMenu.Add(tempoObjetoSub);
                                }
                        }
                   }
                   reader.Close();
                   return tabAplicacaoMenu;
               }
    }

Dentro do meu _Layout.cshtml, apanhei um pouco no Razor, mas consegui chegar a solução:
            @foreach (var item in Model)
            {
                var menu2 = 0;
                var menu = int.Parse(Html.DisplayFor(modelItem => item.Sub_in_codigo).ToString());
                menu2 = int.Parse(Html.DisplayFor(modelItem => item.men_in_codigo).ToString());

                if (menu == 0)
                {

                    @Html.Raw("
");
                    @Html.Raw(" "+
                                ""+
                                ""+ @Html.DisplayFor(modelItem => item.men_st_descricao).ToString() + " "+
                                ""+
                                ""+
                                ""+
                                "");
                    @Html.Raw("
");

                    foreach (var subemnuitem in Model)
                    {
                        var SubMenu = int.Parse(Html.DisplayFor(modelItem => subemnuitem.men_in_codigo).ToString());
                        var menu3 = int.Parse(Html.DisplayFor(modelItem => subemnuitem.Sub_in_codigo).ToString());

                        if (SubMenu == menu2 && menu3 > 0)
                        {
                            @Html.Raw("
"+ @Html.DisplayFor(modelItem => subemnuitem.Sub_st_descricao).ToString() + "
");
                        }
                        else
                        {
                            //@Html.Raw("
");
                           // break;
                        }
                    }
                    @Html.Raw("
");

                }
                else
                {

                    @Html.Raw("
");
                }
            }

Gerando o menu dinamicamente.


A counterexample that marginal convergence in law does not imply joint convergence in law

Question: I just encountered the following counterexamle that should illustrate that marginal convergence in distribution does not imply joint convergence in distribution:
Let U and V be independent standard normal random variables and define
\begin{equation}X_n = U\end{equation} and $$Y_n=(−1)^n \cdot \frac{1}{2} \cdot U+ \sqrt{\frac{3}{4}}\cdot V$$
Then $X_n$ and $Y_n$ are both standard normal for all $n$, and hence trivially converge in law marginally. But
$$\text{cov}(X_n, Y_n) = (−1)^n $$
for all $n$, and so the sequence $(X_n, Y_n)$ of random vectors cannot converge in law.
Here is my question (and I feel that the answer is straightforward, I just can't see it): why does the alternating covariance violate convergence of distribution of the vector $(X_n,Y_n)$?
Many thanks for any help, it is much appreciated. And sorry again if the solution is straighforward...
Comment: The covariance is $(-1)^n\frac12$, not $(-1)^n$.
Comment: I don't understand what is being asked. The random variables $(X_1,Y_1)$, $(X_3,Y_3)$, $(X_5,Y_5), \ldots$ all have one jointly normal distribution with covariance $-\frac{1}{2}$ while $(X_2,Y_2)$, $(X_4,Y_4)$, $(X_6,Y_6), \ldots$ all have a _different_ jointly normal distribution where the covariance is $+\frac{1}{2}$. So in what sense are you thinking that $F_{X_n,Y_n}$ is _converging_ to a fixed $F_{U,V}$? Isn't that something like asking why the sequence $+1, -1, +1, -1, +1, -1, \ldots$ is not a convergent sequence?
Comment: @DilipSarwate No theorem states that convergence in distribution requires convergence of the covariance. In fact it does not, see my *Edit-edit*.
Answer: The variance of $X_n+2Y_n$ is $3$ if $n$ is odd and $7$ if $n$ is even hence
$$
\mathbb P(X_n+2Y_n\leqslant\sqrt{21})=\begin{cases}\Phi(\sqrt7)\quad\text{if $n$ is odd},\\ \Phi(\sqrt3)\quad\text{if $n$ is even.}\end{cases}
$$
Nota: As regards finding a counterexample, I prefer $X_n=U$, $Y_n=(-1)^nU$.
Edit: In the case at hand, the sequences $(X_n)_n$ and $(Y_n)_n$ are uniformly bounded in every $L^p$, for example in $L^4$, hence these families are uniformly square integrable. Assume that the sequence $(X_n,Y_n)_n$ converges in distribution. Then there exists some random variables $(\bar X,\bar Y)$ and some sequences $(\bar X_n)_n$ and $(\bar Y_n)_n$, defined on a common probability space, such that each $(\bar X_n,\bar Y_n)$ is distributed as $(X_n,Y_n)$ and the sequence $(\bar X_n,\bar Y_n)_n$ converges almost surely to $(\bar X,\bar Y)$.
Since the family $(\bar X_n,\bar Y_n)_n$ is uniformly square integrable, $(\bar X_n,\bar Y_n)_n$ converges to $(\bar X,\bar Y)$ in $L^2$, in particular $\mathrm{Cov}(X_n,Y_n)=\mathrm{Cov}(\bar X_n,\bar Y_n)$ converges. This is not so hence $(X_n,Y_n)_n$ does not converge in distribution.
Edit-edit: To see that convergence in distribution can coexist with nonvanishingly oscillating covariances, assume that $\mathbb P(X_n=1/\sqrt{2p_n})=p_n$, $\mathbb P(X_n=-1/\sqrt{2p_n})=p_n$ and $\mathbb P(X_n=0)=1-2p_n$ for some positive sequence $(p_n)_n$ such that $p_n\leqslant1/2$ and $p_n\to0$, and define $Y_n=(-1)^nX_n$. Then $X_n\to0$ in distribution, $Y_n\to0$ in distribution, $\mathrm{Cov}(X_n,Y_n)=(-1)^n$ and $(X_n,Y_n)\to(0,0)$ in distribution. Note that $(X_n)_n$ is not uniformly square integrable since $\mathbb E(X_n^2)=1$ for every $n$ and $X_n\to0$ in distribution.
Comment: The problem is that the convergence in distribution does not imply the convergence of the covariances, except under extra uniform integrability assumptions, which are satisfied in your example but not in general.
Comment: thanks, but that does not answer exactly the question about how the alternating covariance is related to the non-convergence.
Comment: hi did, many thanks for your excellent and well-explained answer. I really appreciate your support!!!
Comment: Well, thanks. $ $


How do I show a coupon code to customers?

Question: I've enabled a Ubercart Discount Coupons module in my eshop site and created some coupons with multiple one-time use only codes for testing purposes.
Now I would like to get one of the active coupon codes to customer who submits a newsletter registration form. Are there any functions to retrieve one of unused coupon codes?
Answer: The UC coupon module doesn't have a general purpose coupon retrieval function.
If you're solely looking to retrieve an active coupon, you can follow what the module itself does: query the DB table uc_coupons for rows with column status = 1. Using a DB query will let you modify it to whatever your particular case (e.g. 1 or more results, bulk codes, date range, etc.).
Answer: I am also looking for this functionality because I want to create a Coupons tab in the MY ACCOUNT area of a Drupal 7 website that uses Ubercart 3 (D7U3).
The line of code that generates a list of system coupons starts at line 118 in uc_coupon.admin.inc with the following comment:
/**
 * Display a brief overview of system coupons
 *
 * @param $view_type
 *   'active' or 'inactive'
 */

To be able to accomplish this task, you need three things:

"Hook" to a Drupal event so your code can be "Triggered"
Have your "Triggered" code generate relevant and meaningful results
Present your relevant and meaningful results in a human-understandable way

The first thing you need to do is figure out what event "triggers" your customization, which defines how it is then "fired".  In my case, the even in question is the marshaling of information necessary to create and present the information that appears in they MY ACCOUNT screen.  Your situation may differ, but the crux of this challenge is to identify the system event to which your custom code can be "hooked".
One potential list of Drupal 7 "hooks" is located at:
https://api.drupal.org/api/drupal/includes%21module.inc/group/hooks/7.x
The next thing you need to do is obtain and manipulate data from the back-end database of Drupal (presumably MySQL, but not strictly so) by creating a database connection, issuing a structured query through that connection and then receiving the result into a data structure that can be iterated through - because most systems have more than one active coupon at any given time.
The design pattern is this:
A) Establish connection
B) Issue command through connection
C) Receive results into local data structure

A tutorial on how to do this is available at:
https://www.drupal.org/docs/7/creating-custom-modules/retrieving-data
The last thing you need to do is present the results of the above two operations in a way that the user can perceive as a meaningful response.  This usually entails the creation of representative PHP and CSS code to position and then present/style the results.
A tutorial on creating an input form and producing an output form is available at:
https://www.youtube.com/watch?v=EHY8McU79gc&ab_channel=CodeKarate
g.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://drupal.stackexchange.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://drupal.stackexchange.com/help/whats-reputation), you can also [add a bounty](https://drupal.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/137309)
Comment: Question asked:  "Are there any functions to retrieve one of unused coupon codes?"

1st Answer:  NO

2nd Answer (mine):  NO, but here's an outline of HOW, WHAT, WHERE and WHEN to answer your own question.

Honestly, please move beyond 1st order thinking.  I am not doing free "work for hire" here.  I am DONE posting on this platform.
Comment: Flag my comment for moderation instead of leaving. Let's get another opinion.
Comment: Goodbye, Have A Nice Day and Bless Your Heart:
1110110100000010110011101100111011011111101101000111010100111101110101


Running sum of elements in a list of lists

Question: I have a list such that:
list =[['x',1,2,3],['y',2,5,4],['z',6,2,1]...]

How do I make a running sum and replace specific elements of a list of list, so that:
>>>list =[['x',1,2,3],['y',3,7,7],['z',9,9,8]...]

EDIT:
Curious why the disapproval?! Update: I tried @Sunitha solution but
  accumulate is not in itertools - maybe because running 2.7. I also came up with:

    temp = [0,0,0]
    for i, item in enumerate(list):
        temp = [temp[0]+item[1], temp[1]+item[2],temp[2] + item[3]]
        list[i] = [item[0],temp[0],temp[1],temp[2]]

Its clunky, but whatever, I am a biologist. Open to more pythonian
  answers!
Comment: Yes for sure if the solution is more elegant.
Comment: Would you be open to using a 3rd party library like numpy or pandas?
Answer:
Update: I tried @Sunitha solution but accumulate is not in itertools - maybe because running 2.7.

I've tested this code with Python 2.7.15 and Python 3.6.5. This code starts at the second sublist in the list (index 1, if applicable) and looks backwards at the previous sublist to accumulate the values as in your example.
Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]]
>>> for i in range(1, len(hmm)):
...     prev = hmm[i - 1][1:]
...     current = iter(hmm[i])
...     hmm[i] = [next(current)] + [a + b for a, b in zip(prev, current)]
...
>>> hmm
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

It could be written slightly different in Python 3 as well:
Python 3.6.5 (default, Jun 14 2018, 13:19:33)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]]
>>> for i in range(1, len(hmm)):
...     _, *prev = hmm[i - 1]
...     letter, *current = hmm[i]
...     hmm[i] = [letter] + [a + b for a, b in zip(prev, current)]
...
>>> hmm
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

Answer: Simple one-liner
>>> from itertools import accumulate
>>> ll=[['x',1,2,3],['y',2,5,4],['z',6,2,1]]
>>>
>>> list(accumulate(ll, lambda *l: [l[-1][0]] + [sum(r) for r in list(zip(*l))[1:]]))
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

Explanation
The bulk of the work is done by accumulate(ll, func) code, which runs func for each element of the iterable ll, with the previously computed result. We just have to impelement the function func that would do the needful
Consider, the first 2 elements of the list
>>> l1=ll[0]; l2=ll[1]
>>>
>>> l1
['x', 1, 2, 3]
>>> l2
['y', 2, 5, 4]

>>> # A simple zip would create pairs of elements from l1 and l2
>>> f = lambda *l: [list(zip(*l))]
>>> f(l1, l2)
[[('x', 'y'), (1, 2), (2, 5), (3, 4)]]
>>>
>>> # Remove the first element, so we can calc sum
>>> f = lambda *l: [list(zip(*l))[1:]]
>>> f(l1, l2)
[[(1, 2), (2, 5), (3, 4)]]
>>>
>>> # Calculate sum for the pairs
>>> f = lambda *l: [sum(r) for r in list(zip(*l))[1:]]
>>> f(l1, l2)
[3, 7, 7]
>>>
>>> # Now add back the removed first element, but only once
>>> f = lambda *l: [l[-1][0]] + [sum(r) for r in list(zip(*l))[1:]]
>>> f(l1, l2)
['y', 3, 7, 7]

Thats it. Now feed this function to accumulate
>>> list(accumulate(ll, f))
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]


Uso de "global" com mysqli deixa a conexão aberta?

Question: Nesta forma de acesso ao banco com mysqli fiquei na dúvida se são abertas duas conexões, e se, depois de fechar a do $stmt, se ainda fica uma conexão sempre aberta.
O uso é basicamente este:
$host = "mysql.host.com.br";
$db = "dbname";
$user = "user";
$passw = "passw";

$mysqli = new mysqli($host, $dbname, $user, $passw);

GLOBAL $mysqli;

Então para usar faz:
$stmt = $mysqli->prepare(SELECT...);
$stmt = execute();
...
$stmt->close();

Então a primeira dúvida é se no caso ficam abertas duas conexões, uma que é usada na query com $stmt, e a outra que fica aberta ($mysqli) esperando algum outro request acontecer.
Sendo apenas uma, a conexão da variável $mysqli vai ficar aberta até o limite do timeout, ou se quando fecha com $stmt ela fecha também a global ($mysqli)?
Comment: Global é no escopo do script, deixa de existir ao final. PHP não tem variáveis de sessão,  e muito menos de aplicação (o que eu sinto uma falta danada, por sinal). Seria legal vc explicar melhor esse "deixa conexão aberta". Qualquer conexão fica aberta por um tempo, enquanto a variável estiver no escopo. O Global só muda a visibilidade da variável justamente em relação ao escopo, o resto é consequência.
Comment: É isso mesmo @VirgilioNovic, achei que abria outra quando faz `$stmt = $mysqli->prepare`, valeu pelo complemento. abs
Comment: Pois é @Bacco, é que vocês estão overating o meu entendimento da matéria rsrs Agora que eu entendi que "O statement aberto permite você ir avançando nos registros, exeutar passos, até que fechado" e que isso não afeta a conexão que foi aberta. Acho que vcs estão pressupondo que eu deveria saber disso, mas eu não sabia.
Comment: @gustavox o meu pressuposto com base no comment era de vc não saber, e por isso que eu comentei o que era :D
Comment: A página principal do statement nao ajuda muito, mas os links dos métodos levam para mais detalhes https://www.php.net/manual/en/class.mysqli-stmt.php
Comment: Não confundir com isso aqui, que eu realmente não recomendo usar sem uma razão MUITO especial (nunca experimentei situação real em que fosse benéfico, muito pelo contrário) https://www.php.net/manual/en/mysqli.persistconns.php
Comment: como você está montando isso, é tudo com `include`? isso vai depender da organização, se você colocar uma pagina que inclui essa conexão temos apenas 1 conexão aberta.
Comment: Então @Bacco eu fiquei na dúvida se quando fechava com `$stmt->close()` fechava também a global do $mysqli, mas pela resposta do @Maniero, e pensando melhor agora, parece meio óbvio que não né hehe. Valeu a força man, desde sempre! abs
Comment: @gustavox isso que vc acaba de dizer não tem relação com o titulo da pergunta e nem do escopo que eu comentei. Esse close ai é método do statement, não da conexão. O statement aberto permite você ir avançando nos registros, exeutar passos, até que fechado. Aí ele libera os recursos daquele statement (que são relacionados à conexão, mas são coisas separadas). Seria legal você dar uma revisada no manual para entender a classe que é retornada pelo prepare
Answer: A pergunta não faz sentido, ela pressupõe que está abrindo duas conexões quando claramente o código mostra que só uma está sendo aberta.
O segundo código está usando a conexão já aberta, não está abrindo uma nova. E o fechamento que ocorre ali é da query e não da conexão, a conexão está suportada pela variável $mysqli, e o que está fechando é a variável $stmt que suporta só a query. Somente quando fizer $mysqli->close() é que a conexão será fechada (ou se o script encerrar, que se for ver o contexto todo do código parece que é quando esta conexão será fechada).
Comment: Sentido faz, tanto que você respondeu o que eu queria saber. Vide "Então a primeira dúvida é se no caso ficam abertas duas conexões". De qualquer forma valeu pela resposta mega ultra rápida! :) abs


C# cast options, is there any difference other than syntax?

Question: I just ran across another way to cast objects in C#.  I have always used (CastType)variable.  I just noticed some code using variable as CastType.  The latter reminds me of VB.
Is there a difference between the two methods of casting other than syntax?
Comment: This is a duplicate, thank you slavoo for finding that. I could not find it.
Answer: The first one will throw InvalidCastException if the types don't match (refer to the documentation - "Explicit conversions" section). The second one (the as operator) will produce null value instead.


The import android.print cannot be resolved

Question: i am trying to implement print function inside my app. but it gives me  PrintManager cannot be resolved to a type error
Minimum requirement for that class android.print.PrintManager was API 19. i tried changing my minSdkVersion to 19 as well. but not working
NOTE: I have updated SDK Platform for API 19 in my sdk.
is there something i should update seperately in sdk for this to work? or is there seperate library to be added in my project?
Comment: Right click project--->properties--->android--->Make sure project build target is 19.
Comment: thanx man it worked. i dont know why i didnt think of that
Answer: Right click project--->Properties--->android--->Set your project build target to 19.
Clean and rebuild and it will work.


Changes to /etc/phpmyadmin/config.inc.php do not have effect

Question: I would like to configure PhpMyAdmin to access only one database through one user.
I tried before to restrict access via .htaccess using this answer from 2013 but it did not work:
phpMyAdmin Block Access to Single Database
I hence tried by adding deny,allow rules as stated in this answer:
How do I restrict access to specific database user accounts in phpMyAdmin?
But it did not work too. I continue to access all users. I have read the documentation and rewrote the lines in config.inc.php as
<code>$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
'deny root from all',
'deny user1 from all',
'deny user2 from all',
'allow user3 from all',
);
</code>
where user1 and user2 are users to deny, and user2 is user to allow. But I can still access with all users. I hence tried only
<code>$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit';</code>
that should block access to all users, but I can still access with all users. I hence believe that /etc/phpmyadmin/config.inc.php is being overwritten in some way, since no change has effect, but I do not understand how.
Any idea on where to check?
Answer: In my case, it is solved by updating PHP and PhpMyAdmin to the latest version. Poof, the problem is gone
Answer: Looks like you are allowing access to all users and then again you are trying to restrict some of the users, seems bit confusing.
<code>$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
</code>
The correct pattern should be deny access to all users and then provide explicit access to the specific user
<code>$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit';
</code>
Please refer the official document
https://docs.phpmyadmin.net/en/latest/config.html#cfg_Servers_AllowDeny_order
The correct configuration should be something like this
<code>$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit';
$cfg['Servers'][$i]['AllowDeny']['rules'] = [
    'allow user3 from all'
];
</code>
hope it works for you!
Comment: Hi @initvik, no, that does not work too, I can still access with all users


Look up speed in Generic

Question: I need to implement a search algoritm with efficient o(1). If I use HashSet and will try search by User.FirstName for example, whether it is right? If not, give me an advice, please, how can I realize this search?
Comment: @Ben: Not if you're using FirstName, as you'll get duplicate keys...
Comment: you probably want a `Dictionary` instead.
Comment: @Reed: True, you want something along the lines of `unordered_multimap`... I don't think any is provided by .NET.
Comment: @Ben: `ILookup/Lookup` - See my answer ;)
Answer: You'll need to use Dictionary<TKey,TValue>, where the TKey is built on the search type.  However, if you're using something like FirstName as a search term, you may have multiple values with the same key, which will cause problems.
A potentially better option would be to use ToLookup to generate an ILookup for you.  For example:
IEnumerable<Person> people = GetPeople();

var nameLookup = people.ToLookup(p => p.FirstName);

You could then do:
var peopleNamedFred = nameLookup["Fred"];
foreach(var fred in peopleNamedFred)
    Console.WriteLine("{0} {1}, fred.FirstName, fred.LastName);

Comment: LookUp is immutable. That's nice for some uses, but makes it unusable for others.
Comment: @CodeInChaos: True - you'd have to regenerate the `ILookup` if your data changes.  That being said, you could always make your own ILookup using `Dictionary>` if required.
Answer: Create an implementation of System.Collections.ObjectModel.KeyedCollection.
According to the MSDN reference it " provides both O(1) indexed retrieval and keyed retrieval that approaches O(1)."  However, it still has the limitations that Dictionary' andHashTable` have with duplicate keys not being allowed.  If you need duplicate key values, or you need to be able to use different items as keys at different times, then Reed Copsey gives a very good solution.

Look up speed in Generic


What's the fundamental difference between these two regression models?

Question: Suppose I have a bivariate responses with significant correlation. I am trying to compare the two ways to model these outcomes. One way is to model the difference between the two outcomes:
$$(y_{i2}-y_{i1}=\beta_0+X'\beta)$$
Another way is to use gls or gee to model them:
$$(y_{ij}=\beta_0+\text{time}+X'\beta)$$
Here is a foo example:
#create foo data frame

require(mvtnorm)
require(reshape)
set.seed(123456)
sigma <- matrix(c(4,2,2,3), ncol=2)
y <- rmvnorm(n=500, mean=c(1,2), sigma=sigma)
cor(y)
x1<-rnorm(500)
x2<-rbinom(500,1,0.4)
df.wide<-data.frame(id=seq(1,500,1),y1=y[,1],y2=y[,2],x1,x2)
df.long<-reshape(df.wide,idvar="id",varying=list(2:3),v.names="y",direction="long")
df.long<-df.long[order(df.long$id),]
    df.wide$diff_y<-df.wide$y2-df.wide$y1

#regressions
fit1<-lm(diff_y~x1+x2,data=df.wide)
fit2<-lm(y~time+x1+x2,data=df.long)
fit3<-gls(y~time+x1+x2,data=df.long, correlation = corAR1(form = ~ 1 | time))

What's the fundamental difference between fit1 and fit2? And between fit2 and fit3, given they are so close on the $p$ values and estimates?
Comment: The difference between fit1 and fit3 is sometimes referred to as Lord's paradox. See here for some discussion (on why the estimates don't change between the models) and a reference to a Paul Allison article, http://stats.stackexchange.com/a/15759/1036. Another reference is `Holland, Paul & Donald Rubin. 1983. On Lord's Paradox. In Principles of modern psychological measurement: A festchrift for Frederic M. Lord edited by Wainer, Howard & Samuel Messick pgs:3-25. Lawrence Erlbaum Associates. Hillsdale, NJ.`
Answer: First, I will introduce yet a fourth model for the discussion in my answer:

fit1.5 <- lm(y_2 ~ x_1 + x_2 + y_1)

Part 0
The difference between fit1 and fit1.5 is best summarized as the difference between a constrained difference vs. an optimal difference.
I am going to use a simpler example to explain this than the one provided above. Let's start with fit1.5. A simpler version of the model would be
$$y_2 = b_0 + b_1·x + b_2·y_1$$
Of course, when we obtain an OLS estimate, it will find the "optimal" choice for $b_2$. And, though it seems strange to write is as such, we could rewrite the formula as
$$y_2 - b_2·y_1 = b_0 + b_1·x$$
We can think of this as the "optimal" difference between the two $y$ variables.
Now, if we decide to constraint $b_2=1$, then the formula/model becomes
$$y_2 - y_1 = b_0 + b_1·x$$
which is just the (constrained) difference.
Note, in the above demonstration, if you let $x$ be a dichotomous variable, and $y_1$ be a pre-test and $y_2$ a post test score pairing, then the constrained difference model would just be the independent samples $t$-test for the gain in scores, whereas the optimal difference model would be the ANCOVA test with the pre-test scores being used as covariates.
Part 1
The model for fit2 can best be thought of in a similar fashion to the the difference approach used above. Though this is an oversimplification (as I am purposefully leaving out the error terms), the model could be presented as
$$y = b_0 + b_1 · x + b_2 · t$$
where $t=0$ for the $y_1$ values and $t=1$ for the $y_2$ values. Here is the oversimplification...this let's us write
$$\begin{align}y_1 & = b_0 + b_1 · x \\ y_2 & = b_0 + b_1 · x + b_2\end{align}$$
Written another way, $y_2 - y_1 = b_2$. Whereas model fit1.5 had $b_2$ as the value to make the optimal difference for the OLS analysis, here $b_2$ is essentially just the average difference between the $y$ values (after controlling for the other covariates).
Part 2
So what is the difference between models fit2 and fit3...actually, very little. The fit3 model does account for correlation in error terms, but this only changes the estimation process, and thus the differences between the two model outputs will be minimal (beyond the fact that the fit3 estimates the autoregressive factor).
Part 2.5
And I will include yet one more model in this discussion

fit4 <- lmer(y~time+x1+x2 + (1|id),data=df.long)

This mixed-effects model does a slightly different version of the autoregressive approach. If we were to include the time coefficient in the random effects, this would be comparable to calculating the difference between the $y$s for each subject. (But, this won't work...and the model won't run.)


How to get instance of a singleton PHP class while extending it?

Question: I have a specific class in my project that used for load and hold everything else like libraries and modules.
For example;
index.php
---------
require_once "Libs/Damn.php";
$damn = Damn::getInstance();

// Initialize the URI class for handling user's request.
$damn->load('URI');
$damn->load('Modules');
$damn->load('Views');

if($damn->URI->module){
    $damn->Modules->load($damn->URI->module);
} else {
    $damn->Modules->load('main');
}

It is simply load 3 library and looking for a module name in the URL. If it can't find, it'll load the module named as "main" (main.php).
Here is the problem;
When i extend the Damn class in main.php, i can't access to loaded libraries like URI, Modules but i want to. It seems extending a singleton class is not getting instance of the class, just copying it.
I want to be able to use a module class like this;
main.php
--------
<?php
if (!defined('SECURED')) die('Access denied.');

class Main extends Damn {

    public function __construct() {}

    public function index() {
        $this->Views->load('test'); //Views library already loaded when Damn initiated.
    }

    public function __destruct() {}

}

?>

Answer: You actually don't extend Damn. You create a new class that extends from Damn. Your original class is unaffected, and the data in the singleton instance is not magically copied to a new class.
The best (well, 'A good') solution here, is not to extend Main from Damn, but create a new Main class that uses Damn to manage the models.
It is illogical to change the type of the instance of a singleton based on a property of an earlier instance of the singleton. This smells like bad design :)


A test for similarity of 2 samples?

Question: I have two samples - one is predicted values and one is actual values.
Paired samples t-test suggested that there are no differences between these two samples.
Because I remember from stats courses that the absence of a difference doesn't mean that the samples are similar, I wanted to ask if there is a statistical significance test to check for similarity of 2 samples?
Comment: But a prediction doesn't meet the condition of a "sample" does it? Do the predictions even correspond to the "actual values" (the thing that is a sample)? How is this different, if at all, from evaluating predictive accuracy?
Comment: "Paired samples t-test suggested that there are no differences between these two samples." Statement suggests confirmation bias. Likely should be "Paired samples t-test **failed to find evidence of** differences between these two samples." Remember: we don't accept the null hypothesis, just fail to reject it. (Of course, we *can* try to find evidence of the equivalence of two quantities, but that requires [tests for equivalence](https://stats.stackexchange.com/tags/tost/info)).
Comment: Another user has posted [a similar question to yours regarding tests for similarity](https://stats.stackexchange.com/questions/327451/test-if-mean-is-similar-to-a-expected-value), and I was able to walk through the construction of the test statistics and inference.
Answer: You want to perform a test for equivalence of two samples. One was to do this is to perform two one-sided tests based on a preferred Type I error rate, and an a priori equivalence threshold (i.e. the smallest difference between the two samples that you would care about).
Your general null and alternate hypothesis in such a case would be:
$H^{-}_{0}: |\mu_{A}-\mu_{B}|\ge\Delta$
$H^{-}_{0}: |\mu_{A}-\mu_{B}|< \Delta$
Which will translate into the two specific null and alternatives:
$H^{-}_{01}: \mu_{A}-\mu_{B}\ge\Delta$
$H^{-}_{01}: \mu_{A}-\mu_{B}< \Delta$
and
$H^{-}_{02}: \mu_{A}-\mu_{B}\le-\Delta$
$H^{-}_{02}: \mu_{A}-\mu_{B}> -\Delta$
If you reject both $H^{-}_{01}$ and $H^{-}_{02}$, then you conclude that the difference in these means is greater than $\Delta$ but less than $\Delta$.
Two one-sided tests are implemented for R in the equivalence package (within R type install.packages(c("equivalence")) to install), and for Stata in the tost package (within Stata type net install tost, from(https://alexisdinno.com/stata) to install the package and net get tost, from(https://alexisdinno.com/stata) for the example data).
Answer: No.
First, significance tests make inferences about differences between populations, not samples. You don't need a significance test if all you want to do is check something like which sample mean is larger—you can do that directly.
Second, the idea of a significance test is to examine how unlikely observations would be under a null hypothesis. If the answer is "extremely unlikely", you can infer that the null hypothesis is implausible. But if the answer is "likely", it doesn't follow that the null hypothesis is plausible. The null hypothesis is no more or less plausible than it was to begin with. In short, significance-testing can't find evidence in favor of a null hypothesis.
Comment: [tost](https://stats.stackexchange.com/tags/tost/info)
Comment: @Alexis It seems pretty clear to me that the question is about how you can confirm the null hypothesis of precisely 0 difference after a failed test of this hypothesis. So I explained why you can't. The TOST method is a different animal.
Comment: The OP's language was "similar", so I disagree. But reasonable people can do this. :)
Answer: You can't do that exactly, but something very similar. Take the difference of all pairs (actual value minus simulated) and compute a one-sample t-test to test, whether the difference is different from 0. The p-value will not be of any interest to you, as that deals with the question of the difference being exactly $0.0000000000\dots$
However, most statistic programs will not only give you a p-value but also a 95% confidence intervall of the true difference. You may define for yourself, that you consider the sample mean differences as similar, if the 95%-confidence interval does not contain values above 0.5 or below -0.5 or any other limit of practical equality (ok, this may work even better with a Baysian credible interval, but given the question you will need an answer that es easy to produce).
A worked example in R:
simulated <- c(3.8, 3.2, 4.7, 9.9, 1.2)
measured  <- c(3.2, 3.8, 4.8, 10.3, 1.3)

delta <- simulated - measured
print(t.test(delta, mu = 0)$conf.int)

This will give a 95% confidence interval from -0.685 to  0.445. Now you can decide, whether that is similar enough for your purposes. Other software will be able to achieve the same similarly easy.
Comment: [tost](https://stats.stackexchange.com/tags/tost/info)

A test for similarity of 2 samples?


Taxonomy overview search term

Question: In this manager:
admin/structure/taxonomy
admin/structure/taxonomy/manage/[fruit]/overview
There is a way to add a search a term?
So, if you have 100 terms it will easier to find a term.
This one is not ported at all https://www.drupal.org/project/term_search
This module is not full ported to D8
https://www.drupal.org/project/taxonomy_manager
I also find this interested article to alter a task in a specific vocabulary. https://www.computerminds.co.uk/drupal-code/replacing-vocabulary-listing I created the view, but I still find out how to add a tab for that view in the overview taxonomy.
There other way to add an option to search a term in manager?
Answer: Views with exposed filters sound like a great way to add a Search page to Vocabulary configuration tabs.
You can add your Views page to Vocabulary pages through Views configuration. Since the List already exists as the default tab, simply configure your Views page Menu option as a normal Menu tab and set the page path to the [path-to-default-vocabulary-page]/search.
The tab will appear as one of the tabs you see when you visit the Vocabulary configuration page.
Comment: I'll test that  today
Comment: I tried It works have way. It is displayed the Search tab. But view is getting an error. The view works alone.. but the I add path to admin/structure/taxonomy/manage/category/overview/search and Menu Tab "Some mandatory parameters are missing ("taxonomy_vocabulary") "
Comment: Have you added the Contextual filter for the vocabulary? You should have /%/ instead of the /category/ in the path. The contextual filter should take the `Raw value from URL` under `Provide default value`, and `Path component` 5. That way you get search pages on all vocabularies. There also seems to be a bug that needs to be patched so Tabs can work: [Views does not create parent local task for a default local task](https://www.drupal.org/project/drupal/issues/2804195), or create the parent item menu item manually.

Taxonomy overview search term


What are the most effective ear training methods?

Question: Ear training is a very important ability for any musician to develop. From intonation when singing or playing an instrument to playing and transcribing by ear.
What is the best way to improve this? Is software like EarMaster or GNU Solfege any effective? Or is it a non natural way to train your ear?
People have been learning this skill for centuries without these tools.
Some people say you should just sing or play a lot, but what if you can't hear that you're out of tune and keep practicing incorrectly? Should you sing or play then with an electronic tuner to get some feedback or is this also a bad idea?
What is the correct approach based on studies, experience, own learning or teaching?
Comment: A couple of recommendations since you mentioned software: http://music.stackexchange.com/questions/32997/having-trouble-memorizing-intervals-in-ear-training#answer-48294 . These are the only applications that I know that teach you how to recognize scale degrees within a key.
Answer: I break ear training into 3 different categories:

The ability to identify notes from hearing them. This includes hearing intervals, hearing what the note is within a key, or hearing notes from memory.
The ability to tune pitches by telling if they are sharp or flat.
The ability to imagine what the music will sound like from notes before ever having heard it or played it.

There are a lot of methods to attack each of these areas. These do all relate, but I found that it helps to treat them differently as I found that ability in one does not always mean ability in the other.
Identify notes from hearing them:
The main method for this is dictation and transcription. You listen to music, or tunes and or harmonies generated by program or just recordings. It helps to start with simple things and build on this as you get better.
The ability to tune pitches:
Singing with a drone really helps with this. You really feel how a tone fits against the tonal center drone by doing this. Also, playing something like a bass line on the piano and singing the melody, and the other way around, can help with this. A lot of intonation comes from the ability to hear the tonal center of the music and the harmonies. When you can internally hear harmonies and the tonal center you can tune accordingly.
Ability to "hear" music form looking at sheet music before it is played:
I believe sight singing is the best method for this. I strongly believe in using solfege, and fixed do solfege (as most people start to develop some sense of perfect pitch over time) is one of the best ways to do this.
You can first learn to sing intervals, and then simple melodies.  When you can't "hear" an interval in your head before singing it you can fill in the notes between the current note and the next notes with scale notes (best to do them as quick grace notes if you can). If you are lost, you sing the tonal note (the note of the key that the music is in) and then do a scale up to the interval. Eventually, you won't need to sing these in between notes any more.
The above method of singing the tonal center or filling in notes is important. Don't play the notes on a piano before singing them because it should be coming from you and not the instrument. Worst case scenario, play the tonal center note on the piano if you get lost, and build up from there. Everything when you are learning this relates to the tonal center, not the previous pitch -- this keeps you from getting off among other things.
Be Patient:
All of these skills, like playing an instrument, take time. Don't get discouraged, start with the basics in each area and move up as you get better. You start with simple intervals and scales. Then move on to navigating a key fluently. You then learn how to do transitions between different keys. Lastly, if you get advanced you work on stuff that is either atonal or near atonal. This process will likely take years, and is often something musicians work on throughout their whole life.
Comment: Raskolnikov: Can't think of anything off hand. Honestly, with the method I think of for this I software might be more of a hindrance than a help. I recommend the three volumes of Dannhauser starting with volume 1 (http://www.amazon.com/Solfege-Solf%C3%A8ges-Book-1-Dannhauser/dp/0793553261). Remember, don't play the tunes before singing them. Just get the root note of the scale from the piano (as infrequently as possible) and find all the notes based off of that.
Comment: I am new to ear training, can anyone tell me which of these three are covered by the Functional Ear Trainer app (of Android/Apple)?
Answer: Solfege is good. I find it very useful. If you have any other method, still solfege could be a neat supplement.
My teacher suggested me this:

Should practice the notes by singing them, even if you play an instrument.
There should be a drone/fixed note in the background, should try to sing that tone followed by the minor 2nd.
Next: Tone followed by the Major 2nd.
Notes should be sustained. Shouldn't be short.
Should give a small pause between tones. (Bit difficult than continuing a tone from while singing some other.)
Should try to hit the note straight away, shouldn't sing an adjacent tone and glide to it.
Shouldn't try to figure out an interval by recalling a familiar piece. It's cheating!

I wouldn't suggest using a guitar tuner, but it's ok to refer to a keyboard or guitar occasionally. I couple this idea with solfege; for the the melodic intervals exercises in solfege, I sing the notes along before answering.
Comment: Really, I don't see why 7 is cheating. We're not talking about having a contest, we're talking about using whatever means possible to help train the ear and I think that is an effective method. I don't know, maybe I'm missing something here from a pedagogical point of view.
Comment: ...But we look at our keyboards when LEARNING to type. It's very important at the beginning. We just make sure we're not using that as a crutch, only as a first step. Using familiar tunes for interval recognition is a GREAT trick for beginners--just wean yourself off of it as you advance!
Comment: @andyvn22 When I learned to touch type, you looked at the keyboard just once: To put your fingers on the home row keys.  After that, it was all looking at the copy, never at the fingers or keys.   This method was taught in several typing books I read, and in a typing class I took.
Comment: Ability to sing an interval directly is a basic skill. Using some tune as a reference will prevent us from mastering that skill. (Do you look down your keyboard while typing? You can, but one should learn to type without looking, right?).
Comment: 7 is just building on what the student already knows, which is good teaching. Eg. in Kodaly methodology you get the children infused with the quality of,say,a minor third (soh -mi)from numerous songs. Later, when learning intervals, the children usually say unprompted, "Oh, it's like the beginning of..." They've so internalised the interval from repertoire that they can always recognise it. The technique described in number 7 above is a sort of cart before horse approach for those of us who didn't have this childhood training, but it gets you there, which is what matters.
Comment: I know associating a familiar tune to a particular interval is a widely used idea. But it should be avoided while actively working out the exercise, because here the idea is to develop the ability to hit any note directly with the same ease as a touch typist hits a letter, automatically, without needing to think much.
Answer: Back when I was doing ear-training, I wrote an app that would randomly:

Tell me an interval and give me the root tone and then after a keypress play the interval for me.
Play an interval and then I would have to name the interval.
Give me a choice of what intervals to quiz myself on.

Don't ask me for the app, it's for an obsolete platform, that's how old I am. :-)
But you can look up ear training apps.
One thing that really helps learning anything is spaced repetition software (SRS).

Spaced repetition is a learning technique that incorporates increasing
  intervals of time between subsequent review of previously learned
  material in order to exploit the psychological spacing effect.

My favorite SRS is Anki which runs on--well, everything.  I use Anki for learning languages but it takes video and sound files so if you can't find an ear training app that does spaced repetition, then you can easily build an SRS flash card deck using Anki.
Comment: +1 for apps. MusicTheory has a great web app: http://www.musictheory.net/exercises/ear-note
Answer: I have been playing music for a long time. Most of the time I play by myself and I have found that it is so important to practice ear training when playing in a band with a song that you never heard. I apply my ear training like the first day I learn the music note by note:

Play a note, memorize it.
This best practice on piano: Close your eyes and put one finger on anywhere of a key on your piano, hear it and try to guess what note it is.
Interval -
Same as above technique but with two note playing (not the same time).
Chords -
Best use of a program or an app on your iphone or smartphone.
Help of a friend -
Let them play and ask you.
Repeat your brain
while you are not at your instrument.
Just imagine in your head the sound you played: C, D, E, F....F#, Bb whatever....
Your own technique that can help or explore want to share with me ? :)
Good luck and play like a pro.
Answer: I especially agree with @KyleBrandt's answer. I think the most effective ear training tool is playing a string instrument (probably not guitar though). When playing these, you have to tune the instrument, find the note you want as accurately as you can and then find others in relation. I have been playing the violin for 10 years and I think this has worked particularly well to give me a finely-tuned musical ear.
In response to your question about playing out of tune without knowing it, this is why it is useful to have a teacher. You will naturally get a better sense of intonation as you play, but if you have someone to tell you when you are playing out of tune, it will be a faster process.

You can also get a great ear by playing any tuned instrument for a long time, but this is more of a long-term solution. I think playing a string instrument such as the violin for a couple of months will greatly improve your ear if that's the only thing you're looking for, and will work much better than simply listening to more music.


Choosing the number of breakpoints for segmented regression (in R)

Question: What methods/functions are available for choosing the number of breakpoints for segmented regression?
Toy data/code for examples:
set.seed(12)
xx<-1:100
zz<-runif(100)
yy<-2+1.5*pmax(xx-35,0)-1.5*pmax(xx-70,0)+15*pmax(zz-.5,0)+rnorm(100,0,2)
dati<-data.frame(x=xx,y=yy)
plot(dati)

###
# A simple code giving a solution if I were to know that the number of break points is 2
require(segmented)
out.lm<-lm(y~x,data=dati)
o<-segmented(out.lm,seg.Z=~x,psi=c(20,70),
    control=seg.control(display=FALSE))
slope(o)

Thanks.
Answer: You're missing a really important caveat to the question: even if I pick 3 breakpoints, the location of those breakpoints will affect the model performance. So not only the number, but the location is important. I will assume for this problem that you have a prespecified list of possible breakpoints and the question is which ones to use and when.
Since increasing the number of breakpoints increases the overall number of model parameters, this is actually a model or covariate selection problem. BIC and cross-validation are very amenable to this purpose. Basically, set-up an iterative procedure as follows:

Simulate a dataset using k-fold cross validation.
Fit all possible break-point models in your fixed/finite list of possible models
Calculate the BIC for each model.
Repeat 1-3 and calculate averages and error bars for the specific models and choose the one with lowest BIC.

Example using cumulative link for probit regression with ordinally valued outcomes having quadratic trend.
library(MASS)
library(splines)
set.seed(1234)
x <- rnorm(1000)
y <- rnorm(1000, -2 + .3 * x - .3*x^2, 0.3)
cutpoint <- quantile(y, c(0, 0.1, 0.4, 0.7, 1))
ycut <- cut(y, cutpoint, include.lowest=T)

## example of model output
model <- polr(ycut ~ x + I(x^2), method='probit')
plot(x, ycut, main='Properly specified model')
predicted <- apply(predict(model, type='prob'), 1, weighted.mean, x=1:4)
lines(sort(x), predicted[order(x)], col='red')
legend('topleft', pch=c(1, NA), lty=c(0, 1), col=1:2, c('Observed', 'Fitted'))

## use no quadratic effects, expect to find breakpoint at apex
data <- data.frame('x'=x, 'y'=y, 'ycut'=ycut)
breakpoints <- c(-2, 0, 2)

ics <- replicate(1000, {
data <- data[sample(1:nrow(data), nrow(data)*0.75), ]
model1 <- polr(ycut ~ x, data=data, method='probit')
model2 <- polr(ycut ~ ns(x, df=1, knots=0), data=data, method='probit')
model3 <- polr(ycut ~ ns(x, df=1, knots=c(-1, 1)), data=data, method='probit')
model4 <- polr(ycut ~ ns(x, df=1, knots=c(-1, 0, 1)), data=data, method='probit')

ics <- c(BIC(model1), BIC(model2), BIC(model3), BIC(model4))
ics})

plot(rowMeans(ics), type='l', axes=F)
axis(1, at=1:4, labels=c('Linear', 'At 0', 'At -1, 1', 'At -1, 0, 1'))
plot(rowMeans(ics), type='l', axes=F, xlab='', ylab='BIC')
axis(1, at=1:4, labels=c('Linear', 'At 0', 'At -1, 1', 'At -1, 0, 1'))
axis(2)
box()

## best model, albeit the "wrong" one
best <- polr(formula = ycut ~ ns(x, df = 1, knots = 0), method = "probit")
plot(x, ycut, main='Properly specified model')
predicted <- apply(predict(best, type='prob'), 1, weighted.mean, x=1:4)
lines(sort(x), predicted[order(x)], col='red')
legend('topleft', pch=c(1, NA), lty=c(0, 1), col=1:2, c('Observed', 'Fitted'))

This method arrives at a near 100% agreement between the true model and BIC best model for predicting ordinal category based on the mode.
            BIC optimal
Truth               [-6.8,-3] (-3,-2.32] (-2.32,-1.96] (-1.96,-1.22]
      [-6.8,-3]            81          2             0             0
      (-3,-2.32]            1        284             1             0
      (-2.32,-1.96]         0          1           209            16
      (-1.96,-1.22]         0          0            10           395

Answer: I recommend the efp(), Fstats(), and breakpoints() functions in the R strucchange package. The bfast package is nice too and provides wrappers for strucchange and segmented. You can read more about these functions here and in the works cited therein. Please note that these functions are slow on very large datasets. While segmented functions are very fast, I don't think they are as powerful.
Comment: Please provide information *what* are those functions and *why* do you recommend them.


Vector multiplication in BUGS and JAGS

Question: In R, c(3,1,0) * c(2,0,1) == c(6,0,0). This is not dot product and it's not cross product. First, what is the name for this product, and second, does it work in WinBUGS, OpenBUGS and/or JAGS?
Comment: this is just element-wise multiplication. i'm not sure if it works in WinBUGS, OpenBUGS, or JAGS.
Answer: Martyn Plummer points out that this is implemented in JAGS, which I missed when reading the manual. From Ch 5:

Scalar functions taking scalar arguments are automatically vectorized.
  They can also be called when the arguments are arrays with conforming
  dimensions, or scalars. So, for example, the scalar $c$ can be added
  to the matrix $A$ using
B <- A + c

instead of the more verbose form
D <- dim(A)
for (i in 1:D[1])
  for (j in 1:D[2]) {
    B[i,j] <- A[i,j] + c
  }
}

Answer: Unlike JAGS, WinBUGS and OpenBUGS does not do this form of vectorization; you have to write a loop, and compute each element 'by hand', as described above.
Answer: To do element-wise multiplication you can just make a for loop in those languages and that's it! I've used for loops in WinBUGS with no problems.
Comment: What question does this reply address?  It does not seem to be relevant here.
Comment: @whubber, why? It is perfectly relevant. Ok, I changed the post a little to be more clear.
Comment: Yup, a for loop is what I've been doing so far; I'd just wondered if a vectorized version was possible.
Comment: I've submitted a feature request to JAGS: https://sourceforge.net/tracker/?func=detail&aid=3470513&group_id=176821&atid=878777
Comment: Thanks, Tomas.  Now I see the connection: you're not answering the question as stated, but you are offering a workaround.
Answer: Incidentally, element-wise multiplication of two equal length vectors is called the Hadamard product (aka the Schur product).

Vector multiplication in BUGS and JAGS


CallerMemberName not working in AzureFunctionsVersion v4

Question: I have an Azure function using AzureFunctionsVersion v3 and CallerMemberName is working. Another function is AzureFunctionsVersion v4 and using the same code, CallerMemberName is empty:
public async Task TheMethod(dynamic messageJSON, [CallerMemberName] string callerMemberName = "")

The method is two deep in a call:
ProcessMessage(string messageText, [CallerMemberName] string callerMemberName = "")
{
  // callerMemberName in ProcessMessage works
  // callerMemberName in TheMethod is ""
  TheMethod(messageText);
}

Is there something different about AzureFunctionsVersion v4 ?
Answer: The following documentation shows difference between v3 and v4.
The main difference would be that v3 use .NET core3.1 and v4 use .NET6 .
But according the following documentation of .netcore3.1 and  .net6 the implementation of using CallerMemberName to obtain the method or property name of the caller to the method remains the same .