Cisco router 877w local subnet route

Question: i have a local network of 192.168.2.1-254 running on a device called MSONA (all in one small business solution), our internet gateway cisco router is on 192.168.0.253. If i want the router to backup its running config to a tftp server on 192.168.2.125, it cannot reach it.
I am very new to Cisco commands so i have no idea what should be done to enable this. Im guessing i need to add some kind of route so that cisco router can reach this subnet, please help.
my running config:
AamalNet#show run
Building configuration...

Current configuration : 8553 bytes
!
version 12.4
no service pad
service timestamps debug datetime msec
service timestamps log datetime
service password-encryption
!
hostname AamalNet
!
boot-start-marker
boot-end-marker
!
logging buffered 51200 warnings
enable secret level 2 5 <removed>/
enable secret level 5 5 <removed>/
enable secret 5 <removed>/
!
aaa new-model
!
!
aaa authentication login default local
aaa authentication login sdm_vpn_xauth_ml_1 local
aaa authentication login sdm_vpn_xauth_ml_2 local
aaa authorization exec default local
aaa authorization network sdm_vpn_group_ml_1 local
!
!
aaa session-id common
clock timezone KSA 3
!
crypto pki trustpoint TP-self-signed-2939284004
enrollment selfsigned
subject-name cn=IOS-Self-Signed-Certificate-2939284004
revocation-check none
rsakeypair TP-self-signed-2939284004
!
!
crypto pki certificate chain TP-self-signed-2939284004
certificate self-signed 01
<removed>
quit
dot11 syslog
!
dot11 ssid 1stdecor Cisco Router
vlan 5
authentication open
authentication key-management wpa
mbssid guest-mode
wpa-psk ascii 7 <removed>
!
ip cef
no ip dhcp use vrf connected
ip dhcp excluded-address 10.10.10.1
ip dhcp excluded-address 10.10.11.1
ip dhcp excluded-address 192.168.0.0 192.168.0.99
ip dhcp excluded-address 192.168.0.201 192.168.0.254
!
ip dhcp pool lan
import all
network 192.168.0.0 255.255.255.0
default-router 192.168.0.253
dns-server 22.214.171.124 18.104.22.168
lease 0 2
!
ip dhcp pool wireless
import all
network 10.10.11.0 255.255.255.0
default-router 10.10.11.1
dns-server 126.96.36.199 220.127.116.11
lease 0 2
!
!
no ip domain lookup
ip domain name aamal.net.sa
ip name-server 126.96.36.199
ip name-server 188.8.131.52
!
!
!
username <removed> privilege 15 password 7 <removed>
!
!
crypto isakmp policy 1
encr 3des
authentication pre-share
group 2
!
crypto isakmp client configuration group aamalnet
key aamalnet
dns 18.104.22.168 126.96.36.199
  include-local-lan
  dhcp server 10.10.10.1
  max-users 10
  netmask 255.255.255.0
 crypto isakmp profile sdm-ike-profile-1
    match identity group aamalnet
    client authentication list sdm_vpn_xauth_ml_2
    isakmp authorization list sdm_vpn_group_ml_1
    client configuration address respond
    virtual-template 1
 !
 !
 crypto ipsec transform-set ESP-3DES-SHA esp-3des esp-sha-hmac
 !
 crypto ipsec profile SDM_Profile1
  set security-association idle-time 60
  set transform-set ESP-3DES-SHA
  set isakmp-profile sdm-ike-profile-1
 !
 !
 archive
  log config
   hidekeys
 !
 !
 !
 bridge irb
 !
 !
 interface ATM0
  no ip address
  no atm ilmi-keepalive
  dsl operating-mode auto
 !
 interface ATM0.1 point-to-point
  pvc 0/35
   pppoe-client dial-pool-number 1
  !
 !
 interface FastEthernet0
 !
 interface FastEthernet1
 !
 interface FastEthernet2
 !
 interface FastEthernet3
 !
 interface Virtual-Template1 type tunnel
  ip unnumbered Dialer0
  tunnel mode ipsec ipv4
  tunnel protection ipsec profile SDM_Profile1
 !
 interface Dot11Radio0
  no ip address
  !
  encryption vlan 5 mode ciphers tkip
  !
  broadcast-key vlan 5 change 30
  !
  !
  ssid 1stdecor Cisco Router
  !
  speed basic-1.0 basic-2.0 basic-5.5 6.0 9.0 basic-11.0 12.0 18.0 24.0 36.0 48.0 54.0
  station-role root
 !
 interface Dot11Radio0.5
  encapsulation dot1Q 5 native
  no cdp enable
 !
 interface Vlan1
  description $ETH-SW-LAUNCH$$INTF-INFO-HWIC 4ESW$
  no ip address
  ip nat inside
  ip virtual-reassembly
  ip tcp adjust-mss 1452
  bridge-group 1
 !
 interface Dialer0
  ip address negotiated
  ip mtu 1452
  ip nat outside
  ip virtual-reassembly
  encapsulation ppp
  dialer pool 1
  dialer-group 1
  no cdp enable
  ppp authentication chap callin
  ppp chap hostname <removed>
  ppp chap password 7 <removed>
 !
 interface BVI1
  ip address <removed> 255.255.255.248 secondary
  ip address 192.168.0.253 255.255.255.0
  ip nat inside
  ip virtual-reassembly
 !
 ip forward-protocol nd
 ip route 0.0.0.0 0.0.0.0 Dialer0
 !
 ip http server
 ip http access-class 23
 ip http authentication local
 ip http secure-server
 ip http timeout-policy idle 60 life 86400 requests 10000
 ip nat inside source list 1 interface Dialer0 overload
 ip nat inside source static 192.168.0.90 <removed>
 ip nat inside source static 192.168.0.91 <removed>
 ip nat inside source static 192.168.0.92 <removed>
 ip nat inside source static 192.168.0.93 <removed>
 ip nat inside source static 192.168.0.94 <removed>
 !
 access-list 1 remark SDM_ACL Category=2
 access-list 1 permit 192.168.0.0 0.0.0.255
 access-list 1 permit 10.10.11.0 0.0.0.255
 access-list 23 permit 18.104.22.168 0.0.0.255
 access-list 23 permit 184.108.40.206 0.0.0.255
 access-list 23 permit 18.104.22.168 0.0.0.255
 access-list 23 permit 10.10.10.0 0.0.0.255
 access-list 23 permit 192.168.0.0 0.0.0.255
 dialer-list 1 protocol ip permit
 snmp-server community private RW
 snmp-server community public RO
 no cdp run
 !
 !
 !
 control-plane
 !
 bridge 1 protocol ieee
 bridge 1 route ip
 banner exec ^CC
 % Password expiration warning.
 privilege interface level 5 encapsulation
 privilege interface level 5 description
 privilege interface level 5 no encapsulation
 privilege interface level 5 no description
 privilege interface level 5 no
 privilege configure level 5 ip route
 privilege configure level 5 interface
 privilege configure level 5 controller
 privilege configure level 5 ip
 privilege exec level 5 copy running-config tftp
 privilege exec level 5 copy running-config
 privilege exec level 5 copy
 privilege exec level 5 write memory
 privilege exec level 5 write
 privilege exec level 5 configure terminal
 privilege exec level 5 configure
 privilege exec level 5 show processes cpu
 privilege exec level 5 show processes
 privilege exec level 2 show running-config
 privilege exec level 5 show configuration
 privilege exec level 2 show
 privilege exec level 5 clear counters
 privilege exec level 5 clear
 !
 line con 0
 privilege level 15
 no modem enable
 line aux 0
 line vty 0 4
 access-class 23 in
 privilege level 15
 transport input telnet ssh
 !
 scheduler max-task-time 5000
 end

Comment: What is the MSONA box's IP in the 192.168.0.0/24 network?
Comment: MSONA's local ip: 192.168.0.91
Answer: It should be as simple as this:
ip route 192.168.2.0 255.255.255.0 <IP_of_MSONA>

Note that this needs to be an IP of the MSONA box that the router can reach, one inside the 188.8.131.52/24 network. This should be done on the 192.168.0.253 router.
Comment: why are you assuming routing is allowed? That MSONA box very likely does NAT.
Comment: i figured out that much, now it can ping to the MSONA box at 192.168.2.1 (192.168.0.91 being its virtual interface on vlan2) but cannot ping or see anything in the 192.168.2.0/24 network.
Comment: What is the default gateway of the machines in the 192.168.2.0/24 network? Do they have a route to 192.168.0.0/24? Ping won't work if the reply packets can't get back.
Comment: their gateway is 192.168.2.1
Comment: @user210774: Then ping should work. You should troubleshoot. (Are packets being sent out? Are they reaching their destination? Is a reply being sent? And so on.)
Comment: @ItsGC: Yeah, good point. Troubleshooting really has to be done by someone who understands the way it's supposed to work.
Comment: ofcourse they can ping to the 192.168.0.253 gateway but this does not mean they can ping anything on the 192.168.0.0/24 subnet. Also what im trying to do is to make the cisco router be able to see the 192.168.2.0./24 subnet. Maybe it needs to be done from MSONA side not sure. Actually i just want to be able to export the cisco router's config to a tftp server and also to be able to export netflow data and this has to be done on a pc in the 192.168.2.0/24 subnet.

Cisco router 877w local subnet route


ReferenceError: lecturerFac is not defined

Question: When I load the html page, my controller retrieves data from an API end point regarding a course. The page gets populate with the data about the course. But at the same time I want to populate part of the page with data about the lecturer of the course (their image, name , description etc ...). I pass the lecturer name to the method using the ng-init directive but I get a
ReferenceError: lecturerFac is not defined.
I am not sure but I believe the issue is the way I am calling the getLecturer() function using the ng-init directive.
What I want to happen when the page loads is have the Lecturer's details displayed on the page along with the course details.
courses.html

{{lecturer.name}}

             <

{{lecturer.description}}
  -->

{{courses.name}}

{{courses.description}}

CoursesDetailsCtrl
todoApp.controller('CoursesDetailsCtrl', ['coursesFac','lecturerFac','$scope','$stateParams', function CoursesCtrl(coursesFac, lecturerFac, $scope, $stateParams){

$scope.getLecturer = function(name){
        lecturerFac.getLecturerByName(name)
            .then(function (response) {
                $scope.lecturer = response.data;
                console.log($scope.lecturer);
            }, function (error) {
                $scope.status = 'Unable to load lecturer data: ' + error.message;
                console.log($scope.status);
            });
    };

}]);

lecturerFac
todoApp.factory('lecturerFac', ['$http', function($http) {

var urlBase = '/api/lecturer';
    var coursesFac = {};

     lecturerFac.getLecturer = function () {
        return $http.get(urlBase);
     };

    lecturerFac.getLecturerByName = function (name) {
        return $http.get(urlBase + '/' + name);
    };

    return lecturerFac;
}]);

Answer: todoApp.factory('lecturerFac', ['$http', function($http) {

    var urlBase = '/api/lecturer';
        var coursesFac = {};
        var service = {};
         service.getLecturer = function () {
            return $http.get(urlBase);
         };

        service.getLecturerByName = function (name) {
            return $http.get(urlBase + '/' + name);
        };

        return service;
    }]);

Comment: sorry I didn't notice that there is a mistake see the update
Answer: i Think the cause of this error is the lecturerFac variable is not initialize in the factory. Create an empty object call lecturerFac in the factory and return it.
todoApp.factory('lecturerFac', ['$http', function($http) {
    var urlBase = '/api/lecturer';
    var coursesFac = {};

    var lecturerFac= {};/////////////////////

    lecturerFac.getLecturer = function() {
        return $http.get(urlBase);
    };
    lecturerFac.getLecturerByName = function(name) {
        return $http.get(urlBase + '/' + name);
    };
    return lecturerFac;
}]);

Also avoid calling functions inside the ng-model. When you bind something with ng-model it must be available for both reading and writing - e.g. a property/field on an object. use ng init instead


Django: Breaking up views

Question: This is really just a "best practices" question...
I find that When developing an app, I often end up with a lot of views.
Is it common practice to break these views up into several view files? In other words... instead of just having views.py, is it common to have views_1.py, views_2.py, views_3.py (but named more appropriately, perhaps by category)?
Answer: Splitting views.py
Most of your code probably expects your views to be accessible as myapp.views.viewname.  One way I've seen people break up their views but keep this python name is to create a views/ directory.  views/__init__.py will have:
from .foo_views import *
from .bar_views import *
from .baz_views import *

Then, in views/foo_views.py, put:
def foo_detail(request, ...):
    # your code here

def foo_list(request, ...):
    # your code here

def your_other_view(...):
    # ...

etc.  So you move everything from views.py into files in this directory, make __init__.py, delete views.py, and you're done.
Then, when you import myapp.views, myapp.views.foo_detail will refer to the function that you defined in views/foo_views.py.
Splitting other modules
This strategy should also work fine for admin.py, etc.  But if you want to split up models.py like this, you will need to add app_label = 'your_app_name' to the class Meta: of all of your models.  For example, unicorn_app/models/unicorns.py could have an entry like this:
class Unicorn(models.Model):
    description = models.CharField(max_length=80)

    class Meta:
        app_label = 'unicorn_app'

(Otherwise, Django imagines that the Unicorn model is part of a Django app named "models", which messes up the admin site.  Current through 1.6 - the upcoming 1.7 release will remove this requirement.)
Comment: You can do relative imports.  I've never tried them and they seem a bit tricky, but here's a relevant SO question:  http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python
Comment: Addendum- the directories with `__init__.py` files are called "packages".
Comment: I like this approach. The only problem is that now I need to put full paths when I import other things from the app. For example, before I could do "from models import *". Now I need to do "from project.app.models import *". Is there any way to fix that?
Comment: I realize this is a kinda old answer. But another question.
"""So you move everything from views.py into files in this directory, make __init__.py, delete views.py, and you're done.

Then, when you import myapp.views, myapp.views.foo_detail will refer to the function that you defined in views/foo_views.py."""

Does this create any kind of performance hit by importing then importing, etc ?
Comment: Python modules are cached, so while it might be a tiny bit slower each time your app is restarted, it should be just as fast after that.  But any difference should be quite small compared to other design decisions that you make when building a web app.
Comment: Awesome.   Tidy, elegant ... I don't know why it's not "the recommended way of doing it", in the tutorial etc!
Answer: As a general guideline, think about readability and maintainability: the default "views.py" is just a suggestion made by initial scaffolding - you do not have to stick to it.
Usually, files with thousands of lines of code are difficult to maintain, for this I usually try to decompose bigger modules into smaller ones.
On the other hand, the division should make sense - splitting related functions into several files, with lots of imports may make maintenance even more difficult.
Finally, you can also think about completely other ways to simplify your application.
Do you see duplicated code? Maybe some functionality could be moved in a completely different application? And so on.
Answer: Another option would be to move some of the functionality into one or more apps. This would allow you to move also forms and templates and keeping things structurized. You don't necessarily need to move the models which saves you from model and data migration.
For example you could have the following structure:
main_app/
  |_models.py
  |_views.py
  |_forms.py
  |_urls.py
  |_templates/

sub_app_1/
  |_views.py
  |_forms.py
  |_urls.py
  |_templates/

sub_app_2/
  |_views.py
  |_forms.py
  |_urls.py
  |_templates/

Comment: I recognize what the other guy is saying, but I like this more.  It makes complete thoughts between subject matter in your app.  +1  Thanks.

Django: Breaking up views


LINQ Union not returning wanted results

Question: I have problem I've been trying to solve for the last couple of hours but without any luck at all.
First, let me show you how my database looks like (just an important part of it):

[radno_mjesto] = JOB
[grupa_radnih_mjesta] = JOB GROUPS (jobs that fall into specific groups; for example if the group name was judges jobs that would fall into this group would be: supreme court judge, administrative law judge, senior judge, etc.)
[osoba] = PERSON
What I'd like to achieve is to query all the people who fall into specific job groups, but after couple of hours I wasn't able to succeed in doing it so. I was trying various combinations of the following code and there are only 2 results I've been getting: all people (no matter what their job is) or people with specific job only (the last job from the job group as in this case).
<code>        var sveOsobe = from p in db.osobas
                       select p;

        if (chkGrupaRadnihMjesta.Checked)
        {
            int id = Convert.ToInt32(GrupaRadnihMjesta.SelectedValue);

            var radnaMjesta = from rm in db.grupe_radnih_mjesta_radna_mjesta
                              where rm.grm_id == id
                              select rm;

            var praznoOsobe = sveOsobe.Where(o => o.osoba_id == -1);

            foreach (var radnoMjesto in radnaMjesta)
            {
                var sveOsobeRadnaMjesta = from p in db.osobas
                                          where p.osoba_id == -1
                                          select p;

                sveOsobeRadnaMjesta = sveOsobe.Where(o => o.rm_id == radnoMjesto.rm_id).Union(sveOsobeRadnaMjesta);
                praznoOsobe = praznoOsobe.Union(sveOsobeRadnaMjesta);
            }
            sveOsobe = sveOsobe.Intersect(praznoOsobe);
        }
</code>
Any help would be appreciated.
Comment: You know you don't need to use the same exact names in your LINQ contexts that are used in the databases, you can give tables and columns _meaningful_ names and still map to the obfuscated names.  Do yourself (and us) a favor and do that. It is terribly difficult to even understand what your code is doing.
Comment: It is not your fault but the names are hard to remember for a person not familiar with your language. It looks like a substitution cipher has been applied. Maybe you can translate them?
Comment: Actually, this project is something that I had inherited from a third person. Personally, I do use shorter table names.
Answer: This should work....
<code>if (chkGrupaRadnihMjesta.Checked) {
  int id = Convert.ToInt32(GrupaRadnihMjesta.SelectedValue);
  var sveOsobe = (
    from p in db.osobas
    join l in db.grupe_radnih_mjesta_radna_mjesta on l.rm_id equals p.rm_id
    where l.grm_id == id
    select p
  ).Distinct();
}
</code>
I'm guessing at names here!!!
Comment: Thank you, that was the solution!

LINQ Union not returning wanted results


argument to pgrep from cmdline returns 2 PID's and argument from global variable value returns 1 PID

Question: 1.first case(processName as argument from cmd i.e java)
command from cmd with arguments : ./a.sh getProcessId contains java
code:
<code>getProcessId(){

matchType=$1
#defaulting matchArg to x i.e exact match
matchArg=x
processName=$2

if [[ $matchType == 'contains' ]];then
  matchArg=f
elif [[ $matchType == 'exact' ]];then
  matchArg=x
fi

if processId=`pgrep -$matchArg $processName`
then
 log $selectedLogLevel "process id fetch is successful" 1 "getProcessId"
else
 log $selectedLogLevel "process id fetched is blank" 1 "getProcessId"
fi

echo "$processId"

}
</code>
output : 2 PIDS

second case(processName as global variable i.e java))
processName='java'
getProcessId(){
<code> matchType=$1
 #defaulting matchArg to x i.e exact match
 matchArg=x

 if [[ $matchType == 'contains' ]];then
   matchArg=f
 elif [[ $matchType == 'exact' ]];then
   matchArg=x
 fi

 if processId=`pgrep -$matchArg $processName`
 then
  log $selectedLogLevel "process id fetch is successful" 1 "getProcessId"
 else
  log $selectedLogLevel "process id fetched is blank" 1 "getProcessId"
 fi

 echo "$processId"

 }
</code>

output : it returns only 1 PID which is execpted.
My requirement is pass process name from argument then it should return 1 PID only.
currently i am getting 2 PIDs
Comment: Does this answer your question? [pgrep -f from shell script is returning 2 pid instead of 1](https://serverfault.com/questions/1150221/pgrep-f-from-shell-script-is-returning-2-pid-instead-of-1)
Answer: We already answered this one here: pgrep -f from shell script is returning 2 pid instead of 1
The second PID being returned is the PID of the process running the script. To make this work you have to modify the script so that it detects its own command line, and does not return that PID.
Comment: Noted, will do so in future.
Comment: Probably best asked in one of the programming areas. It's really kind of off topic in ServerFault.
Comment: Then just comment it so we can close the question as a duplicate. No need to duplicate answers.
Comment: "To make this work you have to modify the script so that it detects its own command line, and does not return that PID."  -> my question is  need help on this .. wat changes  i need to do in script so it return 1 PID only  in case 1


O que é o "Bun"?

Question: Hoje me deparei com uma novidade em uma rede social, mencionando o Bun,  descrito como:

O mais novo e performático runtime JavaScript...

Comumente eu vejo essa imagem sendo compartilhada e demonstrando a "performance absurda" desse runtime bun:

Creio que muitos já tenham conhecimento que performance não é o único critério levado em consideração para se escolher qual linguagem usar para alguns tipos de projetos.
O Bun, pelo que entendi, vem se demonstrando uma alternativa ao deno e ao já experiente de guerra node e pelo pouco que sei, ele meio que se baseou em algumas coisas do deno como
por exemplo suporte nativo ao TypeScript. Ainda sim, eu pergunto:

O que difere este novo runtime dos demais já existentes (Deno e Node.js)?
Ele tem algo que possa ser considerado revolucionário e que possa ser motivo de ocupar o lugar do Node.js?

O projeto teve sua versão 1.0 lançada em 08/09/2023.
Comment: O tal Bun parece mesmo promissor, o melhor dele não é exatamente a velocidade, mas sim o suporte nativo a uma série de coisas, não chega a ser revolucionário, mas é o grande diferencial, como [respondi](https://pt.stackoverflow.com/a/558802/3635). No entanto não dá para afirmar que em 5 ou 50 anos isso vai ser algo bom ou adotado pela comunidade, você pode notar como parte dos devs no mercado só seguem o que é dito como moda, não porque é bom.
Answer: Respondendo ao titulo, é um programa capaz de executar JavaScript, no entanto faz muito mais do que isso, como transpilar outras linguagens e uma série de ferramentas nativas. Basicamente um concorrente do Node.js e Deno que promete ser muito mais performático, como demonstrado na imagem que anexou a pergunta.

O que difere este novo runtime dos demais já existentes (Deno e Node.js)?

O suporte nativo a uma série de recursos comuns hoje em dia, que dispensarão recursos extras/externos, sendo provavelmente a diferença mais relevante.
Algumas das diferenças internas do Node.js e Deno em comparação ao Bun, é que ao invés de usar o motor V8, o Bun usa o framework JavaScriptCore (também usado pelo motor Webkit). Ele é escrito em boa parte em Zig (como pode observar no repositório), com algumas partes variando entre c ou c++.
Não é possível enumerar todas compatibilidades e incompatibilidades dos 3 em uma única resposta, ficaria uma resposta extremamente longa, e mesmo que tentasse enumerar é provável que algo ficaria faltando, mas no site oficial temos uma página dedicada a mostrar a compatibilidade do Bun com o Node.js:

https://bun.sh/docs/runtime/nodejs-apis#node_compressionstream

Sendo um projeto beta (atualmente na versão 0.1.3 em 12/07/2022) isso faria a resposta se tornar desatualizada e incorreta em meses, é melhor aguardamos para afirmar qualquer coisa, principalmente uma melhora na documentação do Bun, que não me parece algo bom ainda. Recomendo por enquanto acompanhar o roadmap: https://github.com/oven-sh/bun/issues/159

Ele tem algo que possa ser considerado revolucionário e que possa ser motivo de ocupar o lugar do Node.js?

Como disse antes, o suporte nativo a uma série de recursos comuns hoje em dia, e é o que difere ele dos demais. Não chega a ser revolucionário, mas é o fator que com certeza é o que torna o projeto promissor.
Recursos nativos:

Gerenciador de pacote compatível com NPM (o que não garante que qualquer pacotes irá funcionar corretamente)
Variáveis env carregam automaticamente, usando process.env e Bun.env (dispensando o dotenv)
Transpilador Typescript e JSX
Algumas bibliotecas (ou muitas) comuns em outros lugares, como fetch(), WebSocket e URL
Executor de tarefas para scripts via package.json
"paths" no tsconfig.json é suportado nativamente, juntamente com exports em package.json
Ferramenta semelhante ao WebPack

Os loaders irão resultar em:

Entrada
Loader
Saída

.js
JSX + JavaScript
.js

.jsx
JSX + JavaScript
.js

.ts
TypeScript + JavaScript
.js

.tsx
TypeScript + JSX + JavaScript
.js

.mjs
JavaScript
.js

.cjs
JavaScript
.js

.mts
TypeScript
.js

.cts
TypeScript
.js

.toml
TOML
.js

.css
CSS
.css

.*
file
string

O .env não resulta em saída e o outros formatos resultam em file. Note que file substitui a importação por um URL (ou um caminho).

Até o momento as APIs fs, path, e process do Node.js estão apenas parcialmente implementadas, então pode ser que alguns pacotes NPM ou códigos existentes não irão funcionar corretamente.

Eu poderia citar uma série de coisas especificas, com exemplos, mas isso seria levar a pergunta a situações opinativas ou muito longas, e é muito cedo para falar qualquer coisa sobre isso (recomendo formular perguntas especificas se surgir alguma dúvida sobre recursos específicos).
Em resumo é isso que é o melhor do Bun, suporte nativo a muitas coisas que é comuns em frameworks e ferramentas usadas hoje em dia. Chega a ser revolucionário? Não considero, mas considero ainda sim como ótimo.

Nota: não relacionado diretamente ao Bun, Node.js ou Deno, mas se formos falar de algo revolucionário no mundo JavaScript, independente do motor, me parece que até agora é o WebAssembly.
Comment: @CmteCardeal eles usam o JavaScriptCore no lugar do V8, o Zig é a linguagem que escolheram para escrever. JavaScriptCore é o motor/framework usado no Webkit: https://github.com/WebKit/WebKit/tree/main/Source/JavaScriptCore. Exemplo de navegador que o usa o Webkit é o Safari.
Comment: Uma coisa que eu achei interessante, é que ele não usa o V8 como o Node ou Deno fazem. Ele tem um interpretador escrito na linguagem `Zig`, o que pra mim suou esquisito de cara, pois nunca tinha ouvido falar. Nem sabia que existia algo aqui no SOpt, mas vou dar uma pesquisada melhor e tentar entender o que essa linguagem tem de tao especial pra ter sido escolhida no lugar de C ou Rust...
Comment: Boa, isso explica melhor. Achei que tinha sido escolha do criador do bun.
Comment: @CmteCardeal em boa parte é escrito em Zig, mas tem partes escritos em C e C++ (detalhes: https://i.stack.imgur.com/nlVDz.png). Provavelmente escolheram o Zig para facilitar escrever e ao mesmo tempo por uma performance boa (não fiz um benchmark para saber de fato os detalhes, é o segundo projeto que vejo usando Zig).

O que é o "Bun"?


Adding and deleting a clone in jQuery?

Question: I've managed to get my adding a clone button working but im now having trouble with getting the delete button to work. Wondering if people can see the problem im guessing im totally wrong.
This is the code in jsfiddle
http://jsfiddle.net/AFfa2/

                    20. Details of Children

                        Family Name

                        Given Names

                        Sex

                        Date of Birth

                        Country of Birth

                    <input type="text" name="children" class="textbox">
                    <input type="text" name="children" class="textbox">
                    <input type="text" name="children" class="textbox">
                    <input type="text" name="children" class="textbox">
                    <input type="text" name="children" class="textbox">

                        <input type="button" value="Add Child Info">

                        <input type="button" value="Delete Child Info">

$("#addChild").click(function(){
        var newElement =$('
').html($("#question20").html());
        newElement.addClass('input');
        $("#question20").after(newElement);
    });

    $("#deleteChild").click(function() {
    if(childId > 0) childId--;
    $("#child"+childId).slideUp();
    if ($("#deleteChild").css("display") == "none") $("#deleteChild").slideUp();
    });

Comment: you want to delete the last div?
Comment: The add button adds the Question20 div then i want to be able to delte the div that was just added
Answer: Try this Answer
$("#addChild").click(function () {
            var newElement = $('
').html($("#question20").html());
            newElement.addClass('input');
            $("#question20").after(newElement);
            childId++;
        });
        $("#deleteChild").click(function () {
            var div = document.getElementById('childdiv');
            if (div) {
                div.parentNode.removeChild(div);
            }

        });

Answer:   $("#addChild").click(function(){
  $(".question20:last").after($(".question20:first").clone(true));
 });

 $("#deleteChild").click(function() {
 if($(".question20").length!=1)
   $(".question20:last").remove();
});

 //and the div got class instead of id since cloning the div with same id is not good

http://jsfiddle.net/AFfa2/4/
Answer: DEMO
updated code posted by rps
as it deletes all the div elements. Modified it not delete the original form element.
$("#addChild").click(function () {
    $(".question20:last").after($(".question20:first").clone(true));
});

$("#deleteChild").click(function () {
    if ($('.question20').length > 1) {
        $(".question20:last").remove();
    }
});

Answer: Try this jsfiddle

20. Details of Children

Family Name
                    <input type="text" name="children" class="textbox">

Given Names
                    <input type="text" name="children" class="textbox">

Sex
                    <input type="text" name="children" class="textbox">

Date of Birth
                    <input type="text" name="children" class="textbox">

Country of Birth
                    <input type="text" name="children" class="textbox">

                            <input type="button" value="Remove Child Info">

                <input type="button" value="Add Child Info">

jQuery code
    $("#addChild").click(function(){
    var newElement =$('
').html($("#question20").html());
    newElement.addClass('input');
    $("#question20").after(newElement);
});

$('#removeChild').click(function(){
    $(this).parent().remove();
});

Answer: This might work
$("#deleteChild").click(function() {
    $('#question20').parent().children('.input:last').remove();
});

http://jsfiddle.net/HLpJP/
You've got issues around where your inserting the new rows however. Your inserting new rows after question20, these will appear before existing ones. The remove method will remove the last one so might not be the behaviour you want.
Answer: Here is jsfiddle link : http://jsfiddle.net/AFfa2/5/
add remove button

                <input type="button" value="Remove Child Info">

and jquery
    $("#removeChild").click(function(){

$('div.input').get($(this).length).remove();
});
you need to change buttons div classes

Adding and deleting a clone in jQuery?


Flutter Acessibilidade - O rótulo deste item pode não ser lido por leitores de tela. - Tela/VIew

Question: Olá! Estou com uma dúvida de acessibilidade com flutter para android. Alguém pode me dar uma mãozinha? Estou tentando subir um app na loja (android) mas estou recebendo relatórios de erro de acessibilidade. Sâo uns 700 erros iguais, dizendo:
O rótulo deste item pode não ser lido por leitores de tela.
O item marcado é a tela inteira.
O rótulo deste item pode não ser lido por leitores de tela.
Eu baixei um Scaner de Acessibilidade e deu exatamente a mesma coisa. No código eu tentei colocar "Semantics" com "label" em tudo quanto é canto, mas o erro persiste.
Answer: Para adicionar opções de acessibilidade para leitores de tela, você pode seguir a documentação oficial do Flutter sobre acessibilidade.
Para o problema em questão (mensagem "O rótulo deste item pode não ser lido por leitores de tela."), você pode resolver adicionando a seguinte linha de código antes da função runApp do Flutter:
RendererBinding.instance.setSemanticsEnabled(true);

Meus apps publicados na Play Store sempre deram o mesmo erro/aviso, e isso resolveu.
Comment: Caso seu app contenha Widgets não padrão do Flutter (algum que você mesmo criou com base em outros Widgets), você pode usar o [Semantic Class](https://api.flutter.dev/flutter/widgets/Semantics-class.html) para definir manualmente a descrição do Widget (confirme está na documentação).
Answer: For Flutter 3.10.0 and further
SemanticsBinding.instance.ensureSemantics();


Shifting parameter orders confusion - Recursive Function

Question: Working on Towers of Hanoi - Trying to understand shifting parameter order in a recursive context.
I'm able to trace the stack for the most part, but check out the code below. I don't understanding why the original def (fr, to) order is printed when n-1 is used in the else call, but switches to the new (spare, to) order when 1 is used. Why doesn't it print the (spare, to) order either way?
More generally, first one prints 'move from P1 to P2' but second one prints 'move from P3 to P2' - why?
def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
    if n == 1:
        printMove(fr, to)
    else:
        Towers(n-1, spare, to, fr)

print(Towers(3, 'P1', 'P2', 'P3'))
                #fr    #to   #spare

def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
    if n == 1:
        printMove(fr, to)
    else:
        Towers(1, spare, to, fr)

print(Towers(3, 'P1', 'P2', 'P3'))
                #fr    #to   #spare

I expected both instances of code to print 'move from P3 to P2' because I thought in both else calls of Towers the (spare, to, fr) order would replace the original def order, but it alternates between the two depending on whether 1 or n-1 is used as the first parameter.
Comment: 20 years ago, I too asked similar question. Based on my experience, I'd like to suggest (1) you play with actual rings (or at least sheets of paper cut in different sizes with numbers on top) -- remember how you moved the rings and (2) trace your program (or run and observe) and see if it is similar to how you move.

Change your program until the movement matches.
Comment: Because you call the function recursively with the arguments in a different order: `Towers(n-1, spare, to, fr)`
Answer: The first part of code would simply switch the poles until you get the original order, which is why you're getting move from P1 to P2 in the first time.
Executing your second example does print move from P3 to P2. This is because, n != 1 then it replaces the spare and then the spare is now the from and the to remains the same.
This is not a complete part of code for Towers of Hanoi. The Towers of Hanoi would have you print each time a disk moves.
To understand the algorithm, it might take you a while (as it did for me) but I'll try my best:
How would you move n disks from the first pole to the second pole using the third pole as an helper? You could look at it like this - If you had a solution to move all but the last (largest) disk to the third pole (in the correct order), then you could move the last disk to the second pole and then move the entire third pole onto the second and you're done. Going by the same idea recursively, we can get the following code:
def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
    if n == 1:
        printMove(fr, to)
    else:
        Towers(n-1, fr, spare, to)
        printMove(fr, to)
        Towers(n-1, spare, to, fr)

So what we have, if you try to "read it out loud", is this:

Move the first n-1 disks from fr to spare using the to pole
Move the largest disk from the fr pole onto the to pole
Move all the original n-1 disks that we moved from spare to to

Note - You don't need to use print when applying the Towers function, it doesn't return anything and simply prints as it is.
Comment: I just wanted to use an altered version of the full code to illustrate my question. I understand the algorithm conceptually, and was even able to trace the stack but I always get the prints wrong. I don't understand why these two bits of code would print two different things, given that from what I can tell in both cases printMove is called by a Towers with the same parameters - I feel like this must be where I'm going astray?
Comment: As I wrote - in the first example, you're simply calling the towers function each time with a switch in the 'spare' and 'fr' parameters - Doing 2 switches (One for `n=3` and another for `n=2`) will restore the "original" order of the poles and then print the `move from P1 to P2`. In the second example, you're only switching it once (Then you call the function with `n=1` which will stop switching) and then you get `move from P3 to P2`
Comment: Thanks. It's that oscillation I still don't really understand. I was thinking in the first example the spare / fr switch would simply happen on the first else call and then repeat. Is a (spare, to, fr) call 'switching' the next (spare, to, fr) somehow? I know I'm going to feel super dumb when it finally makes sense to me.
Comment: Well, yes. If you write down the actual order of invocation of functions then it's `1. Towers(3, 'P1', 'P2', 'P3')` which goes to the `else` clause, then `2. Towers(2, 'P3', 'P2', 'P1')`, which also goes to the `else` clause, then `3. Towers(1, 'P1', 'P2', 'P3')`, which goes to the `if` clause which prints `move from P1 to P2`


Google Analytics (V4) OnCreate Cannot cast from Application

Question: I have followed a better tutorial than the google one to start to get analytics in my app.
The problem is that
package com.sgdva.ishikawa;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import java.util.HashMap;

public class Ishikawa extends Activity {

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.sources, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.action_settings:
        startActivity(new Intent(Ishikawa.this, Sources.class));
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

// The following line should be changed to include the correct property id.
private static final String PROPERTY_ID = "UA-50596309-1";

// Logging TAG
private static final String TAG = "Ishikawa";

public static int GENERAL_TRACKER = 0;

public enum TrackerName {
    APP_TRACKER, // Tracker used only in this app.
    GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg:
                    // roll-up tracking.
    ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a
                        // company.
}

HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

public Ishikawa() {
    super();
}

synchronized Tracker getTracker(TrackerName trackerId) {
    if (!mTrackers.containsKey(trackerId)) {

        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
        Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics
                .newTracker(R.xml.app_tracker)
                : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics
                        .newTracker(PROPERTY_ID) : analytics
                        .newTracker(R.xml.ecommerce_tracker);
        mTrackers.put(trackerId, t);

    }
    return mTrackers.get(trackerId);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get a Tracker (should auto-report)
    ((Ishikawa) getApplication())
    .getTracker(Ishikawa.TrackerName.APP_TRACKER);

    setContentView(R.layout.activity_ishikawa);

In this line
((Ishikawa) getApplication()).getTracker(Ishikawa.TrackerName.APP_TRACKER);
It says:Cannot cast from Application to Ishikawa
I have read that this is because my android name is not delcared in my manifest.xml but it is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sgdva.ishikawa"
android:versionCode="2"
android:versionName="1.1" >

<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:name="com.sgdva.ishikawa.Ishikawa"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
>

<meta-data android:name="com.google.android.gms.analytics.globalConfigResource"
android:resource="@xml/global_tracker" />
<activity
android:name="com.sgdva.ishikawa.Ishikawa"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.sgdva.ishikawa.Machine"
android:label="@string/title_activity_machine"
android:screenOrientation="portrait" >
</activity>
<activity android:name="com.google.android.gms.ads.AdActivity"              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|s    mallestScreenSize"/>
<meta-data android:name="com.google.android.gms.version"
                   android:value="@integer/google_play_services_version" />
<activity
        android:name="com.sgdva.ishikawa.MainActivity"
        android:label="@string/title_activity_main"
        android:screenOrientation="portrait">
    </activity>
</application>
</manifest>

Why would this happen?
Answer: It was my bad, I was calling my "activity" as an "application"
((Ishikawa) getApplication()).getTracker(Ishikawa.TrackerName.APP_TRACKER);
I made another .class called "Tracker.java" get the code for analytics there and referenced it instead:
((Tracker) getApplication()).getTracker(Tracker.TrackerName.APP_TRACKER);


Constructor is already defined in class

Question: I am beginning to learn java, and am coding a simple hockey statistics class. It looks like this:
public class Player
{
    private int games;
    private int goals;
    private int assists;
    private char position;

    public Player()
    {
        games = 0;
        goals = 0;
        assists = 0;
        position = 'X';
    }

    public Player(int initialGames, int initialGoals, int initialAssists,
    char initialPosition )

    {
        games = initialGames;
        goals = initialGoals;
        assists = initialAssists;
        position = initialPosition;

    }

    public void setPlayer(int newGames, int newGoals, int newAssists, char
newPosition)
    {
        games = newGames;
        goals = newGoals;
        assists = newAssists;
        position = newPosition;

    }

    public Player(int initialGames)
    {
        games = initialGames;
        goals = 0;
        assists = 0;
        position = 'X';
    }

    public void setGames(int newGames)
    {
        games = newGames;
    }

    public Player(int initialGoals)
    {
        games = 0;
        goals = initialGoals;
        assists = 0;
        position = 'X';
    }

}

Now, this all compiles fine until I enter the code for the last block. When I try to compile it, I get this error:
(Player.java:52 error: constructor Player(int) is already defined in class Player)
What am I doing wrong? I am following the format of my textbook quite closely to build this class, but I keep running into this error. Can anyone give me a reason why this is happening? Because I do not fully understand this compiler error.
Comment: `public Player(int initialGames)` and `public Player(int initialGoals)` are essentially the same constructor - type remains same and name doesn't matter
Comment: Better saying you can't have two constructor with a same parameter TYPE. so you have two with one int parameter, no matter the name
Comment: You defined the constructor twice `public Player(int initialGames)` check your code
Answer: You have not overloaded properly.
You have 2 constructors with same signature.
public Player(int initialGoals)
    {
        games = 0;
        goals = initialGoals;
        assists = 0;
        position = 'X';
    }

and
public Player(int initialGames)
    {
        games = initialGames;
        goals = 0;
        assists = 0;
        position = 'X';
    }

So one quick solution will be merging the both constructors.
public Player(int initialGoals, int initialGames)
    {
        games = initialGames;
        goals = initialGoals;
        assists = 0;
        position = 'X';
    }

Have a single constructor and pass zero instead when the param is not available.
For ex
Player p = new Player(5,0); // games 0
Player p = new Player(0,5); // goals 0

Answer: You duplicated the constructor, the compiler can not decide which one of those you want to call when typing new Player(8):
public Player(int initialGoals)
public Player(int initialGames)

Try calling new Player() from a new set of methods
static Player NewPlayerFromGoals(int initialGoals){...}
static Player NewPlayerFromGames(int initialGames){...}

And call it with
Player p = Player.NewPlayerFromGoals(8);

Answer: public Player(int initialGoals)
{
    games = 0;
    goals = initialGoals;
    assists = 0;
    position = 'X';
}

and
public Player(int initialGames)
{
    games = initialGames;
    goals = 0;
    assists = 0;
    position = 'X';
}

Have the same signature Player(int).
So you should change your constructors or delete one.
EDIT (I add more code for clarify)
Method 1:
enum ConstructorType {
 GOAL,
 GAME
}

public Player(int value, ValueType type)
{
    switch(type){
      case GOAL:
goals = value;
        break;
      case GAME:
games = value;
         break;
default:
break;
    }
this(games, goals, 0, 'X'); // Prefer this one instead of repeat your constructor code.
}

Method 2:
public Player(int initialGoals, int initialGames)
{
this(initialGames, initialGoals, 0, 'X');
}

Comment: So if I want both, I have to put them in the same constructor?
Comment: @DavidM I've just edit my answer with some example code.
Answer: Multiple constructors with the same parameters aren't allowed. When creating multiple constructors have one main constructor build an object with every possible parameter. If an object is allowed to be created with less parameters then create another constructor which calls the main constructor.
public Player(int games){
    this(games, 0, 0, 0);
}
public Player(int games, int goals, int assists, char position){
    this.games = games;
    this.goals = goals;
    this.assists = assists;
    this.position = position;
}

More constructors can be created to accommodate more parameters using the same format as the first constructor.
Answer: You can't define constructors with same parameter type. And in this case, I think you should use your first constructor + setters instead of define many constructors with just one parameter.
public class Player  {
   private int games;
   private int goals;
   private int assists;
   private char position;

   public Player() {
    games = 0;
    goals = 0;
    assists = 0;
    position = 'X';
   }

   public Player(int initialGames, int initialGoals, int initialAssists,
   char initialPosition ) {
       games = initialGames;
       goals = initialGoals;
       assists = initialAssists;
       position = initialPosition;
   }

   // SETTER
   public void setGames (int games) {
      this.games = games;
   }

   public void setGoals (int goals) {
      this.goals= goals;
   }
}

And then:
Player playerA = new Player();
playerA.setGames(1);

Player playerB = new Player();
playerB.setGoals(2);

Constructor is already defined in class


On invertibility of $A+E$ where $||E||_2<$ smallest singular value of $A$ and $||A^{-1}E||_2<1$

Question: Let $A,E \in M_n(\mathbb C)$ . Suppose $\sigma_\min >0$ be the smallest singular value of $A$ and $||E||_2 < \sigma_\min$. Suppose $||A^{-1}E||_2 <1$. Then how to show that $A+E$ is invertible ?
My work : Going by contradiction; assume ,if possible, $\det (A+E)=0$, then $\det (I+A^{-1}E)=0$. So $-1$ is an eigenvalue of $A^{-1}E$, so $1=|-1|\le ||I+A^{-1}E||_2$, so $||A^{-1}E||_2 <1 \le ||I+A^{-1}E||_2$ ; but I am unable to proceed further.
Please help.
NOTE: Here $||M||_2:=\sup_{||x||_2=1}||Mx||_2=\sigma_\max$
Answer: Suppose that $(A+E)(x)=0$, $x\neq 0$, this implies that $A(x)=-E(x)$ and $x=-A^{-1}E(x)$, we deduce that $\|x\|=\|A^{-1}E(x)\|\leq \|A^{-1}E\|\|x\|<\|x\|$. Contradiction. This implies that $Ker(A+E)=\{0\}$ and $A+E$ is invertible.
Comment: ah, so simple ... I was thinking the wrong way ... thanks !


Working with Equivalence Classes and Quotient Sets

Question: I have a doubt about working with equivalence classes and quotient sets. The definition that I know, is that given an equivalence relation $\sim$ on a set $A$, the set of all elements of $A$ equivalent to a certain element $x$ is the set $\left[x\right]\subset A$ which is called the equivalence class of $x$. The set of all equivalence classes is then the set $A/\sim$ called quotient set.
Well, I understand this. However I'm a bit confused when working with this, because the set $A/\sim$ is a set of sets right? So if $x \in A/\sim$, $x$ is not an element of $A$ but one entire collection of such elements. However, there're texts that it seems that the author is thinking of $x \in A/\sim$ as just and element of $A$.
For instance: in the context of manifolds, when defining tangent vector as equivalence classes of curves, one doesn't think of an element of the tangent space as a set of curves. Or on the context of multilinear algebra, we define the tensor product of vector spaces using one quotient, but we don't think of the elements as sets of vectors.
I've heard that "we think of an element $x \in A/\sim$ as an element subjected to the relation $\sim$", however, we are thinking of $x$ related to what element of $A$ ? I really didn't get the way that we should work/think about equivalence classes and quotient sets.
Thanks in advance for your help, and sorry if the question is to silly.
Answer: Usually when you talk about an equivalence class in a quotient set, you refer to it by using a representative, i.e. an element of that class. For example, consider $\Bbb Z/n\Bbb Z$, the integers modulo $n$. This is defined as a set of sets, but usually you just identify it with $\{0,\dotsc,n-1\}$.
Comment: The identification arises by [transporting the structure](http://math.stackexchange.com/search?q=user%3A242+transport+structure) of $\,\Bbb Z/n\Bbb Z\,$ to the complete system of representatives (a.k.a. normal forms or canonical forms), see esp. [this answer.](http://math.stackexchange.com/a/118922/23500)
Comment: @MathGems Nice, if long, answer. Thanks.
Answer: It might be (and usually this is the case) that all elementary mathematical objects are, in fact, sets. For example take the real line $\mathbb R$. You know that $\pi$ is an element of $\mathbb R$. But in many axiomatization $\pi$ is itself an equivalence class (namely the set of all sequences of rational numbers converging to it). This might sound strange but doesn't change our imagination of $\pi$ being a number or a point in the real line.
Actually it might be that all mathematical objects are sets. For example one can define natural numbers as $0=\{\}, 1=\{0\}, 2=\{0,1\}\dots$
Comment: I'll do you one better. In ZFC, the class of *all sets* is constructible using only the empty set! This construction is called the *Von Neumann Universe*, and is can be shown that every set is just a nesting of the empty set.


Need help running a compiler with input types

Question: I'm working on combining multiple files with data in them to put it into one big file. I've found the compiler we need on Github here: https://github.com/AndyTWF/sector-file-compiler however I've never worked with this before or even the programming language it is in. This would help us a ton instead of copy-pasting the data one by one as we've got over 100+ files to combine.
I understand that it needs a config.json file which I have configured however I do not know where to specify the path of that file in the CompilerCLI files(?). I also want to know how I can specify where the output files will be.
The repo with the input files that are supposed to be mentioned in the .json file is in this repo https://github.com/VATFrance/FR-Sector-File
I'm a total newbie to this type of stuff so help would be appreciated!
P.S: I have Visual Studio installed already.
Answer: Try by adding this flags in your command line to setup configuration file and output
Path to the compiler configuration JSON file :
<code>--config-file [arg]
</code>
Where the output file for the EuroScope ESE should be generated :
<code>--out-file-ese [arg]
</code>
Where the output file for the SCT should be generated :
<code>--out-file-sct [arg]
</code>


xcopy & robocopy - Encrypted during transfer?

Question: I need to transfer some files on some windows hosts, as i come from the unix side, i searched for a tool similar to scp or rsync. I came across xcopy and robocopy and searched the manuals for a hint if the filestream is encrypted or not.
The only thing i found is the /EFSRAW switch of robocopy, which lets you transfer encrypted files.
Before i turn on my wireshark, let me ask the question to the Windows guys: Do this tools encrypt the transfer or not?
Comment: In the same forest, it's easy to have the servers use Kerberos based IPsec (it's literally a few mouseclicks)
Comment: Are the servers in the same forest?
Comment: Yes. They are in the same forest
Answer: Robocopy and xcopy do not encrypt their connections.  You can, of course, run them over a VPN connection or something like that.
Comment: That's correct, they massively pre-date the days where copying over internal networks was considered to require encryption and the Internet was a distant dream :)


Errors after updating phpMyAdmin

Question: After updating phpMyAdmin to v4.7.5 on my Apache/2.4.10 (Debian) I'm getting:

The phpMyAdmin configuration storage is not completely configured,
  some extended features have been deactivated. Find out why.  Or
  alternately go to 'Operations' tab of any database to set it up there.

This is what's not OK:
https://image.ibb.co/jW3fOG/Bildschirmfoto_2017_11_14_um_17_18_34.png
I added the following in /etc/phpmyadmin/config.inc.php:
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';

But after reboot it's still the same, still the same errors.
What am I doing wrong? What can I do?
Answer: This is how I solved it:
Added the following lines to /etc/phpmyadmin/config.inc.php ($cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches'; but maybe doesn't matter where in config.inc.php):
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';

Then I created a file called import.sql with the content from here: https://github.com/phpmyadmin/phpmyadmin/blob/master/sql/create_tables.sql
Then I rebooted and ready!
The errors don't appear any more!
Comment: You've got the right idea, although there's no need to reboot after those steps. `create_tables.sql` is also included with the official phpMyAdmin download.
Answer: Since you seem to be using the Debian packaged version, you should be able to sort it with dpkg-reconfigure -plow phpmyadmin.
The solution you used is what I'd normally suggest, but the Debian package should handle such things for you easier than doing it manually. Either solution should work fine for your purposes.

Errors after updating phpMyAdmin


C++11 - Managing worker threads

Question: I am new to threading in C++11 and I am wondering how to manage worker threads (using the standard library) to perform some task and then die off. I have a pool of threads vector<thread *> thread_pool that maintains a list of active threads.
Let's say I launch a new thread and add it to the pool using thread_pool.push_back(new thread(worker_task)), where worker_task is defined as follows:
void worker_task()
{
    this_thread::sleep_for(chrono::milliseconds(1000));
    cout << "Hello, world!\n"
}

Once the worker thread has terminated, what is the best way to reliably remove the thread from the pool? The main thread needs to run continuously and cannot block on a join call. I am more confused about the general structure of the code than the intricacies of synchronization.
Edit: It looks like I misused the concept of a pool in my code. All  I meant was that I have a list of threads that are currently running.
Comment: ftp://kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html read this before you think about constructing your thread pool architecture.
Comment: What's the purpose of a _thread pool_ if each thread only executes one task?
Comment: Related: [How to check if a std::thread is still running?](http://stackoverflow.com/q/9094422/873025).
Comment: That's not what "pool" means...
Comment: @nosid I simplified the situation for the sake of the question. The threads I am creating will not be as short as the worker_task function I showed above, and I need to be able to display what all the threads are working on at any given time. The thread_pool actually won't contain a list of thread objects, but will contain metadata associated with each thread.
Comment: @nosid OP never wrote that, it is a "pool of thread" not a "thread pool", OP also stated "to perform some task and then die off" which is a statement that suggests that OP is not interested in a "thread pool" approach anyway.
Answer: You can use std::thread::detach to "separate the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits."
If each thread should make its state visible, you can move this functionality into the thread function.
std::mutex mutex;
using strings = std::list<std::string>;
strings info;

strings::iterator insert(std::string value) {
    std::unique_lock<std::mutex> lock{mutex};
    return info.insert(info.end(), std::move(value));
}

auto erase(strings::iterator p) {
    std::unique_lock<std::mutex> lock{mutex};
    info.erase(p);
}

template <typename F>
void async(F f) {
    std::thread{[f] {
        auto p = insert("...");
        try {
            f();
        } catch (...) {
            erase(p);
            throw;
        }
        erase(p);
    }}.detach();
}

Comment: @Chirag: `erase` should be invoked regardless how the function terminates. However, I missed the case of successful termination. It would be better to use RAII instead.
Comment: Thanks! I didn't know about the detach function so I'll look into that. One question about your code though, how come the erase is inside a catch? Is f expected to throw an exception when it is completed?

C++11 - Managing worker threads


Two images per category at wordpress

Question: Is it possible to add multiple images for a category in wordpress?
I've seen this plugin that allows you to add a single image per category.
I would actually like to add 2 images per category. One for its header, and another one for its menu thumbnail.
Any recommendation?
Comment: You may want to use [some custom fields plugin for categories](https://wordpress.org/plugins/advanced-custom-fields-categories/)
Comment: @vard There's no image field there. I want to be easy to maintain. Otherwise I could always use the slug as a CSS selector to set the background. But that's far from ideal.
Comment: ACF is supporting images, you can use the [gallery field](http://www.advancedcustomfields.com/resources/gallery/) for example.
Answer: Yes, it can be done.
One way is a bit long, and it involves

assigning categories and taxonomies to attachments;
querying media files by taxonomy so you can output them in a custom
loop;
using special taxonomy queries for images to display them on archive pages;
adding an image to a category or taxonomy term as the category image.

.. it would require a very long answer.
But - there is a hack that would help you do it, although not as dynamic as the above one. ( although - read below it can be made dynamic as well )
what you do is basically put images with the category name like bananas.jpg, pears.jpg, apples.jpg, and then
<img src="whatever/directory/<?php $category = get_the_category(); echo $category[0]->cat_name; ?>.jpg" />

of course, in your case you would do bananas-head.jpg, pears-head.jpg, apples-head.jpg , and then bananas-footer.jpg, pears-footer.jpg, apples-footer.jpg etc etc.. you get the picture ( no pun intended ).
Of course, like said before, it is not so dynamic, but it can easily be converted to one by using special theme settings, where one upload an image for each category, and the theme just grabs the category image by taxonomy ID ...
Answer: Yes you can upload multiple images using https://wordpress.org/plugins/categories-multiple-images/ plugin. Please check and let me know.
Thanks!

Two images per category at wordpress


Generic Array creation and null pointer errors

Question: I have an array of linked list which runs parrallel to an ordered object array. If an extra element is entered into the object array i need to insert an extra element into the same space in the linked list.
I have this method as follows
public static LinkedList<User>[] insertElement (LinkedList<User>[]a, int index, User friend) {
  LinkedList<User>[] bp = new LinkedList[nElems];

  for (int i=0; i<index; i++){
     bp[i]=a[i-1];
  }
   //index is the position in which i want to insert a new element
   bp[index].add(friend);

  for (int i=index+1; i<a.length; i++){
    bp[i]=a[-1];
  }
  return bp;
}

When bp is initialised as shown I get a null pointer error
When it is initialised as:
LinkedList<User>[] bp = new LinkedList<User>[nElems];

I get a generic array creation error. What it the correct way to initialise this?
Comment: I assume that your attempt to index into a an array in the second `for` loop, `bp[i] = a[-1];`, is a typo?
Answer: You have created an array of linked lists, but you haven't created any LinkedLists within the array.
You need to create the list in each slot of the array before you try and use it.
It seems unlikely that this is what you are actually trying to do though...you seem to be mixing up Arrays and Lists. Really you should use either Collections or Arrays, not mix the two together.
Answer: This line:
LinkedList<User>[] bp = new LinkedList[nElems];

..creates an array of null references to LinkedList<User>. You must initialize these before you use them:
LinkedList<User>[] bp = new LinkedList[nElems];

for (int i = 0; i < nElems; i++) {
    bp[i] = new LinkedList<User>();
}

Answer: What I guess you are trying to do is having a ordered List of Users. If this is the case you can do this by just having a LinkedList and using
LinkedList<String> users = new LinkedList<>();
users.add( index, friend );

LinkedList.add automatically shifts all elements to the right.


Achar os múltiplos fulgaps

Question: O objetivo do programa é mostrar somente os números fulgaps de 0 a 999, número esse que deve ser divisível pela concatenação do primeiro e último número Ex: 192 / 12 ou 583 / 53.
Na compilação é mostrado todos os números de 1 a 999 e não somente os números desejados. Alguém pode me indicar qual o erro da minha lógica?
#include <iostream>

int main()
{
    int Number{ 1 };
    int FirstLastNumber = ((Number / 100) * 10) + Number % 10;
    int Result = Number % FirstLastNumber;

    for (int i = 0; i <= 999; i++)
    {
        if (Result == 0)
        {
            std::cout << Number << std::endl;
            Number++;
        }
    }
    return 0;
}

Comment: Você entende que a resposta que você aceitou não faz o que está no enunciado da pergunta?
Answer: Primeiramente você precisa refazer a conta do Result para cada nova execução de for. Da maneira que é feito atualmente isso não ocorre, nessa situação você obtêm somente uma vez um valor para Result.
int FirstLastNumber = ((Number / 100) * 10) + Number % 10;

Nessa linha você precisa diferenciar se o número é de 3 dígitos ou somente 2, pois o calculo é diferente. Sendo ele de 3 dígitos o calculo do resto no final da equação deve ser Number%100 e não Number%10 como está atualmente.
Segue um exemplo de 100 a 999 com base no seu código:
#include <iostream>

int main()
{
    int Number{ 100 };
    int FirstLastNumber;
    int Result;

    for (int i = 100; i <= 999; i++)
    {
        FirstLastNumber = ((Number / 100) * 10) + ((Number % 100) % 10);
        Result = Number % FirstLastNumber;
        if (Result == 0)
        {
            std::cout << Number << std::endl;
        }
        Number++;
    }
    return 0;
}

Answer: O problema é meio ambíguo. E o código tem muitas coisas sem sentido. O principal erro é fazer o cálculo fora do laço.
Nada foi dito sobre o que fazer quando o número tem apenas 2 dígitos e não 1. Vou considerar que o primeiro é 0. Então calculo apenas o último dígito nesses casos.
#include <iostream>

int main() {
    for (int i = 0; i < 1000; i++) {
        int FirstLastNumber;
        if (i < 100) FirstLastNumber = i % 10;
        else FirstLastNumber = ((i / 100) * 10) + i % 10;
        if (FirstLastNumber == 0 || i % FirstLastNumber == 0) std::cout << i << std::endl;
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Muito obrigado, me atentarei mais a estes detalhes e tentar ser mais específico na próxima.

Achar os múltiplos fulgaps


Vocal technique: Why is Smiling Used to Sharpen Notes?

Question: A very common technique in singing is to smile in order to brighten the tonality of a given note and raise the pitch of the note.
When it comes to raising the pitch of the note, is it the overtones or fundamental frequency being raised? My understanding is that the vocal chords determine the fundamental frequency and the second formant does not. So if smiling affects the fundamental, does it somehow then impact muscles in the throat?
In practise, without any technical discussion, smiling really does work! But in theory, from what I know, it should only impact the overtones, like how changing from an 'A' vowel to an 'E' vowel does. And then that makes me wonder, and might make me ask another question on Stack Exchange, "is a note on pitch if its fundamental frequency is way off, but its overtones are on point?"
Comment: I'd question your hypothesis, right from the outset. Smiling brightens notes, it doesn't sharpen them. If you go sharp too, it's because you haven't separated the throat functions from the mouth functions & one is directly affecting the other.
Comment: Agree with previous comments that the premise is incorrect. And to answer the hidden follow-up question Yes of course a note is out of tune if the fundamental is off. The fundamental is the primary indicator/dependency of tuning, so whilst it's a clever technical achievement to get the overtones correct, the note will sound out.
Comment: With Tetsujin on this one. Smiling will change the *tone* making it a little brighter, but shouldn't affect *pitch*. If a note is sung slightly flat, it's just as easy to change its pitch by singing it correctly.
Comment: Thanks Tetsujin, Tim, Steve for clarifying that smiling doesn't impact (or at least shouldn't) the fundamental. So then can I shift focus to overtones? I know Steve says fundamental=tuning, but there are musical edge cases where overtones reign supreme over fundamentals. There's overtone singing, where the amplitude of the first overtone can be greater than the fundamental. And of course there's stretch tuning on pianos. So would it not be reasonable to say smiling DOES sharpen note, because the overtones of the flat note can be sharpened to the correct frequency, relative to some ensemble?
Answer: The question is being asked with false premises.Smiling won't change the pitch. It will change the timbre or tone. Which may change the number or mix of overtones slightly, all of which will still be overtones of that original pitch.
If the initial pitch is out of tune, then automatically any overtones or harmonics will be too.
So in answer to your embryonic question - the overtones from an off note won't be somehow in tune if the base note is out of tune anyway.
Comment: Hi Tim, you are correct, and I give you accepted answer, though somewhat begrudgingly after the unnecessary [and I'd deem] inaccurate accusation of my question being 'embryonic'! I was wrong because I thought human vocal overtones could be inharmonic. After playing with an audio spectrogram and reading online, I see I was mistaken; human vocals are remarkably close to ideal oscillators. But do allow me to say your statement "_may_ change the number or mix of overtones slightly...", is a little off; it's absolutely necessary for overtones to vary if the timbre does.
Comment: The embryonic question is the one still to be asked...
Answer: No, your facial expression has no direct correlation with the fundamental frequency you vocalise. However, smiling while singing does in fact tend to have a number of favorable side effects.
Traditionally, when I've heard singing (usually choral) instructors explain this, they say that smiling will prevent you from going flat on a note, and that it also prevents you from being monotonous/lifeless. And from my own personal experience, it's seemed to largely be effective advice, especially at lower levels of singing, where the singers may not be as skilled at sustaining a note and keeping it in tune every single time.
If I had to guess (and that's all this is, a somewhat educated guess), I'd say that somehow the act of smiling is closely linked to certain elements of the singing mechanism that are beneficial, and therefore thinking about smiling sort of unconsciously enables the singer to produce the sound more optimally (hence this "sharpening" would really just be a better sound production mechanism being better at singing in tune). And obviously, thinking about smiling can help one be more emotionally aware of the music.
So yes, other answers are correct in that a singer can frown and be perfectly in tune, or smile and be off by half an octave. But choral directors and other singing instructors have been conscious of the correlation between the two human processes, and as such, it makes sense to use this relationship in an educational setting in order to facilitate better singing technique.
Of course, I'm not a vocal instructor myself, so if you're looking to use this idea in your own singing studies or teachings, please talk to actual professionals about how to learn or teach the specifics of this - like many singing ideas, if you do it wrong, it may be more harm than good.

A couple random online sources I found discussing this:

https://www.ardenkaywinvocalstudio.com/smiling-singing/
https://www.themodernvocalistworld.com/forums/topic/9363-singing-with-a-smile/


Calculation of studentized deleted residuals

Question: I have a problem that asks me to calculate studentized deleted residuals from the following set of residuals:

From the original dataset:

The Hat matrix, diagonal elements hii, SSE/MSE, formula for studentized residuals, and final calculation of the residuals are below:
s

However, I cannot reproduce these results given the formula! For example, taking the square root of a negative residual in the numerator results in an imaginary number if x>0. Is there another way to calculate these residuals, or something I am I just not getting it? Thanks!
Comment: The formula for the standardized (internally studentized) residual is: $r_i=e_i/\sqrt{MSE(1 - h_{ii})}$. From this, the externally studentized residuals can be calculated by: $t_i=r_i\left(\frac{n-k-2}{n-k-1-r_i^2}\right)^{(1/2)}$, where $n$ is the sample size and $k$ the number of predictors.
Answer: The $i$-th (internally) studentized residual $r_i$ is given by
$$
r_i = \frac{e_i}{\sqrt{\mathrm{MSE}\left(1-h_{ii}\right)}},
$$
where the residual mean square $\mathrm{MSE}$ (for which a better abbreviation would be $\mathrm{MS}_{\mathrm{Res}}$) is given by $e^\top e /\left(n-p\right)$.
The $i$-th externally studentized residual $t_i$ is given by
$$
t_i = \frac{e_i}{\sqrt{S_{\left(i\right)}^2\left(1-h_{ii}\right)}},
$$
where $S_{\left(i\right)}^2$ is calculated as the usual unbiased estimator of the error variance but based on a data set with the $i$-th observation removed.
It is straightforward to show (see, e.g., Montgomery, Peck, & Vining, 2012, p. 593) that
$$
S_{\left(i\right)}^2 = \frac{\left(n-p\right)\mathrm{MSE} - e_i^2/\left(1-h_{ii}\right)}{n-p-1}.
$$
In terms of the $i$-th internally studentized residual we get
$$
\begin{align}
S_{\left(i\right)}^2
&= \frac{\left(n-p\right)\mathrm{MSE} - r_i^2\mathrm{MSE}}{n-p-1} \\
&= \frac{\left(n-p-r_i^2\right)\mathrm{MSE}}{n-p-1},
\end{align}
$$
and hence
$$
\begin{align}
t_i
&= \frac{e_i}{\sqrt{\frac{\left(n-p-r_i^2\right)\mathrm{MSE}}{n-p-1}\left(1-h_{ii}\right)}} \\
&= \frac{e_i}{\sqrt{\mathrm{MSE}\left(1-h_{ii}\right)}} \cdot \sqrt{\frac{n-p-1}{n-p-r_i^2}} \\
&= r_i \cdot \sqrt{\frac{n-p-1}{n-p-r_i^2}}.
\end{align}
$$

Reference
Montgomery, D. C., Peck, E. A., & Vining, G. G. (2012). Introduction to linear regression analysis (5th ed.). John Wiley & Sons.
Comment: Lack of upvotes even though there are proper answers propel the number of unanswered questions here.
Answer: I believe this is simply a typo. The formula should be:
$$
\frac{e_i}{\sqrt{\operatorname{SSE}(1-h_{ii})-e_i^2}}
$$
or similarly:
$$
\operatorname{sign}(e_i)\left[
\frac{e_i^2}{\operatorname{SSE}(1-h_{ii})-e_i^2}
\right]^{1/2}
$$
Comment: Well.... it still doesn't appear to compute the same amounts for the studentized residuals. For example, t1 should be -.424611 using your formula


Minimizing the KL distance from a uniform distribution under a mean constraint

Question: I wish to solve the problem $$p^*=\arg\min_p D_{KL}(p||q),\;\;s.t.\;\;\mathbb{E}_{X\sim p}X=\mu,$$
where $q$ is the uniform distribution $q=\text{Unif}[0,\alpha]$.
I know that the general solution to these type of problems is exponential family, hence
$$ p^*(x) =q(x)e^{\eta x -a(\eta})= \frac{1}{\alpha}e^{\eta x -a(\eta})\mathbb{I}_{x\in[0.\alpha]}.$$
After I calculate $a(\eta)$ according to the normalization constraint I get
$$ p^*(x) =\frac{\eta }{e^{\eta \alpha}-1}e^{\eta x}\mathbb{I}_{x\in[0.\alpha]}.$$
Now I want to look at interesting values of $\alpha$ (the support of the uniform distribution) and calculate the parameter $\eta$ to hold the mean constraint in these cases. Example for such cases: $\alpha \rightarrow \infty$, $\alpha \rightarrow 0$, $\alpha = \frac{b}{2}$.
However, except in the latter case, I didn't succeed in solving the equation. After calculating the mean I get
$$\mu = \frac{ \alpha}{e^{\eta \alpha}-1}+\alpha -\frac{1}{\eta}$$,
and I don't see how this can be solved, say for $\alpha\rightarrow \infty$.
Comment: Why are KL-minimizers generally in the exponential family?
Answer: Let's do some variational calculus here:
First, let's suppose, that we are looking for the function p(x) with the same domain as q(x).
We want to solve constrained optimisation problem:
$
\left \{ \begin{array}{rcl}
\int\limits_{0}^{\alpha} p(x) \log \frac{p(x)}{q(x)} \ dx \to \min\limits_{p(x)} \\
\int\limits_{0}^{\alpha} p(x) \ dx = 1 \\
 \int\limits_{0}^{\alpha} xp(x) \ dx = \mu
\end{array} \right .
$
So we have $L(p) = \int\limits_{0}^{\alpha} \underbrace{p(x) \log \frac{p(x)}{q(x)} + \lambda_{1} \cdot p(x) + \lambda_{2} \cdot x p(x)}_{F(x, p, p^{\prime})} \ dx \to \min\limits_{p(x)}$.
It's known from variational calculus, that you need to solve $\frac{\delta L}{\delta p} = \frac{\partial F}{\partial p} - \frac{d}{dx} \cdot \frac{\partial F}{\partial p^{\prime}} = 0$ in order to minimize $L(p)$.
$\frac{\delta L}{\delta p} = \log p(x) - \log q(x) + 1 + \lambda_{1} + \lambda_{2}x = 0 \Rightarrow \log p(x) = \log q(x) - 1 -\lambda_{1} - \lambda_{2}x \Rightarrow p(x) = q(x) \cdot e^{-\lambda_{1} - 1 - \lambda_{2}x} = \frac{1}{\alpha} \cdot e^{-1 - \lambda_{1} - \lambda_{2}x}$.
Now we find parameters $\lambda_{1, 2}$ by solving the conditions:
1) $\int\limits_{0}^{\alpha} p(x) = 1 \Rightarrow \frac{1}{\alpha} e^{-1 - \lambda_{1}} \int\limits_{0}^{\alpha} e^{-\lambda_{2}x} \ dx = \frac{1}{\alpha} e^{-1 - \lambda_{1}} \cdot \left( \frac{e^{-\lambda_{2} \cdot \alpha}}{-\lambda_{2}}  + \frac{1}{\lambda_{2}} \right) = \boxed{\frac{e^{-1-\lambda_{1}} \cdot (1 - e^{- \lambda_{2} \alpha})}{\alpha \cdot \lambda_{2}} = 1}$
2) $\int\limits_{0}^{\alpha} x p(x) \ dx = \frac{1}{\alpha} e^{-1 - \lambda_{1}} \int\limits_{0}^{\alpha} x e^{-\lambda_{2}x} \ dx = \boxed{\frac{1}{\alpha} e^{-1 - \lambda_{1}} \cdot \frac{1 - (\alpha \lambda_{2} + 1) \cdot e^{-\lambda_{2} \alpha}}{\lambda_{2}^2} = \mu}$


Why use Elasticsearch with CouchDB when CouchDB 2.0 has /db/_find?

Question: We are reaching a phase in our project now where we would like to search in our documents with a regex that match some strings. CouchDB does now allow it with the 2.0 version and /db/_find which is great. Before that you would need to use Elasticsearch.
I would like to know if one solution is better that the other, and what are to consequences in term of disk storage ?
I saw in CouchDB documentation a lot of warning about the /bd/_find feature, for instance :

Regular expressions do not work with indexes, so they should not be used to filter large data sets.

Thanks in advance for your enlightenment
Answer: Simply speaking, if you use regular expressions with _find, all the documents in your database will be scanned for every query you issue. This is completely different to Elasticsearch, which is optimized for free text queries.
So if you want to use good performance with reqex queries, use Elasticsearch.
The complete picure is a bit more complicated: If you also have a fixed part where an index can be used, you can optimize your query. If you'd elaborate on what exactly your use case is, I might be able to help further.
Comment: There's actually a module provided by Cloudant to provide full-text search indizes for CouchDB running on Lucene. It's not enabled by default in CouchDB 2.0 builds, but it's not so hard to add either. Cloudant runs it in production. But this makes the question slightly more complicated: How do Dreyfus/Clouseau compare against Elasticsearch? https://github.com/cloudant-labs/dreyfus
Comment: There's also couchdb-lucene, which has been on the market for years. https://github.com/rnewson/couchdb-lucene. There are differences, but in the end the answer to the question is the same: Use a full-text engine for full-text queries, use CouchDb for simpler, structured queries.
Comment: [There's](https://github.com/rnewson/couchdb-lucene/issues/236) also a nice thread comparing couchdb-lucene and Clouseau on CouchDB 2.0


Nginx cannot show many static images when using HTTP/2

Question: One of my WordPress sites has a lot of static images (think at least 20 per page) and after I enable HTTP/2, the images in the lower part start to appear as broken (crossed out, like in images with dead links). Nothing wrong shows up in error.log file, but Chrome 53 says like this in the console:
Failed to load resource: net::ERR_SPDY_PROTOCOL_ERROR

I tried messing with client_max_body_size but that was no luck.
edit: this is my nginx.conf:
load_module /usr/local/libexec/nginx/ngx_mail_module.so;
load_module /usr/local/libexec/nginx/ngx_stream_module.so;
user  www;
worker_processes 4;
error_log  /var/log/nginx/error.log  info;

events {
        worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 0;
    large_client_header_buffers 2 1k;
    client_body_timeout 12;
    send_timeout 10;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    gzip off;
    charset UTF-8;

    server {
        listen       80;
        server_name manuth.life www.manuth.life;
        server_tokens off;
        return 301 https://$server_name$request_uri; #redirects to HTTPS
        root   /usr/local/www/nginx/manuth.life;
        index index.php index.html index.htm;
        access_log /var/log/nginx/manuth.life.access.log;
        error_log /var/log/nginx/manuth.life.error.log;

        error_page      500 502 503 504  /50x.html;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/www/nginx-dist;
        }
    }

    server {
        listen       443 ssl http2;
        server_name  manuth.life www.manuth.life;
        server_tokens off;
        root   /usr/local/www/nginx/manuth.life;
        index index.php index.html index.htm;
        access_log /var/log/nginx/manuth.life.access.log;
        error_log /var/log/nginx/manuth.life.error.log;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/www/nginx-dist;
        }

        # strict SSL settings
        ssl_certificate /usr/local/etc/letsencrypt/live/manuth.life/fullchain.pem;
        ssl_certificate_key /usr/local/etc/letsencrypt/live/manuth.life/privkey.pem;

        ssl_session_timeout 5m;
        ssl_protocols TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
        ssl_ecdh_curve secp384r1; #
        ssl_session_cache builtin:1000 shared:SSL:10m;
        ssl_session_tickets off;
        ssl_stapling on;
        ssl_stapling_verify on;
        ssl_dhparam /usr/local/etc/ssl/dhparam.pem;
        resolver 220.127.116.11 188.8.131.52 valid=300s;
        resolver_timeout 10s;
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;

        location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }

    }

}
Comment: What do you mean by "creates a very long URL"? And what is the URL requested by the browser?
Comment: @TeroKilkanen I got confused with another line in error.log thanks to my poor eyes...
Basically each page would display the first probably 10 images correctly, but every image below is crossed out. Ctrl+U shows nothing wrong in HTML and the only error I could find is this `ERR_SPDY_PROTOCOL_ERROR` in Chrome's console. I copied the links of the 'broken' image and opened it directly, and it worked too.
Comment: Which version of nginx are you using?
Comment: @MichaelHampton I'm using 1.10.1 from FreeBSD's pkg, not from source. HTTPV2 is already enabled anyway.
Answer: This seems to be a problem with Chrome 53. I'm using Chrome 54 and I no longer see this issue. In fact the speed just flies! (on local network, that is)
Comment: If this problem is solved, please mark it as solved by clicking the check mark to the left of the answer so that it turns green.
Answer: You're getting SPDY errors, which is a predecessor of HTTP2. HTTP2 isn't built into Nginx by default, you have to build Nginx yourself (documentation link that says this, tutorial link for the build). Building Nginx is pretty easy. Some distributions may build http/2 in.
Once you've gotten Nginx with HTTP/2 support built in, as people have save, you need to add the http2 directive to your listen command.
listen 443 ssl http2;

If this doesn't work you'll need to post your full, accurate configuration, plus a link to the website that's not working properly. We can't diagnose what we can't see.
Comment: You can try this:
https://manuth.life/soshi/yoona/concerts/2016/161001-busan-one-asia-festival
Also HTTP/2 is already in my version.
Comment: Something screwy is going on. On a webpagetest.org test I can see it's super slow to download images, which incidentally are WAY too large. But they do download. Some simple compression will reduce your image size by 80% or more and may help with the problem. If you reduce the image dimensions, which you should as they're too big for a web browser vertically, you could achieve 95% size reduction.
Comment: Well, the point of the site is to serve high-res images like that. Is it safe to enable gzip compression only on the directory that contains the images? I disabled it since the site is HTTPS only and I've read that it's not safe to enable it with HTTPS.
Comment: Gzip won't help images, it only helps web pages, and tends to be automatically disabled for images. You can make the image files smaller but look just as good very easily, for example with https://tinyjpg.com/  . I don't know if it'll solve your problem but I suspect it will help. Also, use a CDN like CloudFlare, it will serve the images much faster than your web server.
Comment: Looks like I need to roll back to HTTP 1.1 then. I have too many images to downsize (and the point is to serve high-res images anyway), plus the total size would be too large. This problem seems to be only on Chrome, at least on the version 53 that I'm using.
Comment: It might be http2, it might be something else. Nothing else stands out to me as a problem. If it works perfectly on HTTP1.1 then I'd probably stick with it for now.
Comment: Chrome 54 appears to have fixed this issue.


What is the path for form elements which are ajax-enabled

Question: I am working on the quiz module.
I have to modify the form node/add/multichoice by hiding some of the form elements in it.
With the help of krumo function of devel module, I am able to find the correct form elements and set ['#access'] to FALSE in order to hide them.
All this is done in a custom module using the hook_form_alter().
But the problem is that I have to hide advanced fieldset under alternatives.
The path for form element for advanced fieldset is thus like below :
$form['alternatives'][0]['advanced']
$form['alternatives'][1]['advanced']
But there is an option of add more alternatives.
What is the path for form elements which are ajax enabled.
Comment: Probably best to loop through `element_children($form['alternatives'])`, you're likely to run into problems otherwise
Comment: You have to loop through `$form['alternatives']`:
`foreach ($form['alternatives'] as $delta => &$alternative) {
  $alternative['#access'] = FALSE;
}`
Comment: thankyou so much. Let me try and get back to you.regards.
Comment: it is throwing errors. please look into it.
Comment: Warning: Illegal string offset '#access' in znew_form_alter() (line 24 of C:\xampp\htdocs\newsite\sites\all\modules\znew\znew.module).
Warning: Illegal string offset '#access' in znew_form_alter() (line 24 of C:\xampp\htdocs\newsite\sites\all\modules\znew\znew.module).
Warning: Cannot use a scalar value as an array in znew_form_alter() (line 24 of C:\xampp\htdocs\newsite\sites\all\modules\znew\znew.module).
Comment: @TulikaSharma follow Clive's advice and use `element_children` instead. That should avoid this issue you're having
Answer: foreach (element_children($form['alternatives']) as $delta) {
  $form['alternatives'][$delta]['advanced']['#access'] = FALSE;
}

Something like this.


Overload the subscript operator to call a function based on the type assigned

Question: I have an object that has functions like addString and addInteger. These functions add data to a JSON string. At the end, the JSON string can be obtained and sent out. How can this be made easier by overloading subscript operators to do the following?
jsonBuilder builder();

builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";

Comment: Right now we're looking at `jsonBuilder::operator[]( std::string & )`. No overloading involved. How do you *want* this to be "made easier"? Do you know how overloading works? What have you tried? **What is your question?** And no, we won't code your solution for you. (I hope no-one does.)
Answer: You need to have a proxy class that is returned by the operator[] function and which handles the assignment. The proxy class then overloads the assignment operator to handle strings and integers differently.
Something like this:
#include <iostream>
#include <string>

struct TheMainClass
{
    struct AssignmentProxy
    {
        std::string name;
        TheMainClass* main;

        AssignmentProxy(std::string const& n, TheMainClass* m)
            : name(n), main(m)
        {}

        TheMainClass& operator=(std::string const& s)
        {
            main->addString(name, s);
            return *main;
        }

        TheMainClass& operator=(int i)
        {
            main->addInteger(name, i);
            return *main;
        }
    };

    AssignmentProxy operator[](std::string const& name)
    {
        return AssignmentProxy(name, this);
    }

    void addString(std::string const& name, std::string const& str)
    {
        std::cout << "Adding string " << name << " with value \"" << str << "\"\n";
    }

    void addInteger(std::string const& name, int i)
    {
        std::cout << "Adding integer " << name << " with value " << i << "\n";
    }
};

int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused)))
{
    TheMainClass builder;
    builder[ "string_value" ] = "Hello";
    builder[ "int_value" ] = 5;
    builder[ "another_string" ] = "Thank you";
}

See here for a working example.
Answer: I think you need this finally. I have implemented for getting the string input, do the same for integer.
#include <iostream>
#include <string>
#include <map>

class jsonBuilder
{
    public:
        std::map<std::string,std::string> json_container;
        std::string&  operator[](char *inp)
        {
            std::string value;
            json_container[std::string(inp)];
            std::map<std::string,std::string>::iterator iter=json_container.find(std::string(inp));

            return iter->second;
        }
};

int main()
{
    jsonBuilder jb;
    jb["a"]="b";

    std::map<std::string,std::string>::iterator iter=jb.json_container.find(std::string("a"));
    std::cout<<"output: "<<iter->second;
}


Java's 'tnameserv' takes 3+ minutes to be "Ready", why?

Question: I'm trying to help a dev of an app I'd like to use trouble shoot a problem utilizing Corba Server on Linux.  I narrowed down the problem to tnameserv taking over 3 minutes to become ready after invocation.
What exactly is tnameserv trying to do in those 3 minutes and is there anyway I can speed it up?  The app failed because it tried to do 5 connection attempts with 1-second between retries; which apparently doesn't give tnameserv nearly enough time to become ready.  I am using Java 6u17 on Slackware 13.0
In case it matters. The actual invocation of tnameserv is the following:
tnameserv -ORBInitialPort 23423

Upon running that command in a shell, it appears to hang until around the 3minute mark when I finally see it display "Ready".
UPDATE
I did an strace -f tnameserv -ORBInitialPort 23423 and I am seeing an eff ton of calls to gettimeofday(), clock_gettime() and futex() of which the latter is always returning '-1 ETIMEDOUT (Connection timed out).  I have a feeling this is related to my problem, but I have no idea how or why.
Here is a but a small fraction of what I am seeing from strace. Can somebody replicate and/or make sense of this?

[pid 30950] futex(0x8128e14, FUTEX_WAIT_PRIVATE, 1, {0, 49903084}) = -1 ETIMEDOUT (Connection timed out)
[pid 30950] futex(0x8098a28, FUTEX_WAKE_PRIVATE, 1) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329619, 995857482}) = 0
[pid 30950] gettimeofday({1260930158, 92108}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329619, 995996617}) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329619, 996088536}) = 0
[pid 30950] gettimeofday({1260930158, 92328}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_REALTIME, {1260930158, 92424295}) = 0
[pid 30950] futex(0x8128e14, FUTEX_WAIT_PRIVATE, 1, {0, 49903705}) = -1 ETIMEDOUT (Connection timed out)
[pid 30950] futex(0x8098a28, FUTEX_WAKE_PRIVATE, 1) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 46761098}) = 0
[pid 30950] gettimeofday({1260930158, 143084}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 46913924}) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 47006961}) = 0
[pid 30950] gettimeofday({1260930158, 143303}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_REALTIME, {1260930158, 143398317}) = 0
[pid 30950] futex(0x8128e14, FUTEX_WAIT_PRIVATE, 1, {0, 49904683}) = -1 ETIMEDOUT (Connection timed out)
[pid 30950] futex(0x8098a28, FUTEX_WAKE_PRIVATE, 1) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 97818379}) = 0
[pid 30950] gettimeofday({1260930158, 194127}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 97957235}) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 98049154}) = 0
[pid 30950] gettimeofday({1260930158, 194346}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_REALTIME, {1260930158, 194441349}) = 0
[pid 30950] futex(0x8128e14, FUTEX_WAIT_PRIVATE, 1, {0, 49904651}) = -1 ETIMEDOUT (Connection timed out)
[pid 30950] futex(0x8098a28, FUTEX_WAKE_PRIVATE, 1) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 148806370}) = 0
[pid 30950] gettimeofday({1260930158, 245055}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 148947182}) = 0
[pid 30950] clock_gettime(CLOCK_MONOTONIC, {329620, 148981547}) = 0
[pid 30950] gettimeofday({1260930158, 245280}, NULL) = 0
[pid 30950] clock_gettime(CLOCK_REALTIME, {1260930158, 245374859}) = 0
[pid 30950] futex(0x8128e14, FUTEX_WAIT_PRIVATE, 1, {0, 49905141}) = -1 ETIMEDOUT (Connection timed out)
Answer: I can't fix your problem directly, but experience tells me that more often than not, unexplained delays of three to five minutes are the result of waiting for DNS timeouts.
Does your configuration call for anything by hostname?
Comment: Absolutely. My first response was DNS as well. Make sure your DNS is working right
Comment: I appreciate the answer and you're right, that is something that I would have thought it would be as well but I'm 100% sure that my DNS is working because the same server I'm running 'tnameserv' on is the same server that is my firewall/squid server that I'm going through as we speak.  I also did a 'dig www.google.com' successfully just to double check.
Answer: Turns out the problem was a firewall issue. Wireshark didn't show anything useful because the firewall was dropping a certain packet. Although I looked at my firewall logs quite a few times to make sure this wasn't the case, turns out I wasn't looking in the right place. I overlooked the fact that this 'tnameserv' was IPv6 aware (as it was binding to :::23423) and a cursory glance of my firewall script showed that I was logging IPv6 related packets to a different location than my IPv4 packets. This was not an oversight but had to be done because ip6tables does not currently support the -j ULOG target.
Long story short, allowing loopback for IPv6 fixed the issue and 'tnameserv' returns "Ready" almost instantly.