Running eXist-db XQuery in Saxon

Question: What is the recommended way in Saxon to load in an XML document from eXist-db via XQuery GET/POST within an XSL stylesheet?  I want to run an XQL query in eXist-db, which should be simple enough to do as a GET with <xsl:variable name="test" select="doc('xmldb:exist:///db/test.xql')"/> or <xsl:variable name="test" select="doc('http://localhost:8080/exist/rest/db/test.xql')"/>.  But the former doesn't exectute the query and tries to return the XQL source as XML, and the latter doesn't have the basic authentication to execute.  Also, I really want to send an XML fragment using POST, and have the XQL use that posted XML fragment.
I can't find anything in the Saxon documentation about this.  I did find an old EXPath article at http://expath.org/modules/http-client/samples, but the downloads there are 7 years old, and may not work with modern Saxon.  So looking for the best known method to do this.
Comment: Not sure what your usecase is and probably a lot of overkill, but take a look at xslweb. It also supports post and much more. It uses Saxon internally. I use it for web development when your main source is xml. github: https://github.com/Armatiek/xslweb ; presentation on xmlprague: https://archive.xmlprague.cz/2020/files/presentations/xslweb.pdf
Answer: The first thing that comes to mind is the EXPath HTTP Client module. There's no way to persuade the doc() or document() functions to do POST instead of GET, AFAIK.
Comment: If you change the permissions on the query stored in eXist, so that it is executable by guest, you will not need to worry about authentication.
Comment: Well, you can persuade the doc() function to do pretty well anything if you provide a custom resolver; but a user-written extension function probably makes more sense.
Comment: OK, so no POST without writing extensions in Java or C#, and nobody else has already done this, apart from EXPath HTTP Client.  Michael, this something I can/should be using with the latest Saxon?
Comment: On the GET, what about simply using doc() to execute XQuery in eXist-db via GET?  Is that possible?  xmldb:exist always returns the XQuery source rather than the query results.  And the REST url fails as I can't pass the basic auth username:password.  Am I missing the way to do this, or does it simply not work?
Comment: Thanks Joe.  That got doc('http://localhost:8080/exist/rest/db/test.xql') working for me as a GET.  Curious, am I correct to assume doc('xmldb:exist:///db/test.xql') cannot execute the query and can only return source?
Comment: Yes you are correct, doc('xmldb:exist:///db/test.xql') cannot execute the query and can only return source.

Running eXist-db XQuery in Saxon


How can I get a checkbox to return True/False?

Question: I'm working with the form API and I have a series of checkboxes. I need them to return true or false instead of 1 and 0.
$form['checkbox1'] = array(
    '#type' => 'checkbox',
    '#return_value' => 'true',
    '#title' => t('Checkbox title'),
    );

This works if the box is checked, but if it's left unchecked it still returns 0. Is there a way I can get an unchecked box to return false?
Comment: Is there any reason you want to get `FALSE` instead of `0`?
Answer: It depends how you want to use the true/false value.
Case 1
You could change the data in a validation handler. In hook_form_alter, something like:
$form['#validate'][] = 'my_great_handler';

Then:
function my_great_handler($form, &form_state){
  $form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value']
    = ($form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] == 1);
}

Not sure what that would do for you, though.
Case 2
If you want to show users true/false rather than 1 or 0, you could change that in a template. Create a template for the field, and add something like:
Checkbox: <?php print $checkbox1 == 1 ? 'True' : 'False'; ?>

Case 3
If you want to save the data in a custom data store, you would add similar code right before the save, in hook_node_save, or some such.


what does this error mean and how do I get rid of it?

Question: I have Android SDK installed in two different folders (slightly different versions) two copies of the same project open in both (that is, SDK1 - Project1; SDK2 -> Copy of Project1). SDK1 works fine, but SDK2 shows an error
Call requires API level 13 (current min is 8): android.view.Display#getSize

at the line
getWindowManager().getDefaultDisplay().getSize(p);

In the MainActivity class. How do I remove this?
(I am pretty sure this has something to do with the compiler options or something; SDK2 suggests that I just add @SuppressWarning to onCreate() while I don't need to do anything with SDK1; would simply suppressing warning be enough, or would it break my program in unexpected ways later)?
Comment: change your min sdk to 13 in manifest
Comment: Based on the error message, it's possible that your app will break if the user is using HoneyComb (API 12) or older since the method is not existed yet in those version.
Comment: like I said, it is a copy of a project that runs without error in SDK1. Why doesn't SDK1 how any errors though? By the way, SDK1 is the slightly older version.
Answer: this warning tells you that the app can be run on SDK lower than 13, getDefaultDisplay() is available since API 13, so if you run it on lower SDK, you will get some kind of ClassNotFound or MethodNotFound exception. You have to manage this code for lower API levels.
To manage this, you can use the android.os.Build.VERSION.SDK_INT which returns the current API level and add the @SuppressWarning annotation
EDIT: the reason you get this warning is that you use higher targetSdkVersion than minSdkVersion in your manifest
Comment: SDK1 and SDK2 will run with no difference. The warnings has nothing to do with the final application. They are a product of code analyzer that informs you for potential problems.
Comment: like I said, it is a copy of a project that runs without error in SDK1. Why doesn't SDK1 how any errors though? By the way, SDK1 is the slightly older version.
Comment: because the SDK become smarter - new warnings are added to make it easier for you to manage such kind of issues
Comment: in other words, if you compile it with the older SDK, this doesn't fix the problem, you just don't get informed about it.
Comment: so that means, at least for my test device, SDK2 should work the same as SDK1, if I just add the `@SuppressWarnings` ?
Answer: The error explain itself you are calling a method or a class that doesn't exist before API 13 and your min API is 8! change to these lines in manifest.xml
<uses-sdk
    android:minSdkVersion="13"
    android:targetSdkVersion="13" />

you can keep your android:targetSdkVersion="13" in your project if its above 13
Comment: `android:minSdkVersion="8"` in SDK1 as well. Why isn't it showing any errors there? (By the way, SDK1 is the slightly older version.)
Comment: yes its maybe the version difference between sdk1 and sdk2 or maybe you are missing some other details. check the project.properties file and let me know if you differece
Comment: project.properties files are exactly same, and has `target=android-18` below the #'ed comments
Comment: but it looks like Mihail's post above answers the question
Comment: accoring to http://developer.android.com/guide/topics/manifest/uses-sdk-element.html "Despite its name, this element is used to specify the API Level, not the version number of the SDK (software development kit) or Android platform"  So it is the version difference between sdk1 and sdk2
Comment: yes it seems to be due to the version difference; apparently this new error notification was added in the newer SDK


Renaming a content type during migration

Question: I am migrating a Drupal 6 site to Drupal 8. On the Drupal 6 site I have a content type called book_page but would like it be called faq on the new site.
I set the default_bundle to faq in my yml file but it still migrates as book_page.
Here is my yml file:
uuid: a67dbd6f-416c-44c0-9698-05ec3bb3c5a9
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_node_book_page
migration_tags:
  - 'Drupal 6'
migration_group: d6_migrate_group
label: 'Nodes (book_page)'
source:
  plugin: d6_node
  node_type: book_page
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration
    migration: upgrade_d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_image:
    plugin: d6_cck_file
    source: field_image
  field_upload_files:
    plugin: d6_cck_file
    source: field_upload_files
destination:
  plugin: 'entity:node'
  default_bundle: faq
migration_dependencies:
  required:
    - upgrade_d6_user
    - upgrade_d6_node_type
    - upgrade_d6_node_settings
    - upgrade_d6_filter_format
  optional:
    - upgrade_d6_field_instance_widget_settings
    - upgrade_d6_field_formatter_settings
    - upgrade_d6_upload_field_instance

Anyone have an idea what I am doing wrong?
Update:
I have also tried adding the following under process under each of my node yml files?:
type:
  plugin: default_value
  value: faq

I wonder if the All node types are created in ....node_type.yml?
Answer: As you've figured out, modifying the d6_node-based migration affects how the content of a given node type is migrated, but does not affect how the actual node type itself is migrated - that is done in d6_node_type. To rename the types themselves in migration, while you could modify the source query as you did, it's simpler to modify the .yml to remap values.
In upgrade_d6_node_type.yml,  you can replace
process:
  type: type
  name: name

with
process:
  type:
    plugin: static_map
    bypass: true
    source: type
    map:
      story: post
      book_page: faq
  name:
    plugin: static_map
    bypass: true
    source: name
    map:
      story: post
      'Book Page': Faq

Comment: Thanks! That looks like a better way than I did.  Any simple way to exclude content types as well from being created?
Comment: @albertski: Removing ```bypass: true``` from the type mapping should skip any node types not explicitly mapped.
Comment: @Pierre.Vriens - Afraid I've never been - maybe someday!
Comment: Does anyone know what the key "story" refers to? Is that something from the OP that isn't there anymore, or a Drupal thing? I don't see mentioned it anywhere on https://www.drupalmigrate.org/plugin/process/staticmap or the OP, so not sure where it came from and if I need it.
Answer: I was able to perform this by creating a custom module and adding a custom source plugin to modify the query.
custom_migration/src/Plugin/migrate/source/d6/CustomNodeType.php
<?php

namespace Drupal\custom_migration\Plugin\migrate\source\d6;

use Drupal\node\Plugin\migrate\source\d6\NodeType;

/**
 * Drupal 6 Node types source from database.
 *
 * @MigrateSource(
 *   id = "custom_node_type"
 * )
 */
class CustomNodeType extends NodeType {
  /**
   * Override the query() method, and provide a custom query that selects just
   * the node types you want.
   */
  public function query() {
    // Our custom query returns only the node types we want and renames them.
    $query = $this->select('node_type', 't');
    $query->fields('t', array(
        'module',
        'description',
        'help',
        'title_label',
        'has_body',
        'body_label',
        'min_word_count',
        'custom',
        'modified',
        'locked',
        'orig_type',
      ));

    // Rename content types.
    $query->addExpression("
      CASE
        WHEN t.type = 'story' THEN 'post'
        WHEN t.type = 'book_page' THEN 'faq'
        ELSE t.type
      END
    ", 'type');

    // Rename content type names.
    $query->addExpression("
      CASE
        WHEN t.name = 'Book Page' THEN 'Faq'
        WHEN t.name = 'Story' THEN 'Story'
        ELSE t.name
      END
    ", 'name');

    // Exclude content types you don't want to migrate.
    $query->condition('t.type', array('forum', 'program', 'show', 'webform', 'homepage_slide'), 'NOT IN');
    $query->orderBy('t.type');

    return $query;
  }
}


Convert an audio to uncompress wav by libvlc

Question:
OS : win10 64 bits
compiler : vc2017 64bits
vlc version : 184.108.40.206 from here

Source codes
#include <vlc/vlc.h>

#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

void libvlc_callback(libvlc_event_t const *event, void*)
{
    switch (event->type) {
    case libvlc_MediaMetaChanged:
        std::cout<<__func__<<": libvlc_MediaMetaChanged = "<<event->u.media_meta_changed.meta_type<<std::endl;
        break;
    case libvlc_MediaSubItemAdded:
        std::cout<<__func__<<": libvlc_MediaSubItemAdded = "<<event->u.media_subitem_added.new_child<<std::endl;
        break;
    case libvlc_MediaDurationChanged:
        std::cout<<__func__<<": libvlc_MediaDurationChanged = "
                <<event->u.media_duration_changed.new_duration<<std::endl;
        break;
    case libvlc_MediaParsedChanged:
        std::cout<<__func__<<": libvlc_MediaParsedChanged = "<<event->u.media_parsed_changed.new_status<<std::endl;
        break;
    case libvlc_MediaFreed:
        std::cout<<__func__<<": libvlc_MediaFreed = "<<event->u.media_freed.md<<std::endl;
        break;
    case libvlc_MediaStateChanged:
        std::cout<<__func__<<":libvlc_MediaStateChanged = "<<event->u.media_state_changed.new_state<<std::endl;
        break;
    default:
        break;
    }
}

std::vector<libvlc_event_e> create_events()
{
    return {libvlc_MediaMetaChanged,
                libvlc_MediaSubItemAdded,
                libvlc_MediaDurationChanged,
                libvlc_MediaParsedChanged,
                libvlc_MediaFreed,
                libvlc_MediaStateChanged};
}

int main()
{
    libvlc_instance_t *inst = libvlc_new(0, nullptr);
    char const *location = "C:/Users/ssss/audio/audio.mp3";
    libvlc_media_t *vlc_media = libvlc_media_new_location(inst, location);
    libvlc_event_manager_t *vlc_events = libvlc_media_event_manager(vlc_media);

    for(libvlc_event_e const &event : create_events()){
        libvlc_event_attach(vlc_events, event, libvlc_callback, nullptr);
    }

    libvlc_media_add_option(vlc_media, "--sout='#transcode{acodec=s16l, ab=16, channels=1, samplerate=16000}:"
                                       "std{access=file, mux=wav, "
                                       "dst=\"audio.wav\"}'");

    std::this_thread::sleep_for(std::chrono::seconds(10));

    libvlc_media_release(vlc_media);
    libvlc_release(inst);
}

The output I got are
main libvlc debug: VLC media player - 220.127.116.11 Vetinari
main libvlc debug: Copyright © 1996-2020 the VideoLAN team
main libvlc debug: revision 184.108.40.206-0-gd4c1aefe4d
main libvlc debug: configured with ../extras/package/win32/../../../configure  '--enable-update-check' '--enable-lua' '--enable-faad' '--enable-flac' '--enable-theora' '--enable-avcodec' '--enable-merge-ffmpeg' '--enable-dca' '--enable-mpc' '--enable-libass' '--enable-schroedinger' '--enable-realrtsp' '--enable-live555' '--enable-dvdread' '--enable-shout' '--enable-goom' '--enable-caca' '--enable-qt' '--enable-skins2' '--enable-sse' '--enable-mmx' '--enable-libcddb' '--enable-zvbi' '--disable-telx' '--enable-nls' '--host=x86_64-w64-mingw32' '--with-breakpad=https://win.crashes.videolan.org' 'host_alias=x86_64-w64-mingw32' 'PKG_CONFIG_LIBDIR=/home/jenkins/workspace/vlc-release/windows/vlc-release-win32-x64/contrib/x86_64-w64-mingw32/lib/pkgconfig'
main libvlc debug: using multimedia timers as clock source
main libvlc debug:  min period: 1 ms, max period: 1000000 ms
main libvlc debug: searching plug-in modules
main libvlc debug: loading plugins cache file C:\vlc-126.96.36.199-win64\plugins\plugins.dat
main libvlc warning: cannot read C:\vlc\vlc-188.8.131.52-win64\plugins\plugins.dat: No such file or directory
main libvlc debug: recursively browsing `C:\vlc\vlc-220.127.116.11-win64\plugins'
main libvlc debug: plug-ins loaded: 494 modules
main logger debug: looking for logger module matching "any": 2 candidates
main logger debug: using logger module "console"
main libvlc debug: translation test: code is "C"
main keystore debug: looking for keystore module matching "memory": 3 candidates
main keystore debug: using keystore module "memory"
main libvlc debug: CPU has capabilities MMX MMXEXT SSE SSE2 SSE3 SSSE3 SSE4.1 SSE4.2 FPU
libvlc_callback: libvlc_MediaFreed = 000001DBD602CC50
main libvlc debug: exiting
main libvlc debug: no exit handler
main libvlc debug: removing all interfaces
main keystore debug: removing module "memory"

I cannot see any audio.wav generated in the folder, which step I missed or done it wrong? Thanks
Edit: pass parameters into libvlc_new
const char * const vlc_args[] = {
                  "--sout",
   "#transcode{acodec=s16l,channels=2,samplerate=44100}:std{access=file,mux=wav,dst=\"C:/my_path/clip_0002.wav\"}",
    "C:/my_path/audio.wav"};
    libvlc_instance_t *inst = libvlc_new(3, vlc_args);

    std::this_thread::sleep_for(std::chrono::seconds(60));
    libvlc_release(inst);

It give me output message
main libvlc debug: exiting
main libvlc debug: no exit handler
main libvlc debug: removing all interfaces
main keystore debug: removing module "memory"

Don't know why the output file 'audio.wav' never generated in the folder
Comment: I think these options belong in `libvlc_new`
Comment: @mfkl Thanks, I pass arguments into libvlc_new, but the output file cannot gererated
Comment: use `--verbose=2` to have some logs
Answer: Found a solution, you need to play the media and open the file correctly, for simplicity I use "libvlc_media_new_path" in this example, if you are using "libvlc_media_new_location", remember to append "file:///" before the location and change to native separator.
#include "core/vlc_error.hpp"

#include <vlc/vlc.h>

#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include <QString>

void libvlc_callback(libvlc_event_t const *event, void*)
{
    switch (event->type) {
    case libvlc_MediaMetaChanged:
        std::cout<<__func__<<": libvlc_MediaMetaChanged = "<<event->u.media_meta_changed.meta_type<<std::endl;
        break;
    case libvlc_MediaSubItemAdded:
        std::cout<<__func__<<": libvlc_MediaSubItemAdded = "<<event->u.media_subitem_added.new_child<<std::endl;
        break;
    case libvlc_MediaDurationChanged:
        std::cout<<__func__<<": libvlc_MediaDurationChanged = "
                <<event->u.media_duration_changed.new_duration<<std::endl;
        break;
    case libvlc_MediaParsedChanged:
        std::cout<<__func__<<": libvlc_MediaParsedChanged = "<<event->u.media_parsed_changed.new_status<<std::endl;
        break;
    case libvlc_MediaFreed:
        std::cout<<__func__<<": libvlc_MediaFreed = "<<event->u.media_freed.md<<std::endl;
        break;
    case libvlc_MediaStateChanged:
        std::cout<<__func__<<":libvlc_MediaStateChanged = "<<event->u.media_state_changed.new_state<<std::endl;
        break;
    default:
        break;
    }
}

std::vector<libvlc_event_e> create_events()
{
    return {libvlc_MediaMetaChanged,
                libvlc_MediaSubItemAdded,
                libvlc_MediaDurationChanged,
                libvlc_MediaParsedChanged,
                libvlc_MediaListEndReached,
                libvlc_MediaFreed,
                libvlc_MediaStateChanged};
}

int main()
{
    libvlc_instance_t *inst = libvlc_new(0, nullptr);
    char const *location = "clip_0002.wav";
    libvlc_media_t *vlc_media = libvlc_media_new_path(inst, location);
    libvlc_event_manager_t *vlc_events = libvlc_media_event_manager(vlc_media);

    for(libvlc_event_e const &event : create_events()){
        libvlc_event_attach(vlc_events, event, libvlc_callback, nullptr);
    }

    QString const cmd("transcode{acodec=s16l, ab=16, channels=1, samplerate=16000}:"
                      "std{access=file, mux=wav, "
                      "dst='audio.wav'}");
    QString config = ":sout=#duplicate{dst=display,dst=\"%1\"}";
    config = config.arg(cmd);
    std::cout<<"-------------------------"<<std::endl;
    std::cout<<config.toStdString()<<std::endl;
    libvlc_media_add_option(vlc_media, ":sout-all");
    qt_vlc::vlc_error::show_err_msg();
    libvlc_media_add_option(vlc_media, config.toUtf8().data());
    qt_vlc::vlc_error::show_err_msg();

    libvlc_media_player_t *vlc_player = libvlc_media_player_new_from_media(vlc_media);
    libvlc_audio_set_mute(vlc_player, true);
    libvlc_media_player_play(vlc_player);

    while(1){
        qt_vlc::vlc_error::show_err_msg();
        if(libvlc_media_get_state(vlc_media) == libvlc_Ended){
            break;
        }
        std::cout<<"media state = "<<libvlc_media_get_state(vlc_media)<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    libvlc_media_player_release(vlc_player);
    libvlc_media_release(vlc_media);
    libvlc_release(inst);
}

You can convert video to audio by this solution too, problem is it will show the video when converting, finding a way to hide the video.


Como destruir um jobSchedule via Activity?

Question: Estou estudando os serviços em Background do Android e consegui criar um serviço em Background que já funciona bem em background mesmo apos reiniciar o android ou fechar o App.
O problema se encontra quando eu quero encerrar o JobService por um botão na Activity.
Tentei com: jobScheduler.cancel(id) e jobScheduler.cancelAll(). Mas nenhum dos dois surtiu efeito.
Meu código esta da seguinte forma atualmente:

BroadcastReceiver.java
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ComponentName comp = new ComponentName(context.getPackageName(), ServiceLocationJob.class.getName());

                JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

                JobInfo jobInfo = new JobInfo.Builder(11, comp)
                        // only add if network access is required
                        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                        .setMinimumLatency(1)
                        .setOverrideDeadline(1)
                        .build();

                jobScheduler.schedule(jobInfo);
                Log.d(Tag, "Iniciado servicoJob as: " + c.getTime().toString());
            }

ServiceLocationJob.java
    private Thread locationThread;

        @Override
        public boolean onStartJob(JobParameters jobParameters) {

            locationThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(Tag, "Serviço (API<21) iniciado pelo Broadcast com sucesso!");

                    new Timer().scheduleAtFixedRate(new TimerTask(){
                        @Override
                        public void run(){
                            Calendar c = Calendar.getInstance();
                            Log.i(Tag, "Serviço funcionando a cada 10 segundos mesmo após reiniciar: " + c.getTime());
                        }
                    },0,10000);
                }
            });

            locationThread.start();

            return true;
        }

E finalmente o MainActivity.java
    public void desligarServico() {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                JobScheduler jobScheduler = (JobScheduler)this.getSystemService(Context.JOB_SCHEDULER_SERVICE );
                jobScheduler.cancelAll();
                Log.d(Tag, "Serviço parado (API>=21) com sucesso");
            }
    }

Não sei se é a Thread que fica viva mesmo após cancelar o JobScheduler. Tanto que acabei tentando colocar locationThread.interrupt(); dentro do metodo onStopJob(), mas ainda sem sucesso.
Já tentei colocar no metodo onStopJob da classe JobService o metodo jobFinished(jobParameters, false);. Mas ainda assim eu não consegui parar o serviço por completo utilizando o botão.
Gostaria de uma sugestão de como resolver isso.
Answer:
Não sei se é a Thread que fica viva mesmo após cancelar o JobScheduler

Tudo indica que sim.
Não só a Thread necessita de ser parada como tem de cancelar o Timer.
Note que um JobScheduler deve ser usado para executar uma tarefa e terminar.
Não é algo para ficar rodando à espera que seja finalizado externamente.
Caso seja usada uma Thread, ao terminar, ela deve chamar o método jobFinished() para indicar que o JobScheduler pode libertar o seu wakelock e terminar.
Se quer que a tarefa seja executada de tempos a tempos, configure o JobScheduler como periódico.


php-fpm package not available, Ubuntu 14.04 LTS

Question: I try to install the package php5-fpm on dist Ubuntu 14.04 LTS, nginx. But I get this message:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php5-fpm is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'php5-fpm' has no installation candidate

I have search a lot what could be wrong and some answer stating that not all the right path's are in the "sources.list" file. I have uncomment lines where path's (URLs) where commented out. My "sources.list" file now looks like this:
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://se.archive.ubuntu.com/ubuntu/ trusty main restricted
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://se.archive.ubuntu.com/ubuntu/ trusty-updates main restricted
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://se.archive.ubuntu.com/ubuntu/ trusty universe
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty universe
deb http://se.archive.ubuntu.com/ubuntu/ trusty-updates universe
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://se.archive.ubuntu.com/ubuntu/ trusty multiverse
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty multiverse
deb http://se.archive.ubuntu.com/ubuntu/ trusty-updates multiverse
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://se.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse
deb-src http://se.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse

deb http://security.ubuntu.com/ubuntu trusty-security main restricted
deb-src http://security.ubuntu.com/ubuntu trusty-security main restricted
deb http://security.ubuntu.com/ubuntu trusty-security universe
deb-src http://security.ubuntu.com/ubuntu trusty-security universe
deb http://security.ubuntu.com/ubuntu trusty-security multiverse
deb-src http://security.ubuntu.com/ubuntu trusty-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu saucy partner
deb-src http://archive.canonical.com/ubuntu saucy partner

## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu trusty main
deb-src http://extras.ubuntu.com/ubuntu trusty main

How come that I cant install "php5-fpm" and how do I solve it?
Comment: Did you do an `apt-get update` after activating the `universe` repo?
Answer: I think you forgot to do apt-get update as everything seems to be ok.


htaccess redirect loop directory to php file

Question: RewriteRule ^cart.php(.*?) https://www.DOMAIN.com/buy-now/$1 [R=301,L]
RewriteRule ^buy-now/(.*?) cart.php$1 [QSA]

This creates a redirect loop. What i want is for cart.php to redirect to /buy-now/ (carrying query strings) and /buy-now/ to actually parse as cart.php.
Answer: Yes this will sure cause loop. You will need to use %{THE_REQUEST} to avoid this looping.
Have your rule like this:
RewriteEngine On

RewriteCond %{THE_REQUEST} /+cart\.php [NC]
RewriteRule ^cart\.php(.*)$ /buy-now/$1 [R=301,L,NC]

RewriteRule ^buy-now/(.*)$ /cart.php$1 [L,NC]

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules.
Comment: Don't think `(.*)` is required since he wants to retain the query string so perhaps just add `QSA` to it, since query string are not available on the `(.*)`.
Comment: okay thanks. i was trying something similar to that but i used %{REQUEST_URI} for some reason... wrong variable.
Comment: @Prix: Actually `QSA` isn't even needed since OP is not passing `$1` in query string.
Comment: @anubhava `to redirect to /buy-now/ (carrying query strings)` so I am assuming he thinks `(.*?)` will catch the query strings which doesn't, which is why I don't think they are needed on your sample and rather the use of `QSA` would have been more suitable.
Comment: Yes I have seen that `carrying query strings` and `QSA` is not the flag for this since that is default behavior anyway. `QSA` is ONLY needed when rule is adding a new query parameter and you want to preserve existing query string.
Comment: @b747fp yes it should but will have overhead from the unneeded parts that's all.


Separable Bnach space implies that the unit ball is separable

Question: if someone could give me an idea of how to carry out this demonstration I would greatly appreciate it, let E be a Banach space, demonstrate
E is separables $\Rightarrow$ The closed unit ball $B_E=\{x∈E:||x||≤1\}$ is separables
Comment: Does this answer your question? [Is the unit ball of a separable Banach space itself separable?](https://math.stackexchange.com/questions/352581/is-the-unit-ball-of-a-separable-banach-space-itself-separable)
Answer: Let $A$ be a countable dense subset of $E$. Then for every positive rational $r\le 1$, $A_r'=\{\frac{ra}{\|a\|}\mid a\in A\}$ is countable and dense on the sphere of radius $r$. Then the union $\cup_r A_r'$ is a countable dense subset of the unit ball.
Comment: Please do not answer questions without context. See https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards?cb=1
Comment: @KaviRamaMurthy: This question does have context, at least for me. Apparently, as FreeHongKong pointed out, this is an exact copy of another question on this site which also has answer.


Self-organising Neural Network - Looking for litterature

Question: I am looking at developing an algorithm that would automatically grow the structure of a neural network by adding/deleting units within a layer, or adding layers as necessary.
I researched the topic and only found literature from before 2000. I was somewhat aware of it, being old enough to have come across some of them when they were published. What I found is mostly interested in neuron-by-neuron construction. I didn't find anything layer-by-layer.
I have searched for more recent papers, including in the deep learning space and have drawn a blank.
I wrote a draft blog article laying out my thoughts (https://emmanuel-r8.github.io/post/neural-network-incremental-growth.html). I will carry on researching the topic. But I am looking for references that would tell me that it is either a blind alley or expand my horizons.
Answer: This might be useful: https://www.amazon.com/SORN-Self-Organizing-Recurrent-Neural-Network-ebook/dp/B00X1FIHCO
And this : https://pypi.org/project/sorn/
Comment: Could you give full references in case the links go dead in the future? Short summaries of the content of each would be helpful, too. Thank you.
Comment: Thank you. One of the citations also looks interesting: https://papers.nips.cc/paper/3394-self-organization-using-synaptic-plasticity
Comment: More generally, NIPS has quite a few more references (although not quite on point. But no doubt I'll find many ideas!): https://papers.nips.cc/search/?q=self-organizing
Comment: I made the comment based on the papers' title. I'll comment more when I have read the papers.


Permission denied @ apply2files - /usr/local/lib/node_modules/node-red/node_modules/websocket-stream/node_modules/ws/lib/.DS_Store

Question: I was installing imagemagick via brew
brew install imagemagick
and then I stumble upon this error message:
Permission denied @ apply2files - /usr/local/lib/node_modules/node-red/node_modules/websocket-stream/node_modules/ws/lib/.DS_Store

Once sudo is not advisable using homebrew, is there any hints on how to solve this issue?
More lines from terminal to give context:
==> Installing imagemagick
==> Pouring imagemagick-7.0.10-28.catalina.bottle.tar.gz
  /usr/local/Cellar/imagemagick/7.0.10-28: 1,499 files, 25.6MB
==> `brew cleanup` has not been run in 30 days, running now...
Removing: /Users/username/Library/Caches/Homebrew/gcc--9.3.0.catalina.bottle.tar.gz... (84.8MB)
Removing: /usr/local/Cellar/gdbm/1.18.1... (20 files, 586.8KB)
Removing: /Users/username/Library/Caches/Homebrew/gdbm--1.18.1.mojave.bottle.1.tar.gz... (196.2KB)
Removing: /Users/username/Library/Caches/Homebrew/gmp--6.2.0.catalina.bottle.tar.gz... (1022.7KB)
Removing: /Users/username/Library/Caches/Homebrew/icu4c--64.2.mojave.bottle.tar.gz... (26.1MB)
Removing: /Users/username/Library/Caches/Homebrew/isl--0.22.1.catalina.bottle.tar.gz... (1.5MB)
Removing: /Users/username/Library/Caches/Homebrew/libmpc--1.1.0.catalina.bottle.tar.gz... (114.4KB)
Removing: /Users/username/Library/Caches/Homebrew/mpfr--4.0.2.catalina.bottle.tar.gz... (1.1MB)
Removing: /firstname.lastname@example.com/1.1.1d... (7,983 files, 17.9MB)
Removing: /firstname.lastname@example.com... (5.2MB)
Removing: /usr/local/Cellar/python/3.7.6_1... (4,036 files, 62.2MB)
Removing: /firstname.lastname@example.com/3.8.1... (4,094 files, 62.5MB)
Removing: /Users/username/Library/Caches/Homebrew/readline--8.0.4.catalina.bottle.tar.gz... (517.7KB)
Removing: /usr/local/Cellar/sqlite/3.31.1... (11 files, 4MB)
Removing: /Users/username/Library/Caches/Homebrew/sqlite--3.31.1.catalina.bottle.tar.gz... (1.9MB)
Removing: /usr/local/Cellar/xz/5.2.4... (92 files, 1MB)
Removing: /Users/username/Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz... (9.0MB)
Removing: /Users/username/Library/Caches/Homebrew/Cask/miniconda--4.7.12.sh... (48.2MB)
Removing: /Users/username/Library/Logs/Homebrew/gmp... (64B)
Removing: /Users/username/Library/Logs/Homebrew/mpfr... (64B)
Removing: /Users/username/Library/Logs/Homebrew/gcc... (64B)
Removing: /Users/username/Library/Logs/Homebrew/isl... (64B)
Removing: /Users/username/Library/Logs/Homebrew/libmpc... (64B)
Pruned 2 symbolic links and 4 directories from /usr/local
Error: Permission denied @ apply2files - /usr/local/lib/node_modules/node-red/node_modules/websocket-stream/node_modules/ws/lib/.DS_Store

Comment: That is a question for `brew` and the question is why is imagemagik messing with the `websocket-stream` node.
Answer: It works for me.
sudo chown -R $(whoami):admin /usr/local


Programmatically render a custom form in a view template while passing view argument to form

Question: I have built a custom form (in its own module using FORM API) and have exposed this form also as a block using Plugin API.
I can add this form fine to page and get it to render using Block Layout but it doesnt appear in the correct place.
I am trying to get it to appear in the main page content of a Page View which has a Header and Footer. The form seems to appear after the footer content, even after shifting the block around in the block layout.
So now I have been trying to use the various view template hooks by loading the form via the snippet:
$block = \Drupal\block\Entity\Block::load('auctioncataloguerequestform');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$variables['form_auction_cat_request'] = $block_content;

auctioncataloguerequestform is the machine name of the "form block" added to Block Layouts (Its in the content section, but disabled)
But in XDebug I cannot find the form_auction_cat_request variable and {{ form_auction_cat_request }} renders nothing.
Hooks I tried using where: template_preprocess_views_view, template_preprocess_views_view_field and template_preprocess_views_view_unformatted
At the moment I am simply trying to get the form to render but once this is done I then need to pass a string variable which is a field of the view in question to be passed to the form.
Am I on the right track or completely missing the mark?
View screenshot
Answer: Print form before the views:
function mymodule_preprocess_views_view(&$variables) {
  $form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
  $variables['attachment_before'][] = $form;
}

===
Another way is to add your custom form and the views in own controller (and route),
In views add filters and expose them, set exposed in block = yes (this will detach the form from the views),
in exposed filters settings set the names as they are in your form - for each one,
make your form to redirect on submit to the route passing the values as query params (?param_name=value&param_name2=value2), for multiple select or checkboxes params are in format: param_name[6]=6&param_name[17]=17
the rest will be done by views - it will get params automatically
Controller:
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Class DefaultController.
 */
class DefaultController extends ControllerBase {

  /**
   * Content.
   *
   * @return string
   *   Return Content string.
   */
  public function content() {

    $elements = [];

    $elements['form_search'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
    $elements['form_search']['#weight'] = 0;

    $views_name = 'machine_views_name';
    $display_id = 'page_1';
    $view = Views::getView($views_name);
    $view->setDisplay($display_id);

    $elements['view'] = $view->render($display_id);
    $elements['view']['#weight'] = 1;

    return $elements;
  }

}

example module with controller, form and exported views "Content list": https://github.com/svetlio/mymodule
Comment: The first suggestion worked for me for displaying the form correctly, still can't inject a string variable though. Will investigate further today on that. Thanks for the help
Comment: There are 2 keys points for this: 1. Add a filter field in the views to search in ("Title" for ex.), expose him, change the "Filter identifier" in a filter conf to "string" for ex.; 2. On submit pass the value to $_GET['string'], so url should look like "/your_views_path?string=something+to+search". You can test it just by typing this kind of url to see results in the views, then research how to redirect your form "on submit" to this url.


Time Series Visualization

Question: Does anyone know how I could create a graph like this one to visualize time series of anual temperature for different years in R?

Thank you very much for your help! :)
Answer: This is a standard surface plot. Just look for "plot a surface over the an x-y plane".
Such plots can be created with base R but they are many other packages (e.g. rgl, ggplot, etc.) that offer similar (and more sophisticated) functionality. Here is a quick proof-of-concept with base-R:
set.seed(14)
x <- seq(1772, 2017, by = 10)
y <- seq(-2, 5, length = length(x))
z <- outer(x, y, function(a, b) sin(b)) + runif(n=length(x)^2, max=0.3)
persp(x, y, z, phi=10, theta=-50)

Comment: Characterizing this as a "surface plot" misses the characteristic feature that it appears to interpolate smoothly in just one direction.  It is, in effect, a pseudo-3D stack of curves. Another special aspect is that each curve is a (univariate) *histogram:* thus, each $y$ cross-section integrates to unity.
Comment: I disagree. Characterising it as not a surface plot complicates its implementation in terms of plotting. Whether or not this is the density or not, or smoothed or not, is immaterial to the plotting and mostly complicates the solution. (I did think of normalising each trajectoriy to integrate to 1 but the realised it just added a potentially redundant layer of functionality.)
Comment: On the contrary, once you recognize the nature of this plot, it allows for a *simpler* algorithm (one of the earliest known for such pseudo 3D plots).  More importantly, the nature of the surface and of the interpolation are important and would likely not be rendered accurately by an arbitrary interpolator.
Comment: I do not think that the interpolation as a part of the plotting implementation. "*it allows for a simpler algorithm (one of the earliest known for such pseudo 3D plots)*". OK, let's see it in R (or your language of choice). :) I might learn something new (from you) (*again*).
Comment: Plotting is tantamount to interpolation. The method illustrated in the question appears related to one of the first 3D methods developed because it didn't need clever ways to remove hidden features: you simply draw the cross-sections back to front, letting each new one occlude the others. You can probably find good examples and descriptions in any graphics textbook published before c. 1985. It looks like `persp` triangulates the data, which works here when all cross-sections are evenly sampled; if you tried to apply almost any other method of interpolation, this plot will look very different.
Comment: I think now we are venturing into what could have happened behind the question. If the data weren't equisampled, if the data needed interpolation, if it had "hidden features" we had to remove. Ehh... OK, if my interpolator had infinite support it would be an extrapolator. Your point about "*simply draw the cross-sections back to front*" is pretty much my point too here. Just use a simple surface plotting routine and move forward with it.

Time Series Visualization


How do we find total number of odd multiples of a number?

Question: For example: Find odd multiples of 7 less than 500. [only +ve values]
I know that to find the multiples of 7 b/w 1 and 499, we find the smallest and largest multiple of 7 within the given range. So here that would be 7 and  497. We subtract the quotient of the larger no. by the smaller no. and add 1.
7×1=7
7×71=497
which is, 71 - 1 + 1 = 71
so, there are 71 numbers b/w 1 and 499 that are multiples of 7.
But now how to find how many of these 71 are odd?
Comment: How many multiples of $14$ are less than $500$?
Answer: $a \times 7$ is even if and only if $2|a$ (Gauss' theorem). So, roughly half of your numbers are odd, and half are even (I let you handle the + or - $1$).
Answer: All odd multiples of $7$ can be found by taking multiples of $14$ and subtracting $7$ from each of them. So your problem is reduced to finding the number of multiples of $14$ less than $507$. This can be done by taking the integer part of $\frac{506}{14},$ which is $36.$
Thus, there are $36$ odd multiples of $7$ less than $500$.


is there any way to load commerce_products into a collection in rules configuration

Question: I need to load all commerce products that their status is "active" into a collection in rules configuration.
I searched in internet and also I tried rules bonus pack but the didn't help me.
Is there any way to load commerce products into a collection and iterate collection via loop ?
Answer: I found that VBO (Views bulk operation) give me ability to load views result into a collection in rules.
Just install VBO and make a view and use it.
Comment: Good answer. Just make sure your rules are components and you're off to the races!
Comment: can you explain it how yo do that??
Comment: Yes, At first I created a view that collects commerce products (in field you must add vbo field). then in rules, you see load view result into a list. finally I made a loop to iterate each item in list. It is working perfect.


Re-define lilypond's `format-mark-box-alphabet`

Question: Say I wanted to re-define the format-mark-box-alphabet using a custom scm command.
How can this be done?
Here is a MWE where I would want both marks to be identical, with the double outline.
\version "2.24.1"

% Custom definition of the marker command
#(define-markup-command (format-mark-box-alphabet layout props text) (markup?)
  "Draw a double box around text."
  (interpret-markup layout props
    (markup #:override '(box-padding . 0.4) #:box
            #:override '(box-padding . 0.6) #:box text)))

\score {
  \new Staff {
    \set Score.rehearsalMarkFormatter = #format-mark-box-alphabet
    a2 a4 b
    \mark \default
    c'1 c'
    \mark \markup \format-mark-box-alphabet A
    a
    c'
  }
}

Current output:

Desired output:
Answer: I think this is an XY question. Redefining a built-in procedure is called monkey-patching, and it is not advised, neither in LilyPond nor in most programming languages that allow it. Instead, you want to define your own rehearsal mark formatter format-mark-double-box-alphabet, which can be done like so (I've also used \etc for the markup command):
\version "2.24.1"

\markup double-box =
\markup \override #'(box-padding . 0.4) \box \override #'(box-padding . 0.6) \box \etc

#(define (format-mark-double-box-alphabet number context)
   #{ \markup \double-box #(format-mark-alphabet number context) #})

\score {
  \new Staff {
    \set Score.rehearsalMarkFormatter = #format-mark-double-box-alphabet
    a2 a4 b
    \mark \default
    c'1 c'
    \mark \default
    a
    c'
  }
}

Namely, the mark formatter is a Scheme procedure that takes a mark number and a context, and returns a markup. In this case, it's enough to use the built-in format-mark-alphabet procedure to get a letter from the number, then double-box it.
Comment: Why not just include the rehearsalMarkFormatter setting in the stylesheet? Do you really want to use that stylesheet with several scores, some which have format-mark-box-alphabet and some of which do not, and only double the boxes of those marks that are already boxed?
Comment: I have done as you suggest, going with a new function name for the modified box-alphabet formatter. The reason why I wanted to modify `#format-mark-box-alphabet` in the first place is that I was working on a stylesheet which, among other things, swaps out the music font. So I would have liked to have the stylesheet also ajust the styling of the box-formatter for it to match the overall style. I am accepting that this is not possible and that changing the style will require not only including the stylesheet, but also adjusting the box-formatter function call.
Comment: You are right, I will include the rehearsalMarkFormatter in the stylesheet.
Answer: I fully support Jeans answer, but I want to fill in some details about why your version does not work. The reason is not that you are trying to redefine built-in procedures (which you can totally do, but usually would be a bad idea because in later code it becomes hard to understand if we are using the internal procedure or a modified one).
The reason for this is that you define your procedure only as markup command. Now, markup commands are a bit special in Lilypond, as they are defined in a separate scope (also they works slightly differently in when they are actually evaluated). So when you do
#(define-markup-command (test layout props) ()
   empty-stencil)

#(display test)

you will actually get an error, as guile won't find the binding for test. In your case this means that while you define a markup command format-mark-box-alphabet, but this does not change the binding for format-mark-box-alphabet, so you are still using the old functions. Needless to say, if it actually tried to use the markup function it would encounter some issues, as Score.rehearsalMarkFormatter is not expecting a markup command, but a function with a different interface, as shown in Jean's answer.


Remove multiple file extensions with .htaccess

Question: I have a subdomain acting as an entirely new website (subdomain.domain.com = subdomain.com). I mainly use .html files but want to get rid of those extensions (instead of http://subdomain.com/file.html, I want http://subdomain.com/file ). I've used the .htaccess code below to accomplish this.
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,QSA]

The only problem is, I also need to get rid of the .php extension of other files on the website. Most people say to duplicate the above code with .php replacing .html. I've done that; doesn't work. I've tried many other versions of the code, and still doesn't work.
Since I'm no expert at all with .htaccess, can anyone please explain how to remove both .html and .php file extensions?
Thanks in advance.
I don't believe this is a duplicate question since I haven't seen anyone else ask how to replace multiple file extensions at once.
Answer: You can use rewrite rules like this:
Options +FollowSymLinks
RewriteEngine on

# for adding .html extension if matching file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ /$1.html [L]

# for adding .php extension if matching file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

Comment: After trying a multitude of example code and suggestions from here and around the web, yours was the first/only one to work! Thank you. Both php and html files now work without extensions in the URL.
Comment: Thanks for answering; it throws a 404 though
Comment: The file is in the main domain folder(not the subdomain). And your code throws the 404 regardless of what other rules are there - I deleted them all and tried it...
Comment: Also make it `RewriteRule ^(.+?)/?$ $1.html [L]` (or see updates)
Comment: Whatever you did to the html block works. I made those changes to the php block and it works. But they don't both work at the same time - either the html extension or the php extension is removed depending on what code block is on the bottom (I think?)
Comment: yeah they're both 404
Comment: /home2/evolutl8/public_html/theism
Comment: No, it is in /home2/evolutl8/public_html. Should I put it in /home2/evolutl8/public_html/theism?
Comment: Yes it should be placed in `/home2/evolutl8/public_html/theism` and let me rollback to original answer.
Answer: To remove multiple file extensions, you can use the following rule in /root/.htaccess .
RewriteEngine on

RewriteBase /
#terminate all rewrite loops
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
#1)Remove ".html" , ".php",".css" extension.
#The following rule redirects "/file.ext" to "/file"
RewriteRule ^(.+)\.(html|php|css)$ $1 [L,R,NE]
#checks if "/file" .html exists, if it exits ,map "/file" to "/file.html"
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*?)/?$ $1.html [L]
#checks if "/file" .php exists, if it exits ,map "/file" to "/file.php"
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
#checks if "/file" .css exists, if it exits ,map "/file" to "/file.css"
RewriteCond %{REQUEST_FILENAME}.css -f
RewriteRule ^(.*?)/?$ $1.css [L]

The rules above remove .php ,.html and .css extension. To remove more extensions you can edit this .htaccess as per your need.


Identifying joint/conditional probability from question

Question: I am trying to solve a basic probability question. This problem is an example of the law of total probability. Here is the problem with its solution.

I interpreted the first line of the question as $P(C \cap M) = 0.07$ and $P(C \cap F) = 0.004$.
But from the solution, it appears the first line meant conditional probability, not a joint probability.
My question is, how am I supposed to understand that the statement meant conditional and not joint probability? Also, is the question poorly written?
Comment: I think it's written clearly. What do you think it was conditioned on?
Answer: The sentence "7% of men ... are colorblind." means "Among men, 7% are colorblind." or in symbols, $P(C|M) = 0.07.$ By contrast, $P(M\cap C) = 3.43\%$ ought to go into English as "In the US population 3.43% are colorblind men."
However, too many imprecise and/or innumerate writers are not careful to distinguish between $|$ and $\cap.$ For example, in accounts of medical screening tests the terminology "false positive" has come to be used about equally often as either "Positive test and not infected: in the population" or "Positive test among those not infected", conflating probabilities $P(+\cap D^c)$ and $P(+|D^c).$
It has come to the point that "false positive" has become either meaningless, or a puzzle to be solved before reading further. In my own writing, I have decided to use "false positive" and "false negative" only
if accompanied by a correct mathematical expression in the same immediate field of view.
Note: For a long time, Wikipedia had a lengthy, excellent, and technically meticulous article on screening tests; but it got replaced by a more popularized, and less precise, article. In sequence, various
different pages have followed under the same header. (I have not checked the current
version before writing this.)
Comment: I think it could be even worse, with false positive also perhaps being used to mean $P(D^c\vert +)$. (The $^c$ denotes the complement of people who have the disease, so people who don't have the disease.)
Comment: Of course you can interpret "colorblind man" anyway you like, but in English "a person who is colorblind and male" seems very awkward and one would think it strange. Phrases such as "beautiful actress" and "chocolate ice cream" are readily understood as indicating intersections of characteristics. Conditioning is not so frequent, but are easily handled: "of the women I know, she's one of the few psychologists" or "German shepherds are an especially loyal breed of dog."
Comment: @BruceET When said "colorblind man" - I am interpreting it as men that are colorblind which is conditional distribution. This is very confusing. I am going to assume if the sentence contains `and` then it's joint distribution otherwise it's conditional.
Comment: I see - I guess I will need more practice. Thank you!


Check if last character of a string is a letter

Question: How can I check if the last character of value is any letter without comparing it manually with each letter?
   if(value.endsWith("A",Qt::CaseInsensitive)==true)
   ...

This is my code so far, Value has to start with Y/X/Z and have 9 characters
 void Extranjero::setNIE(const QString &value)
{

    if(value.startsWith("Y",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }
    else if(value.startsWith("X",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }
    else if(value.startsWith("Z",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }

    else NIE = "Problemon";
}

Comment: why not using `std::isalpha`?
Comment: Does this answer your question? https://stackoverflow.com/questions/8611815/determine-if-char-is-a-num-or-letter it asks for both letters and digits, but the answers should be adjustable easily
Comment: Thanks! I didn't know about the isalpha() function
Comment: The classic is `if ((c >= 'A') && (c <= 'Z'))`. That covers only uppercase though.
Comment: @DavidSchwartz -- it may be "classic", but it's wrong. For example, it won't work when the character encoding is EBCDIC.
Comment: I believe this is much better duplicate candidate since it actually works for QString: https://stackoverflow.com/questions/10231746/how-can-i-find-out-if-a-specific-character-in-a-qstring-is-a-letter-or-punctuati
Answer: You can use back() and begin() member functions.
if(value.length() == 9){
  QChar tmpChar = value.back();
  if( tmpChar == 'Z' || tmpChar == 'Y' || tmpChar == 'Z'){
   // code..
  }
}

Comment: OP: "... without comparing it manually with each letter?"
Answer: If you want your string to end with any alphabetic character, then you can easily use isalpha.
However, in the other case when you want it to start with specific characters like 'X', 'Y' or 'Z', then you need to manually specify them.
In order to generalize your code for the latter case, I recommend inserting your specific characters in a set and just check if this set contains the first character of the given string.
I hope this helps you solve your problem.
Comment: Thanks! I didn't know about isalpha() function, now I only need to split my string into a char array to check it.
Comment: @Yassin Note that `isalpha` is only suited for regular ascii `char`s. QChar has a [isLetter](https://doc.qt.io/qt-5/qchar.html#isLetter) function that is much better suited. Unless you only need to check against [a-zA-Z].
Comment: @Yassin If my answer helps you, kindly accept it.


Sibelius allow to play along like synthesia?

Question: I am looking for a software that you can play along a score and it can wait for you to enter notes like synthesia does. The problem with synthesia is that it's not really focused on the score and more on the notes falling.
Can Sibelius do that? Or some other score software?
Comment: You are looking for a software that plays an accompaniment and automatically adapts its tempo to you playing a solo instrument?
Answer: Sibelius sounds like exactly what you're after. I had to use it for my A Level music and it was an extremely good program (although I would recommend using the real sounds, not the MIDI sounds if you can afford it). I'd also recommend using Guitar Pro 5 or 6 for score and notation, however I'd say Sibelius is geared more towards a proper score, whereas Guitar Pro is geared more towards guitar tab, however it is just as capable. Try a demo of both and see what you like best!
Comment: But does it allows play along? Can you play over it and have it wait for you to play the notes as you play? Like synthesia does?
Comment: @Maralc I never used it for that exact purpose, but I'm pretty certain there is that function in Sibelius at least. I'm sure you can download a demo to see or browse through their site to see if it gives that functionality.


[user-name]@git.drupal.org: Permission denied (publickey)

Question: I am trying to use git.drupal.org without success...

I have uploaded my public key in the SSH keystab under my profile
I have checked that the fingerprint on Drupal match my fingerprint in
.ssh/id_rsa
I have Filled in the Git access tab under my profile=> I got a username and I accepted the agreement

But when I run: GIT_SSH_COMMAND="ssh -vvv -p 22 -i /home/myname/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" git clone firstname.lastname@example.com:project/a_project.git
I got the following error: email@example.com: Permission denied (publickey).
Here is the output: (to anonymize the following, I replaced my Git user name by "my_user_name" and my computer User name by "myname")
OpenSSH_7.9p1 Ubuntu-10, OpenSSL 1.1.1b  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "git.drupal.org" port 22
debug2: ssh_connect_direct
debug1: Connecting to git.drupal.org [126.96.36.199] port 22.
debug1: Connection established.
debug1: identity file /home/myname/.ssh/id_rsa type 0
debug1: identity file /home/myname/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9p1 Ubuntu-10
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u6
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u6 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to git.drupal.org:22 as 'my_user_name'
debug3: hostkeys_foreach: reading file "/dev/null"
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,email@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,email@example.com
debug2: ciphers stoc: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,email@example.com
debug2: MACs ctos: email@example.com,email@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,email@example.com,zlib
debug2: compression stoc: none,email@example.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,email@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,firstname.lastname@example.com
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,email@example.com
debug2: MACs ctos: firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,email@example.com
debug2: compression stoc: none,firstname.lastname@example.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: email@example.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: firstname.lastname@example.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:FeJiekFTTnXWc1GDUfFVcRckyZkZfdmks1dSqtS6OVg
debug3: hostkeys_foreach: reading file "/dev/null"
debug3: hostkeys_foreach: reading file "/dev/null"
Warning: Permanently added 'git.drupal.org,188.8.131.52' (ECDSA) to the list of known hosts.
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Skipping ssh-dss key myname@mycomputer - not in PubkeyAcceptedKeyTypes
debug1: Will attempt key: /home/myname/.ssh/id_rsa RSA SHA256:J9ZRdKhvB9rfq/uchczwpi2CyvOqzktf9q+12AIetxE explicit agent
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/myname/.ssh/id_rsa RSA SHA256:J9ZRdKhvB9rfq/uchczwpi2CyvOqzktf9q+12AIetxE explicit agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
firstname.lastname@example.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Any hint?
`
Answer: Cloning a project as maintainer of that project is done using the following command.
git clone firstname.lastname@example.com:project/a_project.git

The username is always git.
As non-maintainer, the command to clone the project is the following.
git clone https://git.drupalcode.org/project/a_project.git

When I want to clone one of the projects hosted on drupal.org for which I am maintainer, I use the following command.
git clone drupal:project/a_project.git

In the .ssh/config file, I added the following lines.
Host drupal
   HostName git.drupal.org
   User git
   IdentityFile ~/.ssh/id_ed25519_drupal

In this way, the Git command is using the correct identity file, even if I have multiple identity files (for example, one for GitHub and one for Gitlab).
The Git command I reported to clone a project, as maintainer or not, is what the Version control tab of every project (for example https://www.drupal.org/project/drupal/git-instructions for Drupal, where you won't see the instructions for maintainers, if you aren't one of them).
What reported in Generating SSH keys (Linux) is outdated. Git Authentication for Drupal.org Projects has the most updated information. In particular, under Changing Git Remotes, it says:

If you are a maintainer who has an established Git remote in the format <username>@git.drupal.org:project/<yourproject>.git, the format should be changed to email@example.com:project/<yourproject>.git.
Comment: @kiamlaluno is correct and is telling you the current way to access git repositories on git.drupalcode.org. The documentation page at  drupal.org/node/1066928 is very outdated - the method it describes was changed about 9 months ago and is no longer correct.
Comment: Thank you, there are useful information in your answer. I was knowing the fact that we could use "git" as user name, but my goal was to use my user name as explained in: https://www.drupal.org/node/1066928 (under Test your Key) : `git clone [git-username]@git.drupal.org:project/examples.git` If you confirm that I must not use my user-name to clone, I will validate your answer.
Comment: Yes, that page needs to be updated. There must be a page reporting the changes in authenticating on the Drupal.org Git server.


Identifying method by equation (Related to Factorial Fractional Design)

Question: I'd like to know the name of the method in the picture below. It's the same category as full - and factorial fractional design. It's quite difficult to search the net for this equation - I've tried wolfram etc but to no avail. If I remember correctly it's a response design of some kind(?) but I might be wrong.

Thanks for your help. I've read up on central composite design but I'm not sure if I understand it completely.
So I've my variables x1,x2,x3 represented as a cube and I add the center point to see if the variables are linear - what if they are not? Then I add the star points from the center point to see what variable affect the response the most. Is this an accurate description of the essence of the methodology or have I misunderstood/missed something?
Is the number of "experiments" or runs I need to do >= 9? Because 2³ (yellow dots) + 1 center point are 9 runs? I'm trying to compare central composite design with full fractional design (2³=8 runs) and fractional factorial design (with 1/2 fraction: 4 runs).
Answer: It's a central composite design.  You start with the yellow runs to be able to do screening on the effects.  You usually add several of the blue points so that you can estimate variance in terms of pure error, and also test for lack of fit.  When lack of fit is detected you can follow up with the red axial runs to fit a quadratic model as your response surface and use that for process optimization or what have you.
Comment: Apologies for off-topic ping: there is a suggestion on Meta to make [randomized-experiment] a synonym of [random-allocation] tag (http://stats.meta.stackexchange.com/a/4651). You have enough reputation in this tag in order to vote for this suggestion here: http://stats.stackexchange.com/tags/random-allocation/synonyms - it now needs 4 upvotes to go through. If you disagree with the proposal, consider commenting on Meta to explain why. I will delete this comment soon. Cheers.
Answer: You are close: try response surface methodology/regression. A similar pic is the second cover slide here, and provides a reference for the method. The equation is a second order polynomial, which would be a more general term to search for, should the former prove insufficient.


Understanding the roles of different types of offensive lineman in American football

Question: When New York Giants drafted Justin Pugh this year, the ESPN announcers said they picture him as a guard because his arms are short. Football announcers rarely give technical details and tend to over-simplify things as they speak.

What do teams look for to determine whether someone is best as a
tackle, guard, or center?
How hard is it for a quality offensive lineman to switch between
these?
Is there any difference between a left side player and a right side
player other than that one tends to protect the quarterbacks blind
side so you probably want your best tackle on that side?
Comment: Welcome to Sports.SE! Just to note, you have three valid and interesting question there. On StackExchange sites it's preferred to keep one question per thread, so next time you might want to have separate questions instead of bulking them into one question ;)
Comment: Tackles tend to be the quickest players on the OL, reason being is that they go up against Defensive ends, and often Outside line backers that are very quick (think Clay Matthews Jr., Terrell Suggs). To deal with that style they either they are quick, long-armed or better yet, both. Centers would ideally be smart, as goofy as that may sound. They make line adjustments, and have to manage a lot of things that other lineman don't really have to worry about. While right tackles are no less pertinent to a successful OL, the left tackle is generally the most sought after for a star.
Answer: Tackles, and in particular left tackles, tend to be the elite positions on the offensive line. The position requires linemen to generally have the best size (height, arm reach) and athletic ability (agility, technique) in order to deal with one on one pass rushers. Left tackle in particular is crucial as this lineman protects the blindside of a right-handed QB.
Guards tend to be smaller than tackles, though at the pro level this is largely because these players simply did not have the measurables to project as a tackle. Unlike tackles, guards will be more likely to work in double-team assignments, such as with the center against a nose tackle. Guards are also asked to 'pull' in running and rollout plays which requires the linemen to turn and move quickly down the line of scrimmage in order to deliver a crucial block to create or seal a running lane.
Centers tend to be as small as guards, though they're best thought of as specialists. Where as tackles have a physical skillset that distinguishes them from guards, centers have a tactical responsibility that makes them unique. They call out blocking assignments at the line of scrimmage and are responsible for the snap. It's a unique skillset that makes it hard to simply slot any lineman at the position. Centers usually take longer to develop and adjust to the pro game as they adapt to the many confusing defensive looks and blitzes used at the higher level.
In the NFL, left tackles are generally the highest earning lineman. They're considered franchise players as even an elite QB cannot pass effectively without an above average tackle holding down elite pass rushers. Centers can make more than guards, but the pay difference in recent years has really just come down to the player's fit with the team. A center for an elite passing team is likely to make as much as a guard for a strong inside running team.
Answer: A center needs to have the firmest hands because he is the one "hiking" the ball to the quarterback.
Together with a center, the guards are the ones protecting the quarterback at the beginning of the play, so they tend to be bigger and slower, than say, the tackles.
The tackles typically "do their thing" AFTER the play gets under way, so they need to be quicker and more versatile than the centers. If for instance, a halfback wants to go to the "outside," the tackles need to block defenders "inside." If a fullback wants to run a "draw play" (inside), the tackles need to push defenders outside.


Pandas drops timestamp columns in resample

Question: I have a DataFrame which has two Timestamp columns, one of which gets used as an index for resampling, the other remains as a column. If I resample the DataFrame, the one remaining as a column gets dropped. I would like it to be resampled as if it were a numeric column (which it is really):
import numpy as np
import pandas as pd
init_time=pd.date_range(start='2010-01-01 00:00', end='2010-01-05 00:00', freq='12H')
valid_time=pd.date_range(start='2010-01-01 00:00', end='2010-01-05 00:00', freq='12H')
data = np.random.random(len(valid_time))
frame = pd.DataFrame(index=valid_time, data=data)
frame['init_time'] = init_time

DataFrame has an index, 1 numeric column, and one Timestamp column
                     0          init_time
2010-01-01 00:00:00  0.869667   2010-01-01 00:00:00
2010-01-01 12:00:00  0.225805   2010-01-01 12:00:00
2010-01-02 00:00:00  0.348080   2010-01-02 00:00:00
2010-01-02 12:00:00  0.761399   2010-01-02 12:00:00
2010-01-03 00:00:00  0.645069   2010-01-03 00:00:00
2010-01-03 12:00:00  0.133111   2010-01-03 12:00:00
2010-01-04 00:00:00  0.314302   2010-01-04 00:00:00
2010-01-04 12:00:00  0.130491   2010-01-04 12:00:00
2010-01-05 00:00:00  0.621703   2010-01-05 00:00:00

Now resample to daily:
daily = frame.resample('D', how='mean')

             0
2010-01-01   0.547736
2010-01-02   0.554740
2010-01-03   0.389090
2010-01-04   0.222396
2010-01-05   0.621703

My init_time column has been dropped. I could convert it to a raw integer column first, but is there an easier way?
Answer: This is not implemented for datelike (mean), but you can do it this way:
Get the numeric results
In [48]: numeric = frame.resample('D',how='mean')

Get the datelike results. First get the columns which are datelike
In [49]: datelike = frame.loc[:,frame.dtypes.isin([np.dtype('datetime64[ns]')])]

Then resample them; you need to view them as integers to compute on them; Timestamp will handle this float input (and essentially round to the nearest nanosecond)
In [50]: datelike = datelike.resample('D',
         how=lambda x: Timestamp(x.view('i8').mean()))

Put them back together
In [51]: concat([numeric,datelike],axis=1)
Out[51]:
                   0           init_time
2010-01-01  0.798880 2010-01-01 06:00:00
2010-01-02  0.859781 2010-01-02 06:00:00
2010-01-03  0.515503 2010-01-03 06:00:00
2010-01-04  0.505557 2010-01-04 06:00:00
2010-01-05  0.979835 2010-01-05 00:00:00

[5 rows x 2 columns]

Comment: Thanks, that's essentially the workaround I'm using. I wonder if there is any appetite for optionally specifying a resampling function per column in Pandas?
Comment: you could do it via a groupby with TimeGrouper as well. I suppose you could have a signature like: ``df.resamplee(freq....how={ columns : func.....}, how_default = default_function )`` to have per-column overrides and a default. Pls file an issue on github for this. (and a PR would be even better!)
Comment: OK, will try. Could be my first PR.
Comment: Did you ever submit an issue for this? As a novice pandas user, I wasted quite a bit of time before I discovered that ``DataFrame.resample`` was silently dropping my timedelta64 type column. I am glad I found this Q&A here, which gave me a clue what to look for.


Is it correct that $-\lfloor0.5\rfloor \ne \lfloor(-0.5)\rfloor$?

Question: As I understand floor functions:
$\lfloor (-0.5)\rfloor = -1$
while
$-\lfloor(0.5)\rfloor = -0 = 0$
Am I understanding floor functions correctly?
Comment: Yes, $\lfloor -0.5 \rfloor = -1$ and $-\lfloor 0.5\rfloor = 0$. In general $\lfloor x \rfloor + \lfloor -x \rfloor = \begin{cases} 0 & x \text{ is integer }\\ -1, & \text{ otherwise}\end{cases}$.
Comment: @TheGreatDuck At the time of posting the question wasn't answered. Now I would obviously not persuade the OP to edit their question
Comment: Yes, your understanding is correct. The maximum integer below $-0.5$ is $-1$, and the maximum integer below $0.5$ is 0, so $- \lfloor 0.5 \rfloor = 0$
Comment: Thanks.  I was trying to figure out a mistake in a formula that I was using and this was it.  Very surprising.
Comment: You should definitely post the formula in this question - maybe someone on Math SE will be able to figure out where you have made a mistake.
Comment: The formula is [here](https://mathoverflow.net/q/271808/15915).   I had been told that the mistake was in my inequality but I couldn't see how this was so despite the counter example provided.
Comment: @TheGreatDuck Thanks for the advice
Answer: Yes, you are correct. Wikipedia and Mathworld agree (you can look at the graphs there). Be careful, though: There's a small chance that some programming language will have floor defined incorrectly for negative inputs.
Answer: In general. For positive non integer $x $, If $0 < n < x <n+1$ then $-n-1 <x <-n $.
So....
$[x]=n $ while $[-x]=-n-1=-[x]-1$
But if $x $ is an integer then $[x]=[n]=n=$ and $[-x]=[-n]=-n=-x $.
It seems a little weird but it all makes sense.


Exibir form de acordo com resposta do user

Question: Preciso de uma ajudinha.
Tenho um Grid, com uma coluna denominada status de interesse, o tipo dessa coluna é ComboBox.
No entanto, quando o user selecionar a opção declinado quero exibir um form x.
Como faço?
Acho que o evento é o Leave, mas sobre as condições, como verificarei se o usuário selecionou em tal celula a opção tal?
Aqui tem um exemplo de como está o form.
Comment: Inclua o seu código à pergunta
Comment: Exibir form no evento onclose? sim, é leave.
Form1.show ou hide Não vi a IMG então não sei exatamente como é mas pode ser usado tanto um If elseif como loop ou até um case
Comment: Obrigada. Minha dúvida maior é como será feita a verificação do conteúdo da célula para assim exibir o form. Você tem alguma ideia de como realizar?
Comment: Caso precise de uma checagem antes de exibir a form, faça um If em onclick do grid, assim cada clique no componente será verificado e exibida a form
Answer: Boa tarde @Autoit, a forma de você pegar o campo é assim:
grdObjetivo.Rows(e.RowIndex).Cells(2).Value.ToString()


Retornar registros categorias/subcategorias PHP

Question: Tenho a seguinte estrutura de tabelas e registros:
CREATE TABLE IF NOT EXISTS `produto` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_categoria` text,
  `titulo` text,
  `referencia` text,
  `valor` decimal(10,0) DEFAULT NULL,
  `imagem_principal` text,
  `descricao` text,
  `data` text,
  `status` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;

INSERT INTO `produto` (`id`, `id_categoria`, `titulo`, `referencia`, `valor`, `imagem_principal`, `descricao`, `data`, `status`) VALUES
(1, '5', '4Y1A7316-S169', '4Y1A7316-S169', '0', 'd6663aa43c2c044e90375d312b601599.png', '
Pincel para Cílios
', '2019-04-17 18:02:24', 0),
(2, '5', '5Y1A7316-S621', '5Y1A7316-S621', '0', '7f699d3c34fd63b8810b1a457404c317.png', '
5Y1A7316-S621

', '2019-04-22 17:47:24', 0);

CREATE TABLE IF NOT EXISTS `produto_categoria` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_categoria` text,
  `titulo` text,
  `ordem` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=13 ;

INSERT INTO `produto_categoria` (`id`, `id_categoria`, `titulo`, `ordem`) VALUES
(1, '0', 'Cílios', '0'),
(2, '0', 'Pentes', '2'),
(3, '0', 'Toucas', '4'),
(4, '1', 'Fio a Fio', '0'),
(5, '1', '3D', '1'),
(6, '0', 'Pinças', '0'),
(7, '0', 'Pincéis', '0'),
(8, '0', 'Tesouras', '0'),
(9, '0', 'Unhas', '0'),
(10, '0', 'Esponjas', '0'),
(11, '0', 'Espátula', '0'),
(12, '0', 'Alicates', '0');

Note que eu tenho dois registros na tabela produto, com id_categoria 5. Subcategoria que pertence a categoria cílios (1).
Preciso elaborar um SQL onde eu consiga trazer os registros, independentemente da subcategeoria.
Neste caso, preciso que o resultado retorne os dois produtos, quando eu selecionar categoria 1.
Meu SQL Atual segue abaixo:
SELECT * FROM `produto`
LEFT JOIN `produto_categoria` ON `produto_categoria`.`id`=`produto`.`id_categoria`
WHERE `produto_categoria`.`id` = '1'`

Dessa forma, eu buscaria somente os produtos da categoria = 1, mas existem variáveis dentro dessa categoria, como eu consigo retornar?
Criei no SQL FILDDLE: http://www.sqlfiddle.com/#!9/916cba/1
Comment: Na regra do seu sistema, os produtos podem ter um `id_categoria` que não é uma subcategoria? Ex: id_categoria = 1
Comment: Sim, isso mesmo.
Answer: A query abaixo retorna os produtos que sejam da categoria 1 ou cujos produtos sejam de uma categoria filha(1 nível) da categoria 1.
SELECT *
FROM produto p
left JOIN produto_categoria cat
ON cat.id = p.id_categoria or cat.id_categoria = p.id_categoria;


Is this a complex function?

Question: $f(\theta)=\cos(\theta)+i\sin(\theta)$, where $i^2=-1$ and $\theta \in [0,2\pi]$.
Is this function considered to be a complex function? If I want to differentiate it, should I verify the Cauchy-Riemann equations?
Thanks!
Answer: This is a complex valued function of a real variable. It makes no sense to ask about the Cauchy-Riemann equations.
It is differentiable. Just go ahead and differentiate.
Geometrically, it wraps its domain around the unit circle in the complex plane. The derivative will be perpendicular to the value.
Answer: The domain is not an open subset of $\mathbb C$, and therefore the answer is negative.
It is differentiable because $\cos$ and $\sin$ are diffeentiable and $i$ is a constant. So, buy the usual rules of differentiation,$$f'(\theta)=-\sin(\theta)+i\cos(\theta)=i\bigl(\cos(\theta)+i\sin(\theta)\bigr).$$
Answer: According to Wikipedia

A complex function is a function from complex numbers to complex numbers.

However, Wolfram says

A function whose range is in the complex numbers is said to be a complex function, or a complex-valued function.

So there is some ambiguity as to what the term "complex function" means. The domain of your function is the real numbers, while the range is the complex numbers. Thus, is you want be precise, you can call it a complex-valued function on the real numbers.
The Cauchy-Riemann equations apply to the meaning given by Wikipedia, that is, a complex-valued function on the complex numbers. So arguably they do not apply to the function you give. But there is an obvious extension to the domain of the real numbers. We can take $z = x+iy$ and $f(z) = u+iv$, and then $f(x+iy) = \cos(x) + i\sin(x)$, giving us $u_y = v_y=0$, which clearly leads to the CR equations not being satisfied. So $f$ is not differentiable with respect to $z$, but it is differentiable with respect to $x$: $\frac {df}{dx} = -\sin(x)+i \cos(x)$ (if we're taking this to be a function on the real numbers, this is a full derivative, but if we're taking it to be a function on the complex numbers, this should be a partial derivative).
Comment: The Wolfram definition seems a bit weird to me. I'm not sure I'd call a function a "complex function" if it had something other to $\mathbb{C}$ as a domain (e.g. the set of functions or matrices). I think most of the time it's $f:\mathbb{C}\mapsto\mathbb{C}$, as in the Wiki definition. But I guess it's not really important anyway.
Comment: @Jam Adjectives are often used to describe the range of a function, e.g. "negative function". Referring to a complex-valued function as "complex" is in keeping with this usage.

Is this a complex function?


Prove that there exists an infinite subsequence in geometric progression given a strictly increasing sequence of integers in an arithmetic progression

Question: Let $\{a_1,a_2,\cdots{}\}$ be a strictly increasing sequence of positive integers in arithmetic progression . Prove that there exists an infinite subsequence of the given sequence whose terms are in geometric progression.
I started by letting $a_1=a,a_2=a+d,\cdots{}$. Im not sure how to continue from here. Any hints or solutions would be helpful.
Comment: The question seems to suggest that the numbers are in arithmetic progression. But it is an important detail that must be clearly mentioned
Comment: @Crostul: Fixed! Its in AP
Answer: Consider the subsequence
$$a,a(d+1),a(d+1)^2,a(d+1)^3,\cdots$$
As the sequence is strictly increasing, $d\gt0$, and $(d+1)\gt1$. Hence, the above sequence is strictly increasing. On expanding, we get,
$$a,a+ad,a+d(a(d+2)),a+d(a(d^2+3d+3),\cdots,a+ad\frac{((d+1)^{k-1}-1)}{d},\cdots$$
As the original sequence consists of positive integers, each of the above element is guaranteed to be an integer and to be an element of the original sequence.
Hence, let the subsequence be $a_{n_k}$ where
$$a_{n_k}=a+a{((d+1)^{k-1}-1)}$$
where $k\in\mathbb N$.
In other words, the $k^{th}$ element in the subsequence is the $r^{th}$ element of the original sequence where
$$r=\frac{a((d+1)^{k-1}-1)}{d}+1$$


Git checkout without committing user interface state file in Xcode project?

Question: I clone branch from bitbucket and make anew branch from it.
When I want to use checkout command to move from created-branch to the master-branch or from master-branch to created-branch when there is no editing -There is no need to commit-, It ask me to commit file UserInterfaceState.
I search about this problem and I found that i need to remove file or add it to git ignore, and I found this command:  " git rm --cached *.xcuserstate ".
The above command will remove the file. and I can make checkout to another branch.
But the problem is I need to do the above git command every time I need to checkout from one branch to another.
Is there any approach that let me avoid do it every time?
In addition I followed this site to add built in files to .gitignore file but nothing change "Xcode ask me again to commit the file 'UserInterfaceState'".
Is there any solution?
Comment: Unfortunately you will have to perform that command on every branch you have the file already tracked, **and then commit that removal**.
Comment: No, .gitignore stops `git add .` and similar from adding your files but if the file has already been added and is thus tracked, git will track changes to it and not use `.gitignore` for that file.
Comment: Is there anyway to add it to .gitignore file?
If it added to the file gitignore i think i dont need to recomit it when it will change.
Answer: When .gitignore file is not working (adding something into .gitignore file or removing something from .gitignore file), you can inspect the following pointers:

Check for the global gitignore file which sometimes may influence your gitignore.
Even if you haven't tracked the files so far, git seems to be able to "know" about them even after you add them to .gitignore. Run below command from root of your git repo.
git rm -r --cached .
git add .
git commit -m "fixed untracked files"


Finding the mean of $W(s)|W(t)$, I denote as: $E(W(s)|W(t))$where $W$ is the standard Wiener process. $0<s<t$

Question: I have figured out that the density function for $(W(s), W(t))$ is:
$$g_{s,t}(x_1,x_2)=\frac{1}{2 \pi \sqrt{s(t-s)}}e^{-\frac{x_1^2}{2s}-\frac{(x_2-x_1)^2}{2(t-s)}}$$
Also, the density function of $W(t)$ is:
$$g_t(x_2)=\frac{1}{\sqrt{2\pi t}}e^{-\frac{x_2^2}{2t}}$$
My thoughts are that:
$$g_{s|t} =\frac{g_{s,t}(x_1,x_2)}{g_t(x_2)}$$
Now the problem is, I do not know how to set up the integral for the mean,or if $g_{s|t}$ is a function of $(x_1,x_2)$ or just of $x_1$. I am getting back to Stochastics, after a long time. Greatly appreciate input on finding this mean.
Comment: They are not independent. The increments of BM are independent.
Comment: Why don't you try to deduce it from the properties of Brownian motion?
Comment: $W(s)$ and $W(t)$ are independent, therefore $E(W(s)|W(t)) = E(W(s))?$
Answer: Letting $B(t)=tW({1/t})$ for $t>0$ and $ B_0=0$, then it is standard result that $B(t)$ is also a standard Weiner process. Therefore,
$$
E[W(s)|W(t)]=E[s B({1/s})|tB({1/t})]=s\cdot E[ B({1/s})|B({1/t})]\stackrel{\frac1s>\frac1t}=sB({1/t})=\frac{s}t W(t).
$$


Variance of Mean Response at the Mean of the Data

Question: My question concerns the variance of the mean response as outlined
in this short article or in this Wikipedia entry.
Basically, the variance of the mean response is given by
$$\text{Var} \left(\hat{\alpha} + \hat{\beta} x_0\right)= \sigma^2 \left(\frac{1}{n} + \frac{(x_0 - \bar{x})^2}{\sum(x_i-\bar{x})^2}\right),$$
where $x_0$ is the data point at which the mean response is predicted.
What I am interested in, however, is a slight modification of this. I would like to compute the variance of the mean response at the mean of the data. If I simply use $x_0 = \bar{x}$, the result is straight forward:
$$\text{Var} \left(\hat{\alpha} + \hat{\beta} \bar{x}\right)= \sigma^2 \left(\frac{1}{n} + \frac{(\bar{x} - \bar{x})^2}{\sum(x_i-\bar{x})^2}\right) = \frac{\sigma^2}{n}$$
But this is not exactly what I am interested in. According to my intuition, since $\bar{x} = \mathrm{E}[x]$ (i.e. $\bar{x}$ is estimated as well), the variance should account for the uncertainty in $\mathrm{E}[x]$. So, I am interested in
$$\text{Var} \left(\hat{\alpha} + \hat{\beta} \mathrm{E}[x]\right)$$
Using basic algebra, I arrive at:
$$\text{Var} \left(\hat{\alpha} + \hat{\beta} \mathrm{E}[x]\right) = \mathrm{E}\left[\left(\hat{\alpha} + \hat{\beta} \mathrm{E}[x]\right)^2\right] - \mathrm{E}\left[\hat{\alpha} + \hat{\beta} \mathrm{E}[x]\right]^2
$$
$$ = \mathrm{E}\left[\hat{\alpha}^2\right] - \mathrm{E}\left[\hat{\alpha}\right]^2 +2\mathrm{E}\left[\hat{\alpha}\hat{\beta}\mathrm{E}\left[x\right]\right] -2\mathrm{E}\left[\hat{\alpha}\right]\mathrm{E}\left[\hat{\beta}\right]\mathrm{E}\left[x\right] + \mathrm{E}\left[\hat{\beta}^2\mathrm{E}\left[x\right]^2\right] -\mathrm{E}\left[\hat{\beta}\right]^2\mathrm{E}\left[x\right]^2
$$
In the case where $x_0$ is not stochastic, this simplifies to variances and covariances of the parameters. $\text{Var} \left(\hat{\alpha}\right)$ is still present as the first two terms, but how do I continue simplifying the rest of the equation? Or, does anyone know the result (i.e. how to express $\text{Var} \left(\hat{\alpha} + \hat{\beta} \mathrm{E}[x]\right)$)?
Many thanks for any hint! I am happy to provide further clarification of what I mean if it is unclear.
Answer: If defined, there is no uncertainty of $E[X]$ because it is constant, and doesn't depend on data. It's defined purely by the distribution. That is also why $\bar{x}\neq E[X]$, which contradicts your intuition. Sample mean is calculated from data points. So, since you can treat $E[X]$ as if it is another $x_0$, just substitute into your first equation to obtain the variance of the mean response at that point.
Edit regarding your comment:
When $\bar{X}$ is stochastic (i.e. $X_i$ are stochastic), what we have is actually $\operatorname{var}(\hat{\alpha}+\hat{\beta}\bar{X}|\bar{X})$, i.e. $\bar{X}$ is known. We'll use Law of Total Variance to find unconditional variance. Note also that $\hat{\alpha},\hat{\beta}$ are unbiased estimators of the true coefficients.
 $$E[\hat{\alpha}+\hat{\beta}\bar{X}|\bar{X}]=\alpha+\beta\bar{X}$$
Substituting into the law of TV:
$$\operatorname{var}(\hat{\alpha}+\hat{\beta}\bar{X})=\operatorname{E\left[\frac{\sigma^2}{n}\right]}+\operatorname{var}(\alpha+\beta\bar{X})=\frac{\sigma^2}{n}+\frac{\beta^2\sigma_x^2}{n}$$
where $\sigma_x^2$ is the variance of $X_i$.
Comment: Ok, so basically, it is $\frac{\sigma^2}{n}$?
Comment: No. You'll put $x_0=E[X]$ in the first equation and leave it as it is. You need to convince yourself that $\bar{x}\neq E[X]$ in general, before closing up this issue by the way.
Comment: I now see that $\mathbb{E}(x) \neq \bar{x}$, since the expectation is the true mean of the distribution, while the other is the sample mean. If I use the (estimated) sample mean (which has a variance), does this not change the variance of the mean response at all? Is it just like a constant?
Comment: Normally, sample mean has a variance as you said; but here $x_i$'s are also known  numbers. So is $\bar{x}$. If they were stochastic, they couldn't get out of the variance expression. This is also noted in the short article you provided (3rd line).
Comment: Any hint as to where I would need to look if I do not assume the $x_i$ known? Is there even a way to compute the variance of the forecast if the mean has to be estimated (and hence has a variance)?
Comment: Wow, thanks, that's it!!


Problem with Email Notifications in VisualSVN Server

Question: I have a dedicated server running windows 2003 server and Visual SVN Server 2.0.8.
I'm trying to configure it to send email notifications on commit. So I found this article on Visual SVN site.
It says I have to edit the Post-commit hook and set it to the following:
<code>"%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" ^
commit-notification "%1" -r %2 ^
--from <from-email> --to <to-email> ^
--smtp-server <smtp-server>
</code>
Of course I've replaced the variables there.
The problem is when someone commits something, the svn client throws the following error:
<code>post-commit hook failed (exit code 1) with no output.
VisualSVNServerHooks: Error resolving case of '<path-to-repository>'
</code>
The commit process runs with no problems, I mean it does commit the files. But it won't send any email notification. If I remove the post-commit hook, then I don't get the error (and of course I don't get any notification).
Manually running the VisualSVNServerHook.exe using cmd.exe with the following code works fine (sends the email).
<code>"%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" commit-notification ^
<path-to-repository> -r <some-revision_number> ^
--from <from-email> --to <to-email> ^
--smtp-server <smtp-server>
</code>
Could you help me out with it? The error doesn't tell too much =S
Thank you!
EDIT:
Ok... so I've tried replacing %1 and %2 with static values (using the actual repository path and some existing revision number), just as I tested using cmd.exe. But it didn't work.
So I went further and I replaced the entire hook with a simple call to C:\hook.bat, same error.
It seems no matter what I put on the hook, it won't work.
Comment: I had issues with it not picking up the $1 and $2 var's.. didn't resolve.. (its only for me, so wasn't too worried).. does it work if you replaced those vars with static values (I know, that defeats the purpose, but you will know WHERE the problem is then)
Comment: I've edited the hook and replaced the %1 and %2 variables with actual static values and it didn't work. Same error =(
Answer: I have had problems with case sensitivity and subversion on windows before. Could that be the problem?
I would try this:
<code> echo "%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" ^
commit-notification "%1" -r %2 ^
--from <from-email> --to <to-email> ^
--smtp-server <smtp-server> > <somepath>\text.txt
</code>
Check that the command echoed in text.txt works.
Comment:  must be a path that the visual svn server have write-acces to.
Comment: It throws "Access is denied"
Answer: This problem fixed in VisualSVN Server 2.1.3:

Fixed: VisualSVNServerHooks.exe does
  not work if VisualSVN Server service
  account doesn't have access
  permissions to all parents of the
  repositories folder.

See change log entry for VisualSVN Server 2.1.3 for more details.
Answer: Try running the VisualSVNServerHooks.exe from the command line with your parameters. It will display an error message that might help you.
I would check that you don't use fake  address and that it exists on your mail server.
Comment: I said that manually running the VisualSVNServerHooks.exe using cmd.exe works fine. Please read the whole question.