JavaScript validate schema against list of objects

Question: What is the best way to solve this problem?
Given a list of employees like with various properties.
const employees = [
 { name: 'alice',
   title: "ceo",
   salary: 100,
   reports: [{
      name: "bob",
      title: "cfo",
      salary: 10,
      reports: [{
        name: 'zorp',
        title:"controller",
        salary: 40
      }],
   }],
},
…
]

Note the "reports" property in particular. An employee can have properties that are also lists of employees.
And a schema object
const schema = {
  employee: [
    {
    name: "name",
    required: true,
    type: "string"
  },
  {
    name: "title",
    required: true,
    type: "string"
  },
  {
    name: "salary",
    required: false,
    type: "number"
  },
  {
    name: "remote",
    required: false,
    type: "boolean"
  },
  {
    name: "reports",
    required: false,
    type: "array:employee"
  },
]
}

complete the validate function (we just need to return the first case that fails)
function validate(employees,schema) {

/*
- There are multiple test cases, if the test cases all pass you should return

     { ok: true, message: "success" }

- if a required property doesn't exist on the validation, you should return

     { ok: false, message: "${name} does not exist" }

- if a property type is invalid, you should return

     { ok: false, message: "${name} property invalid ${type}" }

- if a property does not belong as part of the schema, you should return

     { ok: false, message: "property ${name} does not belong" }

*/

}

Comment: so when u go to the mechanic u go without the car? or u bring it to actually let the mechanic see what is going on? same here
Comment: so what you've tried so far?
Comment: you search something like this https://joi.dev/ ?
Comment: @ericmp i have tried a solution but with failed test cases, pasting it here might cause confusion
Answer: The problem you are experiencing is that your data is recursive and your schema is linear, ie "flat". You attempted to encode meaning into strings like "boolean" and "array:employee". This is a poor way of trying to represent your recursive structure as a schema.
If you want to build a proper schema validator, start by designing pieces for making the schemas. Use basics and work your way up -
design
// main.js

import { primitives, validate } from "./schema.js"

const [tnumber, tboolean, tstring] = primitives()

const temployee = ...

const tschema = ...

const mydata = ...

validate(tschema, mydata)

With our primitives defined, we can make more advanced types, like temployee and tschema -
// main.js

import { primitives, validate, required, optional } from "./schema.js"

const [tnumber, tboolean, tstring] = primitives()

const temployee = {
  name: required(tstring),
  title: required(tstring),
  salary: optional(tnumber),
  remote: optional(tboolean),
  get reports() { return optional(tschema) } // recursive types supported!
}

const tschema = [temployee] // array of temployee!

const mydata = ...

validate(tschema, mydata)

implement
Now we start the Schema module -

primitives - generates symbolic primitive types
required - type guards against null values
optional - type validates only if value is present

// schema.js

function *primitives() { while(true) yield Symbol() }

const required = t => v => {
  if (v == null)
    throw Error(`cannot be null`)
  validate(t, v)
}

const optional = t => v => {
  if (v != null)
    validate(t, v)
}

export { primitives, required, optional }

Next we'll write an internal helper, validatePrimitive, for validating basic types -
// schema.js (continued)

function validatePrimitive(t, v) {
  switch(t) {
    case tnumber:
      if (v?.constructor != Number)
        throw Error(`${v} is not a number`)
      break
    case tboolean:
      if (v?.constructor != Boolean)
        throw Error(`${v} is not a boolean`)
      break
    case tstring:
      if (v?.constructor != String)
        throw Error(`${v} is not a string`)
      break
    default:
      throw Error(`unsupported primitive type`)
  }
}

Finally we write the public validate interface. It's recursive because both the schemas and the data we are validating are recursive. This harmony of data and code makes it easier for us to think about the problem and write a program that solves it -
// schema.js (continued)

function validate(t, v) {
  switch (t?.constructor) {
    case Symbol:
      return validatePrimitive(t, v)
    case Array:
      if (t.length !== 1) throw Error("Array schema must specify exactly one type")
      for (const k of Object.keys(v))
        validate(t[0], v[k])
      break
    case Object:
      for (const k of Object.keys(t))
        validate(t[k], v[k])
      break
    case Function:
      t(v)
      break
    default:
      throw Error(`unsupported schema: ${t}`)
  }
}

export { ..., validate }

run it
import { primitives, required, optional, validate } from "./schema.js"

const [tnumber, tboolean, tstring] = primitives()

const temployee = {
  name: required(tstring),
  title: required(tstring),
  salary: optional(tnumber),
  remote: optional(tboolean),
  get reports() { return optional(tschema) }
}

const tschema = [temployee] // array of temployee

const employees = [
  { name: 'alice',
    title: "ceo",
    salary: 100,
    reports: [{
      name: "bob",
      title: "cfo",
      salary: 10,
      reports: [{
        name: 'zorp',
        title:"controller",
        salary: 40
      }],
    }],
  },
  …
]

validate(tschema, employees) // throws an Error only if invalid

what's next?
You could design more schema tools like -

withDefault(t, defaultValue) - substitutes null values with a default
const temployee = {
  name: tstring,
  remote: withDefault(tboolean, false)
}

const tstudent = {
  name: tstring,
  major: withDefault(tstring, "undeclared")
}

const tcourse = {
  teacher: temployee,
  enrollments: withDefault([tstudent], [])
}

inRange(min, max) - numeric range guards
const temployee = {
  name: tstring,
  salary: inRange(0, Infinity) // negative salary invalid!
}

oneOf(t, choices) - inclusive value guards
const temployee = {
  name: tstring,
  title: oneOf(tstring, ["exec", "vp", "staff"]) // must be one of these!
}

We could improve the error messages by adding try..catch around the recursive calls. This allows us to add context to the point of failure so the user knows the full path to the offending leaf -
// schema.js (continued)

function validate(t, v) {
  let k
  switch (t?.constructor) {
    case Symbol:
      return validatePrimitive(t, v)
    case Array:
      if (t.length !== 1) throw Error("Array schema must specify exactly one type")
      try {
        for (k of Object.keys(v))
          validate(t[0], v[k])
      }
      catch (err) {
        throw Error(`${k}th child invalid: ${err.message}`)
      }
      break
    case Object:
      try {
        for (k of Object.keys(t))
          validate(t[k], v[k])
      }
      catch (err) {
        throw Error(`${k} invalid: ${err.message}`)
      }
      break
    case Function:
      t(v)
      break
    default:
      throw Error(`unsupported schema: ${t}`)
  }
}

Maybe export common types like -

temail - a valid email address
tphone - numeric string with accepted punctuation
tpassword - string at least 20 characters

Choose "required" or "optional" as the default behavior. Currently these have the same effect -
const temployee = {
  name: required(tstring),
  ...
}

const temployee = {
  name: tstring,  // null is not a string, so null will fail validation
  ...
}

This means required is implicit and we can remove it from our Schema module. Users are expected to use optional or withDefault when nullary values are acceptable.
remarks
Remember all complex things are made from combining simple things.  If you design things that cannot be combined, you are writing dead-end code.
This means we can write sophisticated validation expresssions by combining other validation expressions! Consider adding validation combinators like and and or, among others.
const tuser = {
  newPassword:
    // password must be
    //   at least 20 characters
    //   AND at most 40 characters
    //   AND include 2 symbols
    and(minLength(20), maxLength(40), requireSymbols(2))
  ...
}

const tuser = {
  newPassword:
    // password can be
    //   at least 20 characters
    //   OR 8 characters AND includes 2 symbols
    or(minLength(20), and(requireSymbols(2), minLength(8)))
  ...
}


Module enhancement file

Question: Hi guys (and gals) I'm trying to create a simple enhancement to one of my modules .inc files and am messing something up somewhere, and was hoping someone with sharp eyes can point it out. Even though it is extremely easy to just insert one line into the contrib file, do to our companies "best practices" I need to add this in another way.
I am trying add one extra variable into the $services array of the gigya_get_networks function, the function in gigya.inc is
function gigya_get_networks() {
  $services = array(
    'facebook' => 'Facebook',
    'myspace' => 'MySpace',
    'twitter' => 'Twitter',
    'google' => 'Google',
    'yahoo' => 'Yahoo',
    'aol' => 'AOL',
    'blogger' => 'blogger',
    'wordpress' => 'WordPress',
    'typepad' => 'typepad',
    'liveJournal' => 'liveJournal',
    'hyves' =>  'hyves' ,
    'veriSign' => 'veriSign',
    'linkedin' =>  'LinkedIn',
    'liveid' => 'Windows Live ID',
    'openid' => 'OpenID',
    'orkut' => 'Orkut',
  );
  return $services;
}

I created a new module in /custom/utilities/gigya_enhancements with the following
gigya_enhancements.info
name = Gigya Enhancements
description = Provides Gigya enhancements.
package = Gigya
php = 5.2

files[] = gigya_enhancements.module

dependencies[] = gigya

version = 7.x-3.1
core = 7.x

and a gigya_enhancements.module with the following
<?php
/**
 * Implements hook_get_networks().
 */
function gigyas_enhancements_get_networks() {

  // Add Vkontakte to existing services.
  $services = array(
    'vkontakte' => 'VKontakte',
  );

    // shortcode: return $services['vkontakte'] = 'VKontakte';

  return $services;
}

But I'm not returning my additional array parameter, would someone mind explaining what I (evidently) have done wrong? Is it something to do with
me trying to operate on an *.inc file maybe?
Thanks everyone.
Answer: Just adding an extra module with a similarly-named function won't guarantee that gigya will call that function. If Gigya's module has hooks (Google doesn't seem to be able to tell me at a glance), then that's the source for how to do what you're trying to do.
Also, you never need to put your .module file in files[]. That's only for files in the module that declare classes.
Comment: Thanks paul-m, much appreciated response. Gigya doesn't have hooks (unfortunately) so I created a git diff to patch the issue.

Module enhancement file


How do I fix my navbar text?

Question: For my website (www.heretoedit.com) I want to move the text in my navbar so that the "about" button is lined up with the rest of my website's text but the "contact" button stays put. Plus I want to stop the text for the "extras" and "contact" buttons from moving down when the screen size gets reduced.
Below is my navbar code, any help would be much appreciated. Thanks.

<code>#navbar {
background-color: #0299EB;
font-family: Verdana, Geneva, sans-serif;
color: white;
font-weight: bold;
position: absolute;
width: 1000px;
min-width: 100%;
height: 70px;
top: 150px;
left: 0px;
}

#navbar ul {
list-style:none;
display:inline-block;
margin-left: 130px;
margin-top: 25px;
}

#navbar li {
float:left;
padding: 0 9px;
text-align:center;
left: 0px;
}

#navbar a:link {
padding: 0 30px;
text-decoration: none;
color: #FFF;
}

#navbar a:hover {
color: black;
text-decoration: none;
}

#navbar a:visited {
color: #FFF;
padding: 0 20px;
text-decoration: none;
}
</code>
Answer: <code>#navbar ul {

    list-style: none;
    display: inline-block;

    /* Add these */
    margin: 25px 0px;
    padding: 0;
    width: 100%;
    text-align: center;

}
#navbar li {

    /* float: left; // Remove this */
    padding: 0 9px;
    text-align: center;
    left: 0px;
    display: inline-block; /* Add this */

}
</code>

How do I fix my navbar text?


Como centralizar mapa no meio do polígono?

Question: Tenho um polígono formado, a princípio, com 3 arestas, basicamente criado usando 3 locais: Maiami, Porto Rico e Bermudas. Peguei o exemplo na documentação que mostra como criar um polígono simples. Porém, por padrão exigida da API, deve-se centralizar o mapa em algum lugar (senão nem abre o mapa), no qual centralizei no Rio de Janeiro, através das coordenadas. Veja abaixo e dê zoom:

function initialize() {
  var map = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 10,
    center: new google.maps.LatLng(-22.91711261458102, -43.16944599151611),
    mapTypeId: "roadmap"
  });

  // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [{
      lat: 25.774,
      lng: -80.190
    },
    {
      lat: 18.466,
      lng: -66.118
    },
    {
      lat: 32.321,
      lng: -64.757
    },
    {
      lat: 25.774,
      lng: -80.190
    }
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
}

Uma forma que encontrei foi apontar o centro do mapa para qualquer ponto do polígono, porém não estará totalmente centralizado (baita perfeccionismo). A questão é que, gostaria de centralizar o mapa no meio do polígono, no qual estarei criando dinamicamente.
Qual seria melhor forma de fazer isso? Como centralizar mapa no meio do polígono?
Comment: Já tentou calcular o baricentro do polígono? No caso de um triângulo (polígono de 3 arestas), já há uma fórmula para isso (talvez precise adaptar para a geometria esférica); [fórmula para geometria plana](http://brasilescola.uol.com.br/matematica/baricentro-um-triangulo.htm)
Comment: @JeffersonQuesado mas ai teria que me retornar em formato de latitude e longitude. =D entendes isso ?
Comment: pois é, essa seria uma das adaptações para geometria esférica... Já tentou tirar a média aritmética de todos os pontos? (exclua o primeiro/último porque ele é repetido) Tipo, `centro = (sum(p[i].lat)/size(p), sum(p[i].lon)/size(p))`
Answer: A ideia é calcular o baricentro de um polígono e usar isso como coordenada do mapa.
O baricentro de um polígono é dado pela média aritmética das coordenadas (cartesianas!, detalhe importante para depois) dos pontos do polígono. De grosso modo, o seguinte algoritmo calcula isso:
x_baricentro = somatório (x dos pontos) / tamanho(pontos)
y_baricentro = somatório (y dos pontos) / tamanho(pontos)

O problema, entretanto, está que as coordenadas são dadas por coordenadas esféricas em graus! Para resolver isso, precisamos transformar essas coordenadas em radianos (180 graus vale pi radianos). A fórmula geral é essa:
theta_rad = theta_graus * pi / 180

A conversão oposta é:
theta_graus = theta_rad *180/pi

Ok, agora temos a conversão para radianos. Agora, precisamos converter de radianos para um ponto no espaço cartesiano. Usei as fórmulas contidas nessa pergunta do SO internacional.
x = cos(lat) * cos(lon)
y = cos(lat) * sin(lon)
z = sin(lat)

Com isso, obtenho a média de (x,y,z), vou chamar de (x_c,y_c,z_c) aqui na explicação. A partir desses valores, preciso converter de volta para radianos:
lon_rad = atan2(y, x)
hyp_rad = sqrt(x * x + y * y)
lat_rad = atan2(z, hyp)

Daí, só transformar para graus e ser feliz. O código abaixo está meio sujo e poluído, mas faz esses cálculos do jeito que foi mostrado.

function initialize() {
  // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [{
      lat: 25.774,
      lng: -80.190
    },
    {
      lat: 18.466,
      lng: -66.118
    },
    {
      lat: 32.321,
      lng: -64.757
    },
    {
      lat: 25.774,
      lng: -80.190
    }
  ];

  var x_cart = 0;
  var y_cart = 0;
  var z_cart = 0;
  var i;

  // ignorando primeiro elemento
  for (i = 1; i < triangleCoords.length; i++) {
      var x, y, z;
      var lat, lon;

      lat = triangleCoords[i].lat * Math.PI / 180; // transforma para radianos
      lon = triangleCoords[i].lng * Math.PI / 180; // transforma para radianos

      // obtém as coordenadas cartesianas
      x = Math.cos(lat) * Math.cos(lon);
      y = Math.cos(lat) * Math.sin(lon);
      z = Math.sin(lat);

      x_cart += x;
      y_cart += y;
      z_cart += z;
  }

  // média das coordenadas cartesianas
  x_cart = x_cart/(triangleCoords.length - 1.0);
  y_cart = y_cart/(triangleCoords.length - 1.0);
  z_cart = z_cart/(triangleCoords.length - 1.0);

  // processo para voltar a coordenadas esféricas
  var lng_c, hyp, lat_c;

  lng_c = Math.atan2(y_cart, x_cart);
  hyp = Math.sqrt(x_cart * x_cart + y_cart * y_cart);
  lat_c = Math.atan2(z_cart, hyp);

  // de volta para graus, saindo dos radianos

  lng_c = lng_c * 180.0/Math.PI;
  lat_c = lat_c * 180.0/Math.PI;

  var center = {
     lat: lat_c,
     lng: lng_c
 };
 console.log('lat lng' + lat_c + ',' + lng_c);

  var map = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 4,
    center: new google.maps.LatLng(center.lat, center.lng),
    mapTypeId: "roadmap"
  });

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
}

O @viana descobriu depois a função da própria API do GoogleMaps que faz o cálculo do baricentro.
Essa função é bounds.getCenter(), sendo var bounds = new google.maps.LatLngBounds(). Note que é necessário adicionar os pontos desejados nessa borda para pegar o centro.

function initialize() {
  // Define the LatLng coordinates for the polygon's path.
  var bounds = new google.maps.LatLngBounds();
  var i;

  var polygonCoords = [
     new google.maps.LatLng(25.774252, -80.190262),
     new google.maps.LatLng(18.466465, -66.118292),
     new google.maps.LatLng(32.321384, -64.757370),
     new google.maps.LatLng(25.774252, -80.190262)
  ];

  // ignorando o primeiro elemento
  for (i = 1; i < polygonCoords.length; i++) {
     bounds.extend(polygonCoords[i]);
  }

  // Aqui imprime a coordenada central em relação ao poligono - (25.3939245, -72.473816)
  console.log(bounds.getCenter());

  var map = new google.maps.Map(document.getElementById("map_canvas2"), {
    zoom: 4,
    center: bounds.getCenter(),
    mapTypeId: "roadmap"
  });

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: polygonCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
}


Using Random Number Table

Question: In a random number table, the random numbers are given as first thousand, second thousand, third thousand, and so on.
Every thousand has 25 rows and 1 to 4, 5 to 8 up to 37–40 columns.
Suppose I have to draw a sample of size 40 from a population of 10000, and I am using the 1 to 5 column for selecting the random numbers.
When the 1 to 5 column of first thousand has been finished, but I have not arrived at my desired sample size yet, what is the process to select the random numbers?
Will I need to go to the column 6 to 10 of the first thousand? Or go to the column 1 to 5 of the second thousand?
Another table here is the 1st page. If I decide to use the 1 to 5 number columns, when the 1 to 5 number columns of the 1st page are finished, will I move to the 1 to 5 number columns of the 2nd page or stay on the 1st page using 6 to 10 columns?
Comment: Is there anyway for you to show us what the table looks like?  perhaps a link or image of it?  I am having a hard time visualizing it.
Comment: Also, when you say a population of 10,000 do you mean that your want to sample values between 0 - 10,000 or am I misinterpreting this?
Comment: Out of curiosity why are you using a random number table?
Comment: @BabakP I have to use table in exam hall. In practical exam i may be allow to use software.
Answer: I would suggest watching this YouTube video
http://www.youtube.com/watch?v=9v2d-9VfEK4
in order to understand exactly how to use a random number table to answer your question.  The video show you how to select random numbers between 0 and 58 but you can follow the same routine to sample your random values.
I assume when you say a population of 10,000 you mean that your random values can be any value in the range 0  - 10,000 (correct me if I am wrong) and so you would pick a random starting spot in the your table and starting going down the rows and moving over one column at a time as you finish all the rows until you reach your desired sample size of 40 random values.
Edit:
So based on the table you provided above now, you could use columns 1 - 5 and work your way down accepting numbers (using all 5 columns) that fell in the range 0 - 10,000.  Once you are down with all the rows you would move over and then use columns 2 - 6 and proceed in similar fashion. However, if you exclude 10,000 then you could more efficiently use columns 1 - 4 and when done with those move over to 2 - 5 and so on.
Comment: you are right. the sample values can be determined in the range $00001-10000$
Comment: Please see my edit.
Comment: I apologize. I haven't understood the point. Using 1-5 columns and then using `2-`6. Why not 6-10 ? [In this video](http://www.youtube.com/watch?v=53MVU07j6dY) , once they have taken three digits of 1st,2nd,and 3rd column, they move on the next three column starting at #4 column for generating the next random number.

Using Random Number Table


How to start building a cross platform app?

Question: My friend and I are working on creating a product from scratch. We aim to build a cross platform application using react-native. We've planned to use firebase as our server hosting application.
Although, we both have fair amount of knowledge in react and have gone through some videos on react-native and firebase, mobile app development from scratch is still pretty new to us. We're having trouble to answer the following questions:

Where to start developement ?
Should we write our server in nodeJS and deploy it on firebase and my app can call the endpoints or should we connect to firebase directly from client side ?
How to setup configuration files and different environments for developement ?

These are among the many questions we have and we feel lost in this sea of infinite information.
Could anyone guide us here ? Please help me if I can frame my question in a better way.
Answer:
React Native is a great place to start. With today's ecosystem lead by flutter and react, Angular has unfortunately fallen behind.
Both, Cloud functions are Firebase's solution to server instances, these create short-lived functions that do complex or secure tasks such as handle payments, delete/manage users, etc. While the bulk of your app and its logic with firebase should be handled on the client, including accessing the data so long as you have secure rules.
this depends entirely on your framework of choice but in general, there should be a build option that enables you to configure which settings to compile with.


What's holding arpeggiated chords in piano called?

Question: What does this technique called? Also, what's the proper notation for this? The audio link is attached below.
https://voca.ro/19p4jeWEK5g8
Edit:
It sounds like fast arpeggio repeated over and over again with the same voicing.
Comment: I call that 'rolling' a chord, but no official backing for that.
Answer: Adding to Aaron's answer some notation remarks: In orchestral music such a between-two-notes tremolo is usually notated by notating the two notes in question with double length and putting tremolo beams between them.
In piano notation there is a special notation for this, where the tremolo beams attach to the stems of the notes, making it look like it was a pair of small notes with note heads from large notes. This is only really used for a total length written with a half note, as a whole note would look weird, and black notes allow for no distinguishing between smaller note values (so a 32th tremolo lasting a quarter would look just like 32th notes). Thus for such cases there is a notation where the first beam is attached to the stems, while the other beams are not.
Here is how these three variants look:
Comment: This notation is far more common than that in Aaron's answer, at least in piano music I've seen (Mostly classical and romantic period.  Maybe the other is more of a jazz-thing?)
Comment: Although I've never seen them in practice, multiple note/chord tremolos in this style are also possible, and probably a better fit for an arpeggiated chord (as mentioned by Gould, p. 229).
Answer: It's called a "shake", "tremolo", or "tremolando".

Shake: this term is most often used by jazz or blues players, and is IMO the most descriptive.
Tremolo: probably the most common term, though some musicians use it to mean repetition of a single note.
Tremolando: less common, and technically a synonym for "tremolo", but some musicians use it to mean repetition between multiple notes.

To get the specific effect, it's probably most clear to write "shake", "trem.", or "tremolo" above the notated chord.

"Tremolo bars" are also fine.

One can also use a trill line to indicate duration.


Is it possible to load an external javascript through Selenium RC?

Question: Is it possible to load an external javascript through Selenium RC? Suppose I want to enable jquery in my tests so that I could use the jquery capability for my user-extension.js. Is this possible? I'm using Java for this.
We are testing a black box web app in production so we are not able modify the code we are testing.
Thanks!
Answer: Have you seen this or this from Google ?


Como inicializar essa função de PhotoImage do tkinter?

Question:
Além de importar o tkinter, como eu chamo a função, por exemplo: _show(?, 'o título'), o que coloco na primeira variável que é de imagem? Mostre um exemplo qualquer se ela estiver no desktop.
Comment: Sempre dê preferência a compartilhar o código em vez de uma imagem, isso possibilita que outras pessoas possam usar seu código como base, facilita apontar correções e adaptações. Além disso, você conseguiria ser um pouco mais claro? Eu realmente não entendi o que você deseja.
Answer: A classe PhotoImage do tkinter é usada para mostrar imagens em Labels, Buttons, Canvas e Text.
O método _show() é um método interno do objeto Image; Não deve ser chamado diretamente. Uma dica para isso é que ele começa com um _; é um método interno, um detalhe de implementação que é chamado pelo próprio PIL.
Se você está criando um método _show, está tentando modificar a forma como o PIL mostrará imagens, mas você não deve chamar esse método diretamente.
Pra terminar segue um exemplo de uso da classe PhotoImage, onde uma imagem é inserida dentro de uma área de texto tkinter.Text:

img = """
R0lGODlhIAAgAKIFAAAAAACt74xzUsbGxv/3AAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwHoAAAh+QQF
CgAHACwAAAAAIAAgAAADuBi63P4wyrmApbjam+nmkiCK0QdGwqCSj3k+asw2LhXfQrthtww4Ox4u9wp8
KKlVTnFy/VCjZUXjDEkZT6NJm11Ev1PmlssQ9ZRMcY2sSJ4HgqCTE3Sfl88a58vnG9VyfYJRf1xBAYOD
aYBjVyiLho0YeIySSItze5OQkVptmwoEoqIWox9xo6mqAqqmAKakca+tqay0paSztrS1vLgEp7O8oruq
v8AWssPErS6ry6PFuNPCxcO7CQAAIfkEBQYABwAsAQABABcAHQAAA4IYugwOLMr13ryhWiy1i0J4eZIw
DKNGKSc6VV3QRmRDAa7ibTe/qx7XbxgICXS7DIRXPP6QIKNT1YAoQq1BsrowZWtVq7e17UrPgjJ6/Wyu
pUo1J147YoZiDv46p8OKGASCBA6CGmmDiYqFD4ZpAIqRkIWJApGXkxoElpeLhoedBAkAADs=
"""
import tkinter as t

root = t.Tk()
img = t.PhotoImage(data=img)
text = t.Text(root)
text.insert(t.END, "Olá, aqui está a imagem:\n")
text.image_create(t.INSERT, image=img)
text.insert(t.END, "  Obrigado!")
text.pack()
root.mainloop()

Answer: Bom, pelo que eu entendi, você quer colocar uma imagem na sua interface, se for isso mesmo, esse é um código mínimo para você adicionar uma imagem na sua interface.
try:
   from tkinter import *
except:
   from Tkinter import *

tela = Tk()

imagem_blender = PhotoImage(file="low_poly.png")
foto = Label(tela, image=imagem_blender)
foto.grid(row=1,column=1)

tela.mainloop()

No caso, a imagem low_poly.png" está na mesma pasta que o script com esse código, ok?


Base system question on weights

Question: Alex wanted to weigh 378 kg of wheat.  The weights are available in denominations of 1 kg, 2 kg , 4 kg, 8 kg, 16 kg , 32 kg... etc. He decides not to use more than one weight of each denomination.
In how many ways can he weigh 378 kg, if both sides of the balance can be used for weighing
My attempt :-
Of the 2 sides of balance, i have assumed that the item is kept on right side  , now for 1 kg item , i can put 1 kg weight on left side of balance, for 2 kg i can again use left side only, for 3 kg measurement i can use put 1 and 2  kg but how shall I make use of both sides of pan and measure weightsbv how many ways can he weigh 378 kg, if both sides of the balance can be used for weighing
Answer: You have $378=256+64+32+16+8+2$. So, you can put the wheat on one side of the balance and weights of $256$ kg, $64$ kg, $32$ kg, $16$ kg, $8$ kg, and $2$ kg on the other one. And that's the only answer. Because if there was another answer, then you would hav to put the wheat and also some weights on one side of the balance and then the same weights as before ($256$ kg, $64$ kg, $32$ kg, $16$ kg, $8$ kg, and $2$ kg) on the other side, plus the same weights that you have added to the wheat (since every integer can be written as a sum of powers of $2$ in one and only one way). But you want to use each weight exactly once.

Base system question on weights


union with group by mysql

Question: Hi I have a query as follows but group by is not working.
SELECT messages.thread_id,messages.subject,messages.message_id,messages.status,messages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date from messages inner join login on messages.receiver = login.id where (messages.sender = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and messages.status = 'trash' )
UNION SELECT messages.thread_id,messages.subject,messages.message_id,messages.status,messages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date from messages inner join login on messages.sender = login.id where (messages.receiver = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and messages.status = 'trash')  GROUP BY messages.thread_id

Comment: first use mysqli not mysql it's better and put some explain with some data and example for the output you want
Answer: You have to put brackets around the union select, give it an alias and select from it:
SELECT A.* FROM
(messages.thread_id,messages.subject,messages.message_id,messages.status,mess
ages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as
date from messages inner join login on messages.receiver = login.id
where (messages.sender = '" .
mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and
messages.status = 'trash' )
UNION SELECT
messages.thread_id,messages.subject,messages.message_id,messages.status,messa
ges.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as
date from messages inner join login on messages.sender = login.id where
(messages.receiver = '" .
mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and
messages.status = 'trash')) AS A
GROUP BY A.thread_id

Answer: Wrap your query to an outer query so that it can group the combined results from both the queries.
SELECT z.*
FROM
(
    SELECT messages.thread_id, messages.subject, messages.message_id, messages.status,
    messages.attachment, login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date
    FROM messages
    INNER JOIN login ON messages.receiver = login.id
    WHERE messages.sender = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "'
    AND messages.status = 'trash'
    UNION
    SELECT messages.thread_id, messages.subject, messages.message_id, messages.status,
    messages.attachment, login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date
    FROM messages
    INNER JOIN login ON messages.sender = login.id
    WHERE messages.receiver = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "'
    AND messages.status = 'trash'
) AS z
GROUP BY z.thread_id

union with group by mysql


Row and column integer error when calling load

Question: I have a simple spreadsheet in Excel 97-2003 format, extension is XLS, that is throwing the following error when trying to load it with PHPSpreadSheet.

Error 0 on line 49 in \PhpSpreadsheet\Cell\CellAddress.php -> Row and Column Ids must be positive integer values

The spreadsheet has 14 columns with no formulas or external references. Similar spreadsheets in the same format load and process without error.
require 'PHPSpreadsheet/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$spreadsheet = $reader->load($inputfile);  // <-- this is where the failure happens

If I create a new spreadsheet and copy the rows from the one that fails into the new one the load works just fine. The header row and 1 row of data are shown below. I have tried removing the header row and manually entering a single row but get the same failure.
It seems to be related to the file itself but the error message isn't helping to determine exactly what the problem is.
DATE    Course ID   Title of Class  StartTime   PGH Location    Address City    State   Zip Code    Sponsor/Vendor  Instructor if Known Contact Information Telephone
1/10/2023   7280801 Dual Credit Water & Wastewater Workshop 08:00   6   Anywhere Fire Department    123 Main St Any Town    NC  28580   NC Statewide Safety Conference, Inc.    Sam Smith   Joe Smith   252-555-1212

Answer: This was caused by a bug in PHPSpreadsheet that was revealed by having a vertical break in row H0 for some reason.
Removing the breaks in the spreadsheet manually would also correct the problem but the latest version of PHPSpreadsheet has been fixed so it will not thrown an error if there is a vertical break in the first row.


Integrating arctan

Question: $x^2\over(1+x^2)$
Is there any other way to integrate this other than make the numerator $x^2 +1 -1$ and then split this into two integrals?
My smartass friend told me that this is the only way but I refuse, but I'm stupid I've spent couple of hours trying to think about this but never came up with anything.
Comment: If you mean *any* other way, one way is trig substitution. Take a right triangle with legs $x$ and $1$ and $\theta$ opposite the side of length $x$. Then $x=\tan(\theta),dx=\sec^2(\theta) d \theta$ and $1+x^2=\sec(\theta)^2$ so you have $\int \tan(\theta)^2  d \theta$. This isn't hard to integrate once you use the identity $\tan(\theta)^2=\sec(\theta)^2-1$.
Comment: Did you mean $$\displaystyle \int\left(1- \frac{1}{1+x^2} \right)\mathrm dx = x-\arctan(x) + C$$?
Answer: Letting $x=tan(u)$ so $dx=sec^2(u)du$ also noting that $1+tan(u)^2=sec^2(u)$ the integral becomes $\int tan^2(u)du$.  This integral is pretty easy if you rearrange the previous trig identity to get $tan(u)^2=sec^2(u)-1$.
EDIT: I realized the back substitution is sort of non-trivial so I decided to add it.  Using $\int tan^2(u)du=\int sec^2(u)-1du$ we can split this up and $sec^2(u)$ is an elementary integral to take.  So we get $\int sec^2(u)-1du=\int sec^2(u)du-\int du=tan(u)-u+C$.  Now noting that we let $x=tan(u)$ so $arctan(x)=u$ and you just get $tan(arctan(x))-arctan(x)+C=x-arctan(x)+C$.
Comment: Of course, the trig identity winds up telling you to do almost exactly the same algebra as was suggested in the OP in the first place, it just gets suggested by trig rather than simply by intuition.
Comment: By the way, in elementary calculus they generally frown upon replacing a variable with itself.
Comment: @Ian Yeah I just got home from a long day and typed way too fast, fixed now!  Thanks for pointing that out.
Answer: Split x^2 into x*x. Do integration by parts, where u = x, dv = x/1+x^2. This will lead you to calculating the integral of ln(1+x^2), which is ugly, but can be done with certain trig substitutions.
Answer: $$\frac{x^2}{1+x^2} = \frac{x^2}{(x+i)(x-i)} = \color{red}{x\left(\frac{A}{x+i} + \frac{B}{x-i}\right)}$$  $$A(x-i) + B(x+i) = x$$
$$-2iA = -i \implies A = 1/2$$
$$ 2iB = i \implies B = 1/2$$
This implies that we can rewrite our red fractions as such:
$$= \frac{x}{2(x+i)} + \frac{x}{2(x-i)}$$
We now use the substitutions $x+i = u$  and $x-i = v$
$$= \frac{u-i}{2u} + \frac{v+i}{2v}$$
If we now integrate these we get
$$= \frac{1}{2}\left(u-i\log(u) + v +i\log(v)\right)$$
$$= \frac{1}{2}\left(2x-i\log(x+i)+i\log(x-i)\right)$$
$$= x + \frac{i}{2}\left(\log(x-i)-\log(x+i)\right)$$
We now recognize the final term as a definition of inverse cotangent and the result follows. That might be the most absurd way to solve this, but hey... no adding or subtracting in the numerator!

Integrating arctan


Taxonomy vs. CCK List for categorizing Events

Question: Could someone let me know what the best practice is for choosing between implementing something as a Taxonomy vs. a List field in the Content Type?  Assuming that there is a preset list of values and there is no need for content creators to create their own.
For example, a Content Type of an "event" could be categorized based on audience or type.  Audiences can be [Kids, Youth, Adults, Seniors, etc.].  Similarly, type would have a preset list as well.
Should audience or type be created as Taxonomy or a List field in the Content Type?
Answer: If you use taxonomy, then using the calendar module they can be colour-coded in the legend based on their category.
Comment: Great point. Thank you for pointing that out.  Anything else I should consider?
Comment: Here is a writeup on the subject that I have used in the past to determine the best route for each use-case. http://www.johnandcailin.com/blog/cailin/drupal-cck-vs-taxonomy


A real sequence with a cluster set exactly =$\{n^2: n \in \mathbb{N} \}$

Question: I would like to construct a sequence with a cluster set of the form $\{n^2: n \in \mathbb{N}\}$. I had  ideas of the form $u_n= \cos(\pi\sqrt{n})$, but this seems to not work.
I really appreciate your help.
Thank you
Answer: Hint: Consider the sequence
\begin{align*}
&1\\&1,2^2+1/2\\
&1,2^2+1/3,3^2+1/3\\
&1,2^2+1/4,3^2+1/4,4^2+1/4\\
&1,2^2+1/5,3^2+1/5,4^2+1/5,5^2+1/5\\
&\dots
\end{align*}
Where you read one row at a time, so it starts $(1,1,4.5,1,4.\overline{3},9.\overline{3},\dots)$
If you understand this, try to generalize it to get a sequence which has cluster set $S$, where $S$ is any countable set of real numbers!


android | multiple onclicklistener in dialog

Question: Inside my Activity I start a simple dialog.
final Dialog myDialog = new Dialog(this);
myDialog.setContentView(R.layout.testing);
...

My testing.xml Layout consists of nothing but 10 ImageViews, id`s are '1' to '10'.
I want every ImageView to be clickable and to do something.
The define the onclick() methode in the .xml file isn`t working, as the methode can't be found when the dialog is viewed.
The only way I got it work is following: define 10 onclick-listeners:
ImageView img_1 = (ImageView) myDialog.findViewById(R.id.1);
ImageView img_2 = (ImageView) myDialog.findViewById(R.id.2);
...

img_1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
  execute_funtion(1);
  myDialog.cancel();
}
});

img_2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
  execute_funtion(2);
  myDialog.cancel();
}
});

...

However, that's really bad code, I have 10 times nearly the same lines.
So my question: How can I make that work with clean code?
I thought about a multiple onclicklistener (overwride the onClick() function and make a switch/case in the functions or something like that), but it's not working.
I'm happy about every idea!
Thanks
/EDIT
Here a snippet of the .xml file
<ImageView
  android:id="@+id/1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:padding="2dp"
  android:onClick="myFunction"
  android:src="@drawable/ic_launcher" />

Comment: what do you mean **define the onclick() methode in the .xml** .  post that .xml file as well
Comment: i added it, thanks for calling attention!
When clicking the image, "myFunction()" can't be found.
Comment: Use switch case as you have mentioned `overwride the onClick() function and make a switch/case in the functions or something like that`. But first rename your ids. It is not allowed numerical id, use img1, img2 instead.
Answer: Make your Activity implement OnClickListener and then process the onClick event like below:
@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.img1:
        ...
        break;
    case R.id.img2:
        ...
        break;
    }
}

Comment: Actually you can't define id as number.
Answer:
You should let your Activity/Fragment implement the OnClickListener.
When you do that you will have to override the onClick method in that particular activity/fragment.
Set the onClickListeners on the images as follows:
img_1.setOnClickListener(YourActivity.this);

Then in that onClick method you can put a switch case or an if else if case as follows
@Override
public void onClick(View v)
{
    if(v==img_1) {
          //do this
    } else if(v==img_2) {
        //do that
    }...
}

or
@Override
public void onClick(View v)
{
    switch (v.getId()) {
        case img_1.getId(): // do this
            break;
        case img_2.getId(): // do that
            break;
        .
        .
        .
        default : break;
    }
}

Comment: Sorry, the first piece of code is not formatting for some reason!
Comment: "case img_1.getId():" isn't working, but it works when i write
  "case R.id.1"

thanks!


substraction of groups in direct sum

Question: Assume I have a sub group $G\leq \mathbb Z^n$ and I have $\mathbb Z^n = G\oplus \mathbb Z^m $ for some $m\leq n$.
I want to deduce $G\cong\mathbb Z^{n-m}$. Is that true? how can I do it?
Comment: It is true and there are several ways to go about it. What have you tried/how much do you know about these objects?
Comment: i tried writing down an explicit isomorphism $G\to \mathbb Z^{n-m}$ using the original isomorphism, but it didnt work.

You may assume I have decent knowledge in group theory.
Answer: $G$ is a subgroup of a finitely generated abelian group. So itself must be also finitely generated. $G$ cannot contain any non-zero torsion as $\mathbb{Z}^n$ doesn't either. So $G\cong \mathbb{Z}^k$ where $k$ is a non negative integer. $\mathbb{Z}^k\oplus \mathbb{Z}^m \cong \mathbb{Z}^{m+k}$ so it follows.

substraction of groups in direct sum


How to pass argument in service with dependency injection

Question: In a custom module, I have a custom service that uses GuzzleHttp\Client service.
mymodule.services.yml:
services:
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@http_client']

The MyModuleCall is using dependency injection and start like:
namespace Drupal\mymodule;

use GuzzleHttp\Client;

class MyModuleCall {

  protected $client;

  public function __construct(Client $client) {
        $this->client  = $client;
  }

}

As explained in the GuzzleHttp documentation (http://docs.guzzlephp.org/en/latest/quickstart.html), we can pass an argument to the Client constructor to set the base_uri.
Like so:
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org'
]);

How do we set the 'base_uri' in the constructor when we use dependency injection to instantiate a class?
Comment: you don't provide the create method in your class?
Comment: Short answer: you can't. Arguments in your services.yml file are other services which are objects. You can add an extra setter in your class "setBaseUri" or put it in config and get it from the config factory
Comment: There is a work around however...
Answer: While it would not be possible to use the http_client service it is possible to use the factory service (or create your own factory service if you choose not to rely on core methods).
The http_client_factory service provides a fromOptions method.
The Symfony2 documentation has a section on using parameters:

Use the parameters section of a config file to set parameters:

parameters:
  mymodule.http_client.config:
    base_uri: 'http://httpbin.org'

services:
  mymodule.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%mymodule.http_client.config%']
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@mymodule.http_client']

Now the MyModuleClass will use Guzzle with Drupal's default configuration and custom configuration.
Note: it is also possible to provide your own factory service for Guzzle and to use that directly. This would be useful if you need to use your own overridden Guzzle\Http\Client class (I do this in a contrib module). This would probably be necessary to inject custom configuration such as handler stack (OAuth1).
Comment: is it possible to pass an argument at runtime? for example, at the time of calling  \Drupal::service('custom_service'); how to pass an argument?
Comment: Get the factory service directly and call the appropriate method (or ideally a different method).


How long does Grade 6 music theory take?

Question: I did Grade 5 theory back in 2013. And did A-level music in 2012-2014. My attendance wasn't great, for various reasons, and my memory is patchy but I've retained my Grade 5 theory skills and then some.
I aim to do Grade 8 piano in March and then Grade 6 theory in Summer. I hope to start doing preparatory work for the Theory exam in January and then take the exam on June 16th (I study an unrelated subject full time so time presently is taken up with that and specific practical exam practice). Are my aims realistic?
Typically, a sensible place to ask is my teacher. However, although he's covered the material in his BMus, his previous students have stopped at G5 so he isn't entirely sure (I don't believe G6-8 ABRSM theory is particularly popular or useful, probably).
One handicap is that I self taught G1-5 material in 2012-2013 by going through Eric Taylor's AB Guide to Music theory and doing the associated practice books. I eventually got total in the G5 theory exam for all questions bar the one on composition which I was ill-prepared for. I'm aware that that particular skill as well as harmony is what's examined primarily in the subsequent grades which I plan to take.
ABRSM syallbus

1 Writing specified chords for voices in four parts or for keyboard (at the candidate's choice) above a given bass part of about four bars

No experience but I'm aware of the chords which contain every diatonic melody notes in each key as well a the need to contain pivotal chords and cadences at key points. I already know figured bass notation.

2 The indication of suitable chords for the accompaniment of a diatonic melody of about eight bars in any key, using any recognized method of notation, or, at the candidate's choice, the provision of a bass to a given melody, adding figures to indicate the intended harmonies.

I gather that I simply have to realize the figured bass notation and follow stylistic rules such as no parallel octaves. Practice is clearly needed, but at least there doesn't seem to be a huge barrier to starting.

3 Composition of a melody for a specified instrument (a choice will be given), using a given opening. Modulation to the dominant, subdominant, relative major or relative minor may be required.

This is where I think I'll really struggle I think. I don't have a strong internal sense of what melodies sound like when written on paper so finishing them will require training.

4 Questions on short extracts of music written for piano or in open score for voices or for any combination of instruments and/or voices, designed to test the candidate's knowledge of the elements and notation of music, including the realization of ornaments, the identification and notation of underlying harmonic structure, phrase structure, style, performance, and on the voices and instruments for which the works were written.

My A-level music skills should come in handy here as I spent a lot of time doing score analysis although I will need to look at specific material.
Based on what I've written, does my time frame look realistic? And what sort of daily commitment time would you suggest?
Answer: Sounds about right. The ABRSM 'Theory in Practice' books are well thought of, and will take you past 5, into 6 easily. Work through them, with an occasional teacher input. Most people seem to do grade 5 as a passport to practical 6+, and don't do 6,7 and 8. Assuming you want to pursue a musical career, it will look good on the c.v. and also fill in a lot of stuff you never meet just doing practical exams. How much time each day/week? Don't know you, so impossible to say! But aim to get through everything and leave a month before the exam, to polish it all.
Comment: You need to work through tons of those mock exams to build up your knowledge. I spent nearly a year working through past papers in prep for my ABRSM grade 6
Answer: Grade 6 ABRSM is a fair bit more work than Grade 5. Grade 5 theory is sufficient to gain you access to a practical level of Grade 8, that is more than enough for most people who do not want to do music for a career.
Grade 6 is only required when you start work on the music diplomas that ABRSM offers. Grade 6 is for the DipABRSM and Grade 8 is for the LRSM.
What got me when I prepared for my Grade 6 is the rather large amount of soft skills you need to develop before you can enter the exams. Take for instance that 4th and 5th question.
They can ask you just about anything about any piece and you have to have the rounded general music knowledge to answer the questions.
Although the previous grades could be considered formulaic in there answering the Grade 6 expects a sound musical base knowledge and ask you questions accordingly.


How to add multiple js files in hook_field_widget_form()?

Question: When I load two JS files using drupal_add_js() as can be seen in the code marked "After", it does not show alert() text on page load and also when I click on the button created in the form to load fancybox (popup) it shows
$.fancybox is not a function

When I just add taxonomy_fancybox.js it shows alert, so my question is
How can I make sure both fancybox.js and taxonomy_fancybox.js are loaded.
Before
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

After
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  drupal_add_js(drupal_get_path('module', 'fancybox') . '/fancybox.js');
  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

taxonomy_fancybox.js has
(function ($) {
  Drupal.behaviors.selectterms = {
    attach: function (context, settings) {

      alert('enters');

      $('#edit-select-terms').click(function (e) {

        e.preventDefault();

        $.ajax({
          url: '/ajax/fetch-vocabularies/',
          success: function (data) {
            $.fancybox(data);
          }
        });

      });

    }
  };
}(jQuery));

Answer: Seems you missed step 3. from the README.

Download the fancyBox plugin and extract the entire directory into    sites/all/libraries. (You may need to create this directory). The path
  to    fancyBox should be
  sites/all/libraries/fancybox/source/jquery.fancybox.js.    (the module
  uses the minified version, so actually jquery.fancybox.pack.js).

The second JS then doesn't fire anymore as the first JS virtually raised an exception already (due to the non-existent 3rd party library).


Wrapping multiple TextBoxes into a DataTable

Question: I have a web page and my in my data access layer I am updating the textboxes to my page. It is a simple 3 Tier App.
Something like this I have in my DataAccess Class:
 public void SaveDataSet(DataTable table)
        {

           //What to do here???

        }

How should I pass all of my textboxes value to this function as DataTable parameter?
Answer: I would suggest you to use Microsoft Entity Framework, you can grab some video tutorials  here it is pretty easy to use and really fast, and it will not take you too much on understand how it works, also it googles really well ;)
Answer: Or if you want to go the data table way yo need something like this
first we create the datatable
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();

DataColumn myDataColumn;

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);

return myDataTable;
}

then you need a method to insert data to your datatable
private void AddDataToTable(string username,string firstname,string lastname,DataTable myTable)
{
DataRow row;

row = myTable.NewRow();

row["id"] = Guid.NewGuid().ToString();
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;

myTable.Rows.Add(row);
}

now you can create a method to insert the datatable to the sql server like this
private void insertDataTable(DataTable MyDataTable)
        {
            string ConnectionString = "your connection string";
            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(ConnectionString)
            {
                bulkcopy.DestinationTableName = "dbo.<your table>";
                try
                {
                    bulkcopy.WriteToServer(MyDataTable);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
              }
          }

Comment: Oh! My....I just read Entity Model Framework and I knew this is happening. Thanks for the info. I am learning as fast as I can...
Comment: Don't mention it :) Im really pleased with EF its awesome
Comment: Also i would recommend you to step into ASP MVC 3 it just blends pretty good with Entity Framework
Comment: Yea, I started learning MVC3 using Entity Framework. It is pretty good.


Makefile with multiple directories

Question: I wanted to write a makefile for a program that has source files located in different directories, the structure is:
--root(here will be makefile)
  --src:
    --main.c
    --include:
      --here are 6 .h files, that are used by other .c files, main.c includes on all of them
    --operacje
      --suma.c
      --iloczyn.c
      --roznica.c
    --reszta:
      macierz.c
    --we_wy:
      --rest of the .c files

most of .c files include at least one .h file. This is what I wrote so far:
VPATH=./src:./src/include:./src/operacje:./src/reszta:./src/we_wy
CLFAGS = -Wall
CC = gcc
INCLUDE = -I src/include
NAME = macierze

FILE_SOURCE := pliki.c wczytaj_plik.c wypisz_plik.c
CONSOLE_SOURCE := wczytaj_konsola.c wypisz_konsola.c
OTHER_SOURCE := suma.c roznica.c iloczyn.c macierz.c
HEADERS := suma.h roznica.h iloczyn.h wypisz.h wczytaj.h macierz.h

FILE_OBJECTS := $(FILE_SOURCE:.c=.o)
CONSOLE_OBJECTS := $(CONSOLE_SOURCE:.c=.o)
OTHER_OBJECTS := $(OTHER_SOURCE:.c=.h)

%.o: %.c %.h
    gcc $(CFLAGS) $(INCLUDE) -c $?

%.o: %.c
    gcc $(CFLAGS) $(INCLUDE) -c $? -o $@

finput: HEADERS+=pliki.h

finput: $(FILE_OBJECTS) $(OTHER_OBJECTS) main.o
    gcc $(CFLAGS) -o $(NAME) $^ -D WEWY_PLIKI

main.o: main.c $(HEADERS)
    gcc $(CFLAGS) $(INCLUDE) -c src/main.c

clean:
    rm -rf *.o

The goal is, to make compiled program run a bit differently based on make , hence the -D option and adding
finput: HEADERS+=pliki.h

this finput is the first of the 4 possible options. Each option will be using slightly different set of .c and .h files
Now, when I do
make finput

i get the listing:
gcc  -I src/include -c ./src/we_wy/pliki.c ./src/include/pliki.h
gcc  -I src/include -c ./src/we_wy/wczytaj_plik.c -o wczytaj_plik.o
gcc  -I src/include -c ./src/we_wy/wypisz_plik.c -o wypisz_plik.o
gcc  -I src/include -c src/main.c
gcc  -o macierze pliki.o wczytaj_plik.o wypisz_plik.o ./src/include/suma.h ./src/include/roznica.h ./src/include/iloczyn.h ./src/include/macierz.h main.o -D WEWY_PLIKI
wczytaj_plik.o: In function `wczytaj':
wczytaj_plik.c:(.text+0x5f): undefined reference to `macierz_alokuj'
main.o: In function `main':
main.c:(.text+0x7e): undefined reference to `suma'
<and other undefined references in main>

I noticed few errors:
1. it doesen't produce .o files from $(OTHER_OBJECTS)
2. there is no -Wall option from $(CFLAGS)
3. and of course it doesen't complete.
I would be grateful for some info, what am I doing wrong.
Answer:
OTHER_OBJECTS := $(OTHER_SOURCE:.c=.h)

If this is not a typo, it is the explanation for (1.). You rename the files to header files, and the header files are found in VPATH and have no remake rules, so they are included verbatim in $^. Try $(OTHER_SOURCE:.c=.o).

CLFAGS = -Wall

Try CFLAGS instead.
Comment: Now i feel silly, everything works fine, it was just 2 typos..., anyway big thanks for help.
Comment: I have one more question, I fixed the make-file but everytime I invoke make finput it always at least does the linking of .o files (finput rule), even if I didn't made any changes to files, why?
Comment: There is no `finput` file, only a `macierze` file. The target part says `finput`, though, so make looks for `finput` and doesn't find it. Replace `finput` by `$(NAME)` everywhere.
Answer: Just to point out that this:
finput: HEADERS+=pliki.h
  ...
main.o: main.c $(HEADERS)

will not do what you want it to do.  Target-specific variables only are in effect inside the recipes of child targets.  They do not have any impact on the prerequisite lists (for example).
I urge you to look into methods of automatically generating make dependencies: this is far more efficient (and accurate) than trying to maintain them by hand within the makefile.

Makefile with multiple directories


IIS site not responding from some machines, DNS correct

Question: This is a strange one.
I have a site set up on IIS 6, this site has a unique IP assigned to it. The strange thing is that it works from some locations and it just doesn't from other locations. DNS is resolving to the right IP address, however pinging to that address times out.
Any ideas why the site doesn't work?
As a note, I have other sites running from the same VPS, but using a different IP address. and they are working fine.
Cheers
Answer: Try tracert from both directions. Are they following the same route?
Maybe the response from your server is going on a different route that is blocked.
Comment: tracert from where it doesnt work timesout, works fine from where it does work
Answer: Since it's not pinging, it's at a lower level than IIS.  My only guess is that you have some custom firewall rules in place.  Also confirm that your server does listen to pings, just so that you know for sure what the expected response should be.
To troubleshoot, narrow this down to the smallest part.  i.e. ping the IP of a good site and failed site and confirm that one listens to the IP and the other doesn't.  Try the same from a computer where both sites work.
Consider any patterns in the computers where it doesn't work from.  Are they in a different subnet, in a different part of the Internet?  Review all firewall rules in the path from the failed computers to the server.
Answer: It sounds like you might be running into an issue with Socket Pooling.  From Microsoft's technical whitepapers:

In IIS4, you could bind different Web
  sites to different IP addresses. Sites
  did not share sockets, but each site
  on a unique IP address had several
  sockets. These sockets are created
  when the site starts, and they consume
  significant non-paged memory (RAM).
  This memory consumption limits the
  number of sites bound to IP addresses
  that can be created on a single
  machine.
For IIS 5.0, this process has been
  modified so that sites bound to
  different IP addresses, but sharing
  the same port number, share the same
  set of sockets.

Socket Pooling continues from IIS 5.0 to the current Windows versions.  Try disabling the socket pooling and see if you can get your web site working.  I ran into this problem and wrote a blog post about it titled Separating IP:PORT Bindings on Windows.


How can I check the Chromium version used by the latest Electron release?

Question: So apparently since 2018 Electron has used an outdated feature set of JavaScript via older Chromium / Node version so we can't use import ES6 syntax. According to an answer linked, the solution is to use babel. However, if Electron ever gets with the times, Id like to remove that extra step from my project. Where / how can I see which version of Chromium / Node is supported by the latest release of Electron? Preferably by looking at the GitHub page or documentation rather than having to install / test.
Comment: JavaScript runtimes don't implement *versions*, but *features*. See https://stackoverflow.com/a/61836170/906113
Comment: @str thanks for the correction. I think I updated my phrasing accordingly
Answer: Electron releases page has a note everytime Chromium version is updated.
For instance, 11.0.5 has updated Chromium to 87.0.4280.88.
Apart from that, if you want to know which Chromium version your application is using, you can enable DevTools and see release information there.
Comment: Oh cool. Good to know. I know I left it out of the question but I suppose they also always mention when the version of Node is updated?
Comment: Wait on that documentation, on page two release 11.0 it says its using Node V12... Shouldnt that support `import`?
Comment: It does. Where are you getting the error? Runtime or on the editor?
Comment: nvm I found a github issue where they explain they're not supporting `import` until they support node v14 https://github.com/electron/electron/issues/21457


What is the best way to cache a home page?

Question: I have a simple home page, like that:
index view with partials:

header
how_it_works
benefits
customer_supports
about
covered_areas

I tried to use "Page Caching"/"Action Caching". But in my layout I have a top header that has a condition if user_signed_in?. So using "Page Caching"/"Action Caching" doesn't work for me.
Should I use "Fragment Caching" for each partial?
I appreciate any help!
Answer: You can use caches_action :index, layout: false if the problem is only about the layout.


help with graph theory question

Question: Let $A_1A_2A_3A_4$ be a square, and let $A_5,A_6,A_7,\ldots,A_{34}$ be distinct points inside the square. Non-intersecting segments $\overline{A_iA_j}$ are drawn for various pairs $(i,j)$ with $1\le i,j\le 34$, such that the square is dissected into triangles. Assume each $A_i$ is an endpoint of at least one of the drawn segments. How many triangles are formed?

how can I approach this problem?
Comment: I'd try smaller numbers of points, first, to see if there is a pattern.
Answer: Hint:

From Euler characteristic we know that $V-E+F=2$.
Because the square is triangulated, there is a relation between number of edges and number of faces:

 $$3(F-1)=2E-4$$ (the outer face is a square and we count its edges only once).

I hope this helps $\ddot\smile$

help with graph theory question


ActionBar ignoring icon

Question: I'm slowly moving my app to Android Lollipop, in fact I'm just beginning this process.
But I'm already having some problems. The first one is that I can't make the icon appear in the ActionBar again. Just the app name and buttons appear.
Here is my style:

And here is my AndroidManifest:
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:name=".MyApp"
        android:theme="@style/AppTheme" >
<activity
            android:name="com.br.myapp.MainActivity"
            android:label="@string/explore"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >

        </activity>

</application>

And my activity class is extending ActionBarActivity from the AppCompat library v21.
Answer: Try adding the following two lines in onCreate of your main Activity:
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.your_actionbar_icon);

Comment: Have you made sure that your icon is the correct size? Icons displayed in the `ActionBar` must be of size 32x32 dp, as per the Iconography guidelines: http://developer.android.com/design/style/iconography.html#action-bar
Comment: I'm using the same launcher image. After using AppCompat 21 it is displayed bigger than before.
Comment: This might just be an implementation difference, seeings as how the Material theme for Lollipop was not designed to show the application icon in the `Toolbar`. As per the Material Design Checklist: "The app bar doesn't have an app icon. Color and typography are used for branding instead." You could always try resizing the image and then see if that fixes your issue.

ActionBar ignoring icon


how to get IMEI number in ionic 2 mobile app?

Question: I am building a mobile application and want to access the IMEI number.
I have gone through the following plugins.

https://github.com/vliesaputra/DeviceInformationPlugin
https://github.com/hygieiasoft/cordova-plugin-uid
https://github.com/aquto/cordova-plugin-imei

And all of them are giving me 404 error.
Finally I got one plugin that I could install

https://www.npmjs.com/package/imeiplugin

and below is the code I wrote to access the IMEI
The below code is written inside my home constructor.
platform.ready().then(() => {
            window["plugins"].imeiplugin.getImei(function (imei) {
                console.log(imei);
            });
        });

But the control never goes to the console.log();
Am I doing anything wrong here??
Or if anyone has integrated the IMEI number with some other method please let me know.
Or as per suggested in the below link do I have to build my own custom plugin??

How to get IMEI number in PhoneGap?

I am stuck here and I am looking for an efficient way any help is appreciated.
Thanks in advance
Answer: Actually this plugin works:
https://github.com/hygieiasoft/cordova-plugin-uid
(Using: cordova plugin add org.hygieiasoft.cordova.uid returns 404)
So try this instead:
cordova plugin add https://github.com/hygieiasoft/cordova-plugin-uid
platform.ready().then(() => {
   alert(cordova.plugins.uid.IMEI);
});

Comment: i tried this plugin, but this is also giving me error!!!! says failed to fetch plugin. Can you share your ionic info??
Comment: Please try again, here is the screen shot of the plugin I added.
https://drive.google.com/open?id=0B5NOdnm05pUWRUdtUUVWblBkdVE
Comment: This worked for me: cordova plugin add https://github.com/lionelhe/cordova-plugin-uid.git


Get the user theme

Question: In my admin page, I have a text field, for which I want to set the default_value as the active theme. I am getting the admin theme. But my requirement is to get the user theme.
Is there some how I could get theuser active theme.
Answer: The user default theme could be obtained by
<code>variable_get('theme_default');
</code>
Comment: If I active any other theme, will it give me back that theme name?
Comment: This will return the theme which is set to 'Active and default'. So, if you change the default theme, it will return the name of that theme :-)

Get the user theme


How do you scrape even numbered  elements with python/selenium?

Question: Code that I am targeting looks like this:

     Shipwreck: Fairfax the Deckhand

     Harpoon Harry's: Franchisco Corvallio

The issue is there are 50  elements on the page, out of every 5 TD elements, I only need the second one. So for example  element 2, 7, 12, 17, etc. All of the  elements do not have any class elements or id's so the only way that I am able to target them is through order but I am not sure how to do that through selenium.
Answer: That would be: find_by_css_selector('td:nth-child(5n+2)')


ModuleNotFoundError: No module named 'psycopg2.errors'

Question: I have psycopg2 module installed, but I can't import exceptions from this library:
$ pip freeze | grep psycopg
psycopg2==2.7.7
$ python
Python 3.7.4 (default, Nov  5 2019, 17:21:00)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> from psycopg2.errors import InsufficientPrivilege, UndefinedTable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'psycopg2.errors'

Comment: `psycopg2.errors` was introduced in version 2.8.
Comment: Yes, it was... Sorry.
Answer: As @john-gordon mentioned.

psycopg2.errors was introduced in version 2.8.


MS Excel - replicating a series of cells

Question: I have the following data in a spreadsheet:
I
I need a formula/workaround that would give me the following:

Thanks,
Answer: You can reference and repeat data by using the INDEX function.
Placing the formula =INDEX(A:A,FLOOR((ROW()+4)/5,1),1) into a cell on the first row (B1, C1, etc.) and copying down will repeat everything in column A 5 times.


Using 2 sample T test in time series data

Question: I have two data series (not stationary) and I would like to see if the mean of  series 1 is significantly different when a certain condition (on the other series) is met. The theory is that when series 2 reaches a value greater than 100, the value of series 1 declines.
I've done the following: I've broken the data down into chunks, where each chunk represents a time period during which all the data in series 2 were either below or above 100. I then compare the means of series 1 in each chunk with the mean in the next chunk using the two sample T test to see if the mean of series 1 is lower when series 2 is greater than 100, and higher when series 2 is less than 100.
For example:
<code>Obs Series1 Series2
1    0.05     50
2    0.03     80
3    -0.4     30
4    0.1      110
5    0.03     105
6    0.12     90
7    -0.3     92
8    0.11     100
9    0.2      120
</code>
The first chunk would be the first 3 observations (all less than 100, and the second chunk the next 2 (both greater than 100). I would compare the means of series 1 in these two chunks to one another to see if they are different using the two sample t test.
I would then compare the mean of series 1 from observations 6&7 with the mean from observations 8&9.
Then, if I find that in the majority of the chunks the means are significantly different, I can conclude that series 1 is significantly lower when series 2 exceeds 100.
Does this methodology even make any sense? I'm sure there is a much better way, if anyone has suggestions for me, I'm just fairly new to this kind of analysis.
Thanks
Mike
Answer: First, a comment on your approach. The standard setting in which a t-test is used would require independence across observations. Meanwhile, your observations may have some time patterns (autocorrelations etc), if I understand it correctly. Then you would need some adjustment to account for that instead of using the plain-vanilla t-test.
Second, here is how I would try solving this problem. Call the first series $y$ and the second series $x$. I would build a model for $y$ incorporating a feature that you are interested in. Then I would test whether the estimated feature is statistically significant.
From the limited information you have provided, I am not able to suggest what kind of model that would be. But for the sake of an example, let me assume two things:
(1) $x$ is exogenous to $y$ ($y$ does not determine $x$);
(2) $y$ follows an ARIMA(p,d,q) model with an exogenous regressor.
Since you say that $y$ (and $x$) is not stationary, let $y$ ~ $I(1)$ as an example. Then $y$ ~ ARIMA(p,1,q) with an exogenous regressor. Here is how you incorporate the feature of interest: make the exogenous regressor the indicator of $x$ being above/below 100.
Now choose suitable AR and MA orders for your model (by using AIC, BIC, looking at model residuals etc. – follow the standard guidelines). Once done, you only need to look at the coefficient on the exogenous regressor and the associated p-value. This should answer you question of interest.
If $x$ is not exogenous to $y$, you would need to model $y$ and $x$ jointly. However, the logic is still the same. Once you have built a decent model that incorporates the feature of interest, just check the relevant coefficient and its significance.
Comment: Sorry, maybe I didn't make it clear, but I have no reason, a priori, to believe that the standard deviations would be the same between the two groups
Comment: Hi Richard, thanks for the reply. I have checked my data for autocorrelation and found none, indicating that they are, in fact, independent across time. That should be sufficient to allow me to use the two sample t-test, right? Thanks again!
Comment: Absence of autocorrelations does not guarantee independence across time (there might still be dependence in higher order moments, for instance) but it gives some encouragement. And if your observation are truly independent across time, then I guess you could do the following. Gather all observations corresponding to $x<100$ in one subsample, all the other observations in another subsample and test whether the means of the two subpopulations (that correspond to the two subsamples) are equal using a t-test that allows for a different number of observations in the two subsamples.
Comment: The important idea is that you would like to account for any other systematic differences between the two subsamples so that your t-test result would indeed reflect the effect of the difference in means rather than some other effects (e.g. due to difference in variances etc.).
Comment: Ok, I undestand. Yes, that's exactly what I'm doing. I am using the two sample t-test, which allows for different standard deviations and sample sizes across the two sub samples. Cool, thanks Richard!
Comment: One more thought: if you believe that the only difference between the $y$'s is due to $x$'s being above of below 100, then why do you allow for different standard deviations between the two subsamples when doing the t-test? I would only allow for different standard deviations if I believed that the variance of $y$ depends on whether $x<100$.


Regex in Notepad ++ or Dreamweaver

Question: Using Notepad ++, Dreamweaver or some other editor,
is it possible to use a regex which uses file name in the replace field?
For example:
There are files: firstfile.html and secondfile.html
Find: yyy
Replace: "some regex for files name"

And then in those files wherever yyy is found it will be replaced with the file's name.
In firstfile.html - if there is yyy it will be replaced with firstfile.
In secondfile.html - if there is yyy it will be replaced with secondfile.
Comment: [Same issue](http://stackoverflow.com/questions/19840541/find-text-and-replace-for-filename-on-notepad), basically you can't without writing a plugin or using an altogether other language/tool.
Comment: Make a tool to do this, and you can use it again and again.
Answer: As for "some other editor", the answer is yes (EditPad can do this):

(I removed some parts of the user interface to save space in this screenshot).
Comment: There is a problem. It really work BUT - it seems that all files must be open in order to do replace job. Is it possible it won't replace whole folder as dreamweaver for example? Folder contains a lot of files that need change I mean a lot... I'm new to editpad pro perhaps I miss something.... I download editp ro 7 free trial...
Comment: @user3082821: Right, EditPadPro only works on files opened in the editor. There'a different tool that works on folders/disks etc. (PowerGREP), but that's much more expensive. You could open all the files in your folder and click on the "Files" option in the regex search/replace panel to tell EPP to apply the regex to all the opened files.
Comment: Your solution with editpad pro is good. I know your name on this site from other questions. I think, if I remember other topics, that you are expert for regex problems. Thank you very much for your help. Just to mention I download PowerGrep but I can not find replace field.
Comment: Can you please check the link below :http://stackoverflow.com/questions/31294441/rename-file-name-using-some-text-from-that-same-file

Regex in Notepad ++ or Dreamweaver


What do you call it when two different melodies are combined?

Question: Say that Alice has a theme song with a certain melody. Also, Bob has his own theme with a certain melody. But during a scene where Alice and Bob are together, both melodies are played together at once on top of each other.

Does this technique have a name?
Are there any prototypical / classic examples of this?
Are there any important properties the 2 melodies must have so that, combined, they sound pleasant?

The only related thing I can think of is how "Canon" and "Row Row Row Your Boat" are both able to complement themselves, but that's not exactly the same.
Comment: I've always thought the best 'pop' example of this is [Paul McCartney/Wings, Silly Love Songs](https://www.youtube.com/watch?v=ap87QgZKTNw) I think it was 7 distinct melodies, last time I counted.
Comment: I'm not sure whether you meant it, but your Alice and Bob story muddies the water. Polyphony and counterpoint are the general terms. Canon is a specific type among many. Your Alice and Bob story suggests the two melodies were composed _independently_, but you didn't say that explicitly. Counterpoint is often described in terms of _procedure_. You've left out some important procedural detail. Who/when/how were the two melodies written?
Comment: @MichaelCurtis I specifically chose that example because, yes, the two melodies should be considered separate/independent. But then, when you play them on top of each other, it sounds nice (and has thematic meaning in this case between Alice and Bob).
Comment: separate/independently... composed? Independence of melodies has a meaning in counterpoint. If you just say "the melodies are independent", it isn't understood you mean composed by two different people.
Answer: The term you're looking for is quodlibet, which is a composition that combines several melodies.
There are different types of quodlibets, but you're discussing the "simultaneous quodlibet," when different melodies are played at the same time so as to sound harmonious.
This practice dates back to the Renaissance era, but the tradition is alive and well today, especially in Broadway musicals.
At some level there are important properties the melodies must have for this to work. But since melodies can be combined in so many ways—which melody is above which, are they played at the same tempo (or is one, say, in half time), are there slight changes made at cadence points, etc.—that it's frankly tough to pinpoint what these properties would be. Instead, it's up to the composer to show their mastery and make the melodies fit.
I'm a classical guy, and my favorite quodlibet is at the climax of Benjamin Britten's "Young Person's Guide to the Orchestra." Not only is this a quodlibet, but it's at the ending of what is in my opinion the most impressive fugue ever written. He combines it with a theme of Henry Purcell that started the very beginning of the piece.
Comment: @chausies Note, this is a great word for a time that someone works with existing material; like, Britten added his own theme to a theme that was hundreds of years old. It might not be a good choice for times that one composer, within one work, combines two themes from earlier in the work, like "Anakin's theme and the Imperial March are superimposed" or, in *Matilda: The Musical*, a reprise of the song "Naughty" is superimposed on the later song "When I grow up."
Comment: I should probably throw in that a more contemporary/pop term for the same concept is "mashup," but again that usually implies combining materials that have been produced earlier, often by other artists (e.g. Jonathan Coulton's "When I'm 25 or 64," combining Paul McCartney's "When I'm 64" with Chicago's "25 or 6 to 4").
Answer: Polyphony: two or more simultaneous "voices" (e.g., melodies). Prototypical examples: Palestrina and Bach.
Duet: two people (or instruments) singing together, each with their own distinct part that combine into a single song. Prototypical examples: too far back in music history, and too many exemplars.
Leitmotif: The use of melodies specific to a character or idea, which can be combined to convey meaning. Prototypical example: Wagnerian opera.
The qualities required to make two simultaneous melodies sound pleasant is, more or less, the basis of several hundred years of Western music theory. And, of course, "pleasant" is in the ear of the beholder. Atonal duets, depending on the particular style, will follow a set of rules, but may or may not be "pleasant".
Comment: "more or less, the entire basis of music theory": much of music theory concerns itself with music that has only one melody.  Some music theory even concerns itself with music that has none.  Certainly, the origins of music theory stretch back far enough that the basis (in a historical sense) couldn't lie in the rules of counterpoint.
Comment: @phoog I think you're nitpicking here. Is my meaning really that unclear?
Comment: No, your meaning is perfectly clear; I just wanted to point out that the statement implies an overly narrow conception of "music theory."
Comment: @phoog It does, true. It seemed inappropriate in this question to bring in all the other music theories.
Comment: @phoog Perhaps the clarification I just added will suit.


How can I add tags to an RDS cluster

Question: There's a difference between an individual RDS instance and an RDS cluster, I can tag the RDS instance just fine via the AWS UI but can't seem to be able to tag the cluster.
How do you go about tagging an AWS RDS cluster.
Answer: Turns out this isn't possible in the AWS Console. You have to use the API:
List tags:
aws rds list-tags-for-resource --resource-name arn:aws:rds:<region>:<account>:cluster:<cluster_name>

Add keys:
aws rds add-tags-to-resource --resource-name arn:aws:rds:<region>:<account>:cluster:<cluster_name> --tags '
[
    {
        "Key": "Name",
        "Value": "MyCluster"
    },
    {
        "Key": "Environment",
        "Value": "dev"
    }
]'

How can I add tags to an RDS cluster


Getting blitting to work in funcAnimation embedded in PyQT4 GUI

Question: Starting with the working Matplotlib animation code shown below, my goal is to embed this animation (which is just a circle moving across the screen) within a PyQT4 GUI.
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation

fig,ax = plt.subplots()
ax.set_aspect('equal','box')
circle = Circle((0,0), 1.0)
ax.add_artist(circle)
ax.set_xlim([0,10])
ax.set_ylim([-2,2])

def animate(i):
    circle.center=(i,0)
    return circle,

anim = animation.FuncAnimation(fig,animate,frames=10,interval=100,repeat=False,blit=True)

plt.show()

I am able to accomplish this using the following code, but there is one hitch: I cannot get blitting to work.
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Circle
from matplotlib import animation

class Window(QtGui.QDialog): #or QtGui.QWidget ???

    def __init__(self):
        super(Window, self).__init__()
        self.fig = Figure(figsize=(5,4),dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.ax = self.fig.add_subplot(111)  # create an axis
        self.ax.hold(False)  # discards the old graph
        self.ax.set_aspect('equal','box')
        self.circle = Circle((0,0), 1.0)
        self.ax.add_artist(self.circle)
        self.ax.set_xlim([0,10])
        self.ax.set_ylim([-2,2])
        self.button = QtGui.QPushButton('Animate')
        self.button.clicked.connect(self.animate)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def animate(self):
        self.anim = animation.FuncAnimation(self.fig,self.animate_loop,frames=10,interval=100,repeat=False,blit=False)
        self.canvas.draw()

    def animate_loop(self,i):
        self.circle.center=(i,0)
        return self.circle,

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

When I set blit=True, after pressing the Animate button I get the following error:
a.figure.canvas.restore_region(bg_cache[a])
KeyError: matplotlib.axes._subplots.AxesSubplot object at 0x00000000095F1D30
In searching this error, I find many posts about how blitting does not work on Macs, but I am using Windows 7. I have tried replacing self.canvas.draw() with self.canvas.update(), but this does not work.
Comment: looks like I am following your footsteps: have you been able to find a solution on this?
Comment: Not yet, unfortunately...
Answer: After looking at the source code of the animation module, I realized that there is an error in the Animation class (the dictionary bg_cache is empty, when it is accessed for the first time with blitting switched on).
This is fixed in the git version of matplotlib; however, in the most recent stable version 1.5.1, the bug is still present. You can either fix the bug in the matplotlib code itself or you can make a subclass to FuncAnimation. I chose that way, because it should still work after updating matplotlib.
from matplotlib import animation

class MyFuncAnimation(animation.FuncAnimation):
    """
    Unfortunately, it seems that the _blit_clear method of the Animation
    class contains an error in several matplotlib verions
    That's why, I fork it here and insert the latest git version of
    the function.
    """
    def _blit_clear(self, artists, bg_cache):
        # Get a list of the axes that need clearing from the artists that
        # have been drawn. Grab the appropriate saved background from the
        # cache and restore.
        axes = set(a.axes for a in artists)
        for a in axes:
            if a in bg_cache: # this is the previously missing line
                a.figure.canvas.restore_region(bg_cache[a])

Then, simpy use MyFuncAnimation instead of animation.FuncAnimation.
Took me a while to figure it out, but I hope it helps anybody.
Answer: After some time I managed to recreate the animation by using the underlying functions directly and not using the animation wrapper:
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Circle
from matplotlib import animation
from time import sleep

class Window(QtGui.QDialog): #or QtGui.QWidget ???

    def __init__(self):
        super(Window, self).__init__()
        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.ax = self.fig.add_subplot(111)  # create an axis
        self.ax.hold(False)  # discards the old graph
        self.ax.set_aspect('equal', 'box')
        self.circle = Circle((0,0), 1.0, animated=True)
        self.ax.add_artist(self.circle)
        self.ax.set_xlim([0, 10])
        self.ax.set_ylim([-2, 2])
        self.button = QtGui.QPushButton('Animate')
        self.button.clicked.connect(self.animate)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.canvas.draw()
        self.ax_background = self.canvas.copy_from_bbox(self.ax.bbox)

    def animate(self):
        self.animate_loop(0)

    def animate_loop(self,begin):
        for i in range(begin,10):
            self.canvas.restore_region(self.ax_background)
            self.circle.center=(i,0)
            self.ax.draw_artist(self.circle)
            self.canvas.blit(self.ax.bbox)
            self.canvas.flush_events()
            sleep(0.1)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Maybe this will be of use to you.
Comment: This is perfect! Thanks so much!
Comment: Undetermined, I'm having a new problem with my axes not changing appropriately when I try to modify them before blitting (posted [here](http://stackoverflow.com/questions/36811952/deleting-old-axes-when-blitting-in-matplotlib-animation-embedded-in-pyqt4)). Have you encountered this issue before?
Comment: Yes I  have had this problem. No I have not found a solution. Sorry. I actually turned to c# in the end for the stuff i'm doing now. May look into this again later
Comment: Why do you give `animate_loop` an argument called `i` and you overwrite it immediately by running `for i in range(10)`?
Comment: @Guimoute that looks like a bug have changed the input to the function to do something useful...


'apt-get clean' returns error in Ubuntu 20.04 LST with WSL2

Question: apt-get clean
returns errors
E: Could not open lock file /var/cache/apt/archives/lock - open (13: Permission denied)
E: Unable to lock directory /var/cache/apt/archives/
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
when run on ubuntu 20.04 LTS in wsl-2 on Windows
Tried various solutions on internet but nothing worked
Thanks in advance..
Answer: You will need to run the command with sudo:
sudo apt-get clean


github3.py. Empty list of commited files

Question: I developing a web service which uses some Github info. I need to get a list of files which changed with a commit. I found a list of libraries. I tried all 3 Java libraries and github3.py. And all these libraries returns me a commit info with an empy list of affected files(or null for Java libs). The code for getting list of affected files is really easy so I have no idea why it happens.
from github3 import login, repository

repo = repository('sigmavirus24', 'github3.py')
commits = repo.iter_commits()
for commit in commits:
    print len(commit.files) #prints 0

UPD: How I can get a list of files changed by specific commit?
Comment: So what exactly is your question?
Comment: @MattDMo Sorry. Updated
Answer: When iterating over a resource (in this case commits) the GitHub API often returns a subset of the information that is available for one instance of that resource. Using your code, let's try something
from github3 import repository

commits = repository('sigmavirus24', 'github3.py').iter_commits()
c = next(commits)
print(len(c.files))  # => 0
print(c.refresh())  # => <Repository Commit [0eec5f6]>
print(len(c.files))  # => 1
print(c.files)
# [{u'status': u'modified', u'deletions': 0, ... }]

github3.py provides (on most objects) a refresh method that will fetch that particular instances complete data from the API. This will unfortunately result in more API calls than you might like though. A common pattern for some is to do
r = repository('sigmavirus24', 'github3.py')
cs = r.iter_commits(50)  # Limit it to 50 commits
commits = [c.refresh() for c in cs]

In this case you're making exactly 51 API calls, 1 for the listing of the first 50 commits, and 50 to get all of the data for each commit from the API.
I'm not sure if the Java wrappers provide any similar capability


Forcing direction in Bootstrap carousel

Question: I have the following slides: 0 1 2 3 4 and I want the carousel to go from 3 to 0 while looking like it's sliding 'forward' to 0, instead of 'back' to 0;
This will slide "back" from 3 to 0:
$("#my-carousel").carousel(slideNum);

I can force direction by using next, but it will show from 3 to 4, which I don't want:
$("#my-carousel").carousel('next');

Is it possible to go from 3 to 0, by forcing the direction you want it to slide to? I'm looking for something like:
$("#my-carousel").carousel(slideNum, direction);

Comment: http://stackoverflow.com/questions/16877562/twitter-bootstrap-carousel-cycle-items-right-to-left-rtl-reversed
Comment: Hmm... close, but not quite what I'm looking for, since I need to force direction only on certain occasions, not all the time. I have the following slides: `0 1 2 3 4` and I want the carousel to go from 3 to 0 while looking like it's sliding 'forward' to 0, instead of 'back' to 0;
Comment: i am not sure if i understand the issue, why are you skipping slide 4? you can catch the slide event and check if the current slide is 4, skip it (which wraps around back to 0). Is that what you want?
Comment: I want to show slide 4 depending on user interaction, so sometimes it will be available, and sometimes it won't. When I skip from 3 to 0 via `.carousel(0);` the animation looks like it's sliding 'back' to 0, but I want it to skip 'forward' to 0. I can't use `.carousel('next');` because although it gives me the 'forward' animation I want, it gives me slide 4.
Comment: use `.carousel('next');` and catch the event (http://getbootstrap.com/javascript/#carousel-usage) `slide.bs.carousel` which fires right when the slide is called.  make logic that decides whether to show slide 4, or launch `.carousel('next');` a second time to move to 0 and skip it.
Comment: Thanks for your help! Unfortunately I had to circumvent the issue through other means because calling `.carousel('next');` twice in a row didn't give me the desired results.
Answer: I know it's been years since this question first raised. TBH I myself came here looking for the solution to this one. but looks like it was never resolved perfectly, not here, not anywhere else too.
So I am posting my solution for those who would possibly be visiting this page in future.
I was surprised that this is doable with only css. I would hope a comment from the OP if this was the thing he wanted.

.carousel.vertical {
    position: relative;
}

.carousel.vertical .carousel-inner {
    height: 100%;
    width: auto;
}

.carousel.vertical .carousel-inner > .item {
    transition: 0.6s ease-in-out;
    transform: translate3d(100%, 0, 0);
    top: 0;
    background: #ccc;
    width: 100%;
    height: 300px;
    border: 1px solid #e6e6e6;
}

.carousel.vertical .carousel-inner > .item div {
    text-align: center;
    height: 100%;
    font-size: 80px;
    line-height: 300px;
}

.carousel.vertical .carousel-inner > .next,
.carousel.vertical .carousel-inner > .prev,
.carousel.vertical .carousel-inner > .right {
    transform: translate3d(100%, 0, 0);
    top: 0;
}

.carousel.vertical .carousel-inner > .left,
.carousel.vertical .carousel-inner > .prev.right,
.carousel.vertical .carousel-inner > .next.left,
.carousel.vertical .carousel-inner > .active {
    transform: translate3d(0, 0, 0);
    top: 0;
}

.carousel.vertical .carousel-inner > .active.right,
.carousel.vertical .carousel-inner > .active.left {
    transform: translate3d(-100%, 0, 0);
    top: 0;
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

1

2

3

4

5

6

Comment: Neat! That's exactly what I was looking for 4 years ago. Haha!
Answer: One way to achieve the reversed direction is to manipulate the items position in the DOM.
On the slide.bs.carousel event you can prevent its default behavior, reverse the direction by:

Move the desired item before/after the current active item
Call the .carousel('prev') or .carousel('next') method
Move item back to its original position

The following code is able to prevent default behavior and reverse its direction (with optional direction parameter). On the slide.bs.carousel event, it will slide to the first item from right-to-left.
A working demo can be found here: http://codepen.io/dimbslmh/pen/JEaGJK
(function() {
  'use strict';

  /**
   * Slide to item.
   * @param {object} event - Carousel slide event.
   * @param {string} [direction=left] - Cycle direction.
   */
  function slideTo(event, direction) {
    var $element = $(event.currentTarget);
    var $indicators = $element.find('.carousel-indicators');
    var $items = $element.find('.item');
    var $active = $element.find('.item.active');
    var $item = $(event.relatedTarget);
    var itemIndex = $item.index();

    if (typeof direction === 'undefined') direction = 'left';

    if (event.direction !== direction) {
      event.preventDefault();

      if (direction === 'right') {
        $item.insertBefore($active);
        $element.carousel('prev');

        setTimeout(function() {
          if (itemIndex === $items.length - 1) {
            $item.insertAfter($items.eq(itemIndex - 1));
          } else {
            $item.insertBefore($items.eq(itemIndex + 1));
          }
        }, 600);
      } else {
        $item.insertAfter($active);
        $element.carousel('next');

        setTimeout(function() {
          if (itemIndex === 0) {
            $item.insertBefore($items.eq(1));
          } else {
            $item.insertAfter($items.eq(itemIndex - 1));
          }
        }, 600);
      }

      $indicators.find('.active').removeClass('active');
      $indicators.children().eq(itemIndex).addClass('active');
    }
  }

  $('#myCarousel').on('slide.bs.carousel', function(event) {
    if ($(event.relatedTarget).index() === 0) {
      slideTo(event);
    }
  });

})();

Forcing direction in Bootstrap carousel