Como fazer inner join em tabela associativa?

Question: Tabelas e inserts:
CREATE TABLE CLIENTE(
  IDCLIENTE INT PRIMARY KEY AUTO_INCREMENT,
  NOME VARCHAR(30) NOT NULL,
  SEXO ENUM('M','F') NOT NULL,
  ID_CARRO INT UNIQUE
);

INSERT INTO CLIENTE VALUES (NULL,'GABRIEL','M',1);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL2','M',2);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL3','M',3);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL4','M',4);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL5','M',5);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL6','M',6);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL7','M',7);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL8','M',8);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL9','M',9);
INSERT INTO CLIENTE VALUES (NULL,'GABRIEL10','M',10);

CREATE TABLE TELEFONE(
  IDTELEFONE INT PRIMARY KEY AUTO_INCREMENT,
  TIPO ENUM('RESIDENCIAL','CELULAR') NOT NULL,
  NUMERO VARCHAR(15) NOT NULL,
  ID_CLIENTE INT
);

CREATE TABLE MARCA(
  IDMARCA INT PRIMARY KEY AUTO_INCREMENT,
  MARCA VARCHAR(30) NOT NULL UNIQUE
);

INSERT INTO MARCA VALUES (NULL,'FIAT'); -- 1
INSERT INTO MARCA VALUES (NULL,'VOLKSWAGEM'); -- 2
INSERT INTO MARCA VALUES (NULL,'TOYOTA'); -- 3
INSERT INTO MARCA VALUES (NULL,'RENAULT'); -- 4
INSERT INTO MARCA VALUES (NULL,'LAMBORGHINI'); -- 5

CREATE TABLE CARRO(
  IDCARRO INT PRIMARY KEY AUTO_INCREMENT,
  MODELO VARCHAR(30) NOT NULL,
  PLACA VARCHAR(30) NOT NULL UNIQUE,
  ID_MARCA INT
);

INSERT INTO CARRO VALUES (NULL,'PALIO','CSW-6202',1);
INSERT INTO CARRO VALUES (NULL,'PALIO FIRE','AAA-0000',1);
INSERT INTO CARRO VALUES (NULL,'ONIX','BBB-1111',2);
INSERT INTO CARRO VALUES (NULL,'ONIX FIRE','CCC-2222',2);
INSERT INTO CARRO VALUES (NULL,'SPIN','DDD-4444',3);
INSERT INTO CARRO VALUES (NULL,'SPIN FIRE','EEE-5555',3);
INSERT INTO CARRO VALUES (NULL,'SANDERO','FFF-6666',1);
INSERT INTO CARRO VALUES (NULL,'SANDERO FIRE','GGG-7777',1);
INSERT INTO CARRO VALUES (NULL,'GALLIARDO','HHH-8888',1);
INSERT INTO CARRO VALUES (NULL,'GALLIARDO FIRE','III-9999',1);

CREATE TABLE COR(
  IDCOR INT PRIMARY KEY AUTO_INCREMENT,
  COR VARCHAR(30) NOT NULL UNIQUE
);

INSERT INTO COR VALUES (NULL,'CINZA'); -- 1
INSERT INTO COR VALUES (NULL,'VERMELHO'); -- 2

CREATE TABLE CARRO_COR(
  ID_CARRO INT,
  ID_COR INT,
  PRIMARY KEY (ID_CARRO,ID_COR)
);

INSERT INTO CARRO_COR VALUES (1,1);
INSERT INTO CARRO_COR VALUES (1,2);
INSERT INTO CARRO_COR VALUES (2,1);
INSERT INTO CARRO_COR VALUES (2,2);
INSERT INTO CARRO_COR VALUES (3,1);
INSERT INTO CARRO_COR VALUES (3,2);
INSERT INTO CARRO_COR VALUES (4,1);
INSERT INTO CARRO_COR VALUES (4,2);
INSERT INTO CARRO_COR VALUES (5,1);
INSERT INTO CARRO_COR VALUES (5,2);

FOREIGN KEY E CONSTRAINTS
-- FOREIGN KEY E CONSTRAINTS

ALTER TABLE TELEFONE
ADD CONSTRAINT FK_TELEFONE_CLIENTE
FOREIGN KEY (ID_CLIENTE)
REFERENCES CLIENTE(IDCLIENTE);

ALTER TABLE CLIENTE
ADD CONSTRAINT FK_CLIENTE_CARRO
FOREIGN KEY (ID_CARRO)
REFERENCES CARRO(IDCARRO);

ALTER TABLE CARRO
ADD CONSTRAINT FK_CARRO_MARCA
FOREIGN KEY (ID_MARCA)
REFERENCES MARCA(IDMARCA);

ALTER TABLE CARRO_COR
ADD CONSTRAINT FK_COR
FOREIGN KEY (ID_COR)
REFERENCES COR(IDCOR);

ALTER TABLE CARRO_COR
ADD CONSTRAINT FK_CARRO
FOREIGN KEY (ID_CARRO)
REFERENCES CARRO(IDCARRO);

* QUERY :*
SELECT C.NOME, CAR.MODELO, CO.COR,
FROM CLIENTE C
INNER JOIN CARRO CAR
ON CAR.IDCARRO = C.ID_CARRO;
INNER JOIN CARRO_COR CC
ON CC.ID_CARRO = CAR.IDCARRO
INNER JOIN COR CO
ON CO.IDCOR = CC.ID_COR;

Estou com erro de sintaxe será que podem me ajudar com isso?
Comment: Na sua *query*, após o primeiro `inner join`, parece haver um ponto-e-vírgula que não deveria existir.
Comment: Remova o ";" do meio da query
Comment: E qual é exatamente a mensagem de erro?
Comment: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN CARRO_COR CC
ON CAR.IDCARRO = CC.ID_CARRO
INNER JOIN COR CO
ON CC.ID_' at line 1
Comment: Opa esse ; estava só para testar se o primeiro inner estava ok.

Retirei, ficou :
SELECT C.NOME, CAR.MODELO, CO.COR,
FROM CLIENTE C
INNER JOIN CARRO CAR
ON CAR.IDCARRO = C.ID_CARRO
INNER JOIN CARRO_COR CC
ON CC.ID_CARRO = CAR.IDCARRO
INNER JOIN COR CO
ON CO.IDCOR = CC.ID_COR;

O erro é :

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM CLIENTE C
INNER JOIN CARRO CAR
ON CAR.IDCARRO = C.ID_CARRO
INNER JOIN CAR' at line 2
Comment: Edite a pergunta e coloque o erro que está a obter para que seja mais claro
Answer: Você tem uma vírgula sobrando depois da declaração das colunas:
SELECT C.NOME,
       CAR.MODELO,
       CO.COR
  FROM CLIENTE C
       INNER JOIN CARRO CAR ON CAR.IDCARRO = C.ID_CARRO
       INNER JOIN CARRO_COR CC ON CC.ID_CARRO = CAR.IDCARRO
       INNER JOIN COR CO ON CO.IDCOR = CC.ID_COR

Comment: Lindo você fazer uma modelagem bonitinha tudo bonitinho e depois errar por uma , ... HAHAHA OBRIGADO!!!


Can one website be accessed via multiple domains with ssl?

Question: Can a website on a vps with a dedicated ip be accessed via multiple domain names and use ssl where needed? How would this be done on IIS 7.5 WIndows R2 2008
Comment: you'll need one SSL certificate per IP:PORT pair
Answer: Re: your first question:
Sure, a website can be accessed via multiple domain names using SSL.  In most instances this means you'll need multiple SSL certificates, but it will work just fine.  If all the domain name share a common parent domain, you may be able simplify things with a wildcard certificate (although those are typically more expensive).
Re: your second question:
Haven't the foggiest.
Answer: It is possible to do so, using TLS (SSLv3) Server Name Indication (SNI). This is not supported in every browser, but it's much better than it was two years ago.
TLS-SNI is not officially supported in IIS7.5, so no it can't be done in IIS7.5.
Though it looks like you can complain to Microsoft about it here.


mocha error : invalide usage of console logs detected

Question: All my test passed successfully.
But at the end I have this message :
  32 passing (7s)
=== ATTENTION - INVALID USAGE OF CONSOLE LOGS DETECTED ===
[------------all logs here------------]
npm ERR! code ELIFECYCLE
npm ERR! errno 10
npm ERR! firstname.lastname@example.com test: 'lb-mocha --opts tests/mocha.opts'
npm ERR! Exit status 10
npm ERR!
npm ERR! Failed at the email@example.com test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\XXX\AppData\Roaming\npm-cache\_logs\2019-04-03T09_57_58_382Z-debug.log

Here are my mocha.opts :
--allow-console-logs
--recursive
--require ts-node/register
tests/**/*.ts
--exit

Do you know why it's not working ?
Answer: I found my mistake.
--allow-console-logs is NOT a mocha cli options. This is a "lb-mocha" cli option, meaning that is only dependent to loopback. That's why it was not interpreted by mocha in the mocha.opts file. The solution is to extract this argument from mocha option file to the test commande line in the package.json, see below:
//package.json//
{
  ...
  "script": {
    ...
    "test": "lb-mocha --allow-console-logs --opts tests/mocha.opts"
    ...
  }
  ...
}

Don't forget to remove the argument from mocha.opts file:
//mocha.opts//
--recursive
--require ts-node/register
tests/**/*.ts
--exit

I hope it will save your day.


Cannot play video in TextureView Android

Question: I have a problem with playing video on some devices. I am using textureview with mediaplayer, every methods of SurfaceTextureView are called but when I just call mediaPlayer.start(), immediately the listener with completition of playing is called. In log is this error:
<code>E/MediaPlayer﹕ error (1, -2147483648)
</code>
When I list log from all applications, I can see some errors and I dont know if it is somehow related http://pastebin.com/rRxxQgdJ
This log is from CyanogenMod with Android 4.3.1 but on some other devices like Samsung Galaxy S3 mini this error is happening.
On my Nexus 4 everything works fine. I've tried convert that video with mp4 codec for android H.264 and even with ffmpeg but the result is still the same. I am using TextureVideoView implementation from here:
https://github.com/dmytrodanylyk/video-crop/blob/master/library/src/com/dd/crop/TextureVideoView.java
Thanks for any advice
Comment: it is an issue with the path of the video to play..the path is not correct..or the file name or file type is not supported..
Comment: Well the filetype is mp4, i know that its not rule of thumb that it should work, but i converted it to that type that should work on Androids.. and path to file is right, if on some device it can be played and on other cant, right? I've tried two approach of loading video - from assets or from raw folder and none of them works. This is for assets approach  mTextureVideoView.setDataSource(getAssets().openFd("intro_video.mp4")); and this is for raw approach  String uriPath = "android.resource://" + getPackageName() + "/raw/intro_video" ;mTextureVideoView.setDataSource(this, Uri.parse(uriPath));
Answer: As I already pointed it out here it may be due to the fact that video encoding parameters (profile, level, pixel format, etc.) are not supported on the platform, try playing around with the source.


Netbeans Glassfish giving 404 on webservice, but not a JSP page

Question: I created a "WebApplication" in NetBeans.  It has a JSP page and a webservice.  It was working fine.  Then I made a few minor changes and redeployed.  Suddenly the webservice gives a 404 (Not Found) error.  GlassFish is still up and I can even hit a JSP page in the same project and changes to the JSP page are recognized.
Here's my deploy output:

init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
Building jar: C:\Documents and Settings\randys\My Documents\NetBeansProjects\WebApplication6\dist\WebApplication6.war
Starting GlassFish V3
GlassFish V3 is running.
Incrementally deploying WebApplication6
Completed incremental distribution of WebApplication6
Incrementally redeploying WebApplication6
redeploy?name=WebApplication6&properties=keepSessions=true running on GlassFish V3
redeploy?name=WebApplication6&properties=keepSessions=true completed on GlassFish V3
run-deploy:
Browsing: http://localhost:8080/WebApplication6/
run-display-browser:
run:
BUILD SUCCESSFUL (total time: 41 seconds)

and

INFO: Launching GlassFish on Apache Felix OSGi platform
Welcome to Felix.
=================
INFO: Started bundle org.glassfish.common.glassfish-mbeanserver [7]
INFO: Started bundle org.glassfish.core.kernel [103]
INFO: Started bundle org.glassfish.common.common-util [84]
INFO: Started bundle GlassFish-Application-Common-Module [68]
INFO: APIClassLoader = Class Loader for Bundle [GlassFish-Application-Common-Module [68] ]
INFO: registering service = org.apache.felix.framework.StartLevelImpl@676437, contract = org.osgi.service.startlevel.StartLevel, name = null
INFO: registering service = org.apache.felix.framework.PackageAdminImpl@1e808ca, contract = org.osgi.service.packageadmin.PackageAdmin, name = null
INFO: Started bundle org.glassfish.branding.branding [31]
no resource bundle found for version, using default GlassFish version
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: Started bundle org.glassfish.common.internal-api [88]
INFO: Started bundle org.glassfish.admin.config-api [76]
INFO: Started bundle org.glassfish.registration.glassfish-registration [98]
INFO: Started bundle org.glassfish.deployment.deployment-autodeploy [61]
INFO: Started bundle org.glassfish.deployment.deployment-common [94]
INFO: Started bundle org.glassfish.flashlight.flashlight-framework [97]
INFO: Listening on port 8080
INFO: Network listener http-listener-2 on port 8181 disabled per domain.xml
INFO: Listening on port 4848
INFO: Started bundle org.glassfish.common.container-common [106]
INFO: The Admin Console is already installed, but not yet loaded.
INFO: Started bundle org.glassfish.persistence.jpa-connector [65]
INFO: Started bundle org.glassfish.webservices.jsr109-impl [70]
INFO: Started bundle org.glassfish.scripting.gf-jruby-connector [60]
INFO: Started bundle org.glassfish.web.gf-web-connector [121]
INFO: Started bundle org.glassfish.security.security [63]
INFO: security.secmgroff
INFO: Started bundle org.glassfish.security.securitycommon [19]
INFO: Security startup service called
INFO: Started bundle org.glassfish.common.glassfish-naming [90]
INFO: Started bundle org.glassfish.security.realms [74]
INFO: Started bundle org.glassfish.common.glassfish-api [107]
INFO: Started bundle org.glassfish.connectors.connectors-runtime [23]
INFO: Security service(s) started successfully....
INFO: registering service = org.glassfish.web.DirContextURLStreamHandlerService@12d26d2, contract = org.osgi.service.url.URLStreamHandlerService, name = null
INFO: Started bundle org.glassfish.web.web-glue [113]
INFO: Started bundle org.glassfish.transaction.jta [57]
INFO: Started JMXConnector, JMXService URL = service:jmx:rmi:///jndi/rmi://RANDYS-LAPTOP:8686/jmxrmi
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Started bundle org.glassfish.deployment.dol [8]
INFO: Started bundle org.glassfish.web.web-core [130]
INFO: Dual registration of jndi stream handler: factory already defined
INFO: Unknown loader 113.0 class org.apache.felix.framework.searchpolicy.ContentClassLoader
INFO: Started bundle org.glassfish.web.jstl-connector [119]
INFO: Started bundle org.glassfish.web.jsf-connector [126]
INFO: Using com.sun.enterprise.transaction.JavaEETransactionManagerSimplifiedDelegate as the delegate
INFO: Started bundle org.glassfish.connectors.work-management [37]
INFO: Started bundle org.glassfish.common.glassfish-ee-api [50]
INFO: Started bundle org.glassfish.connectors.connectors-internal-api [111]
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Unknown loader 113.0 class org.apache.felix.framework.searchpolicy.ContentClassLoader
INFO: policy.loading
INFO: Started bundle org.glassfish.web.war-util [122]
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
INFO: Started bundle org.glassfish.security.websecurity [115]
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1e14a78 class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1e14a78 class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Loading WebApplication6 Application done is 10032 ms
INFO: GlassFish v3 Prelude startup time : Felix(7062ms) startup services(13173ms) total(20235ms)
INFO: classLoader = WebappClassLoader
  delegate: true
  repositories:
    WEB-INF/classes/
----------> Parent Classloader:
org.glassfish.internal.api.DelegatingClassLoader@1e14a78
INFO: SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@1ba5016
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1e14a78 class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1e14a78 class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Deployment of WebApplication6 done is 3156 ms
INFO: Server shutdown initiated
INFO: classLoader = WebappClassLoader
  delegate: true
  repositories:
    WEB-INF/classes/
----------> Parent Classloader:
org.glassfish.internal.api.DelegatingClassLoader@1e14a78
INFO: SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@1ba5016
SEVERE: PWC3983: Coyote connector has not been started
SEVERE: PWC3983: Coyote connector has not been started
INFO: PWC1240: Container WebModule[] has not been started
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] exiting
INFO: Stopped bundle = org.glassfish.common.common-util [84]
INFO: Stopped bundle = org.glassfish.registration.glassfish-registration [98]
INFO: Stopped bundle = org.glassfish.security.websecurity [115]
INFO: Stopped bundle = org.glassfish.web.web-core [130]
INFO: Stopped bundle = org.glassfish.deployment.dol [8]
INFO: Stopped bundle = org.glassfish.security.securitycommon [19]
INFO: Stopped bundle = org.glassfish.persistence.jpa-connector [65]
INFO: Stopped bundle = org.glassfish.security.realms [74]
INFO: Stopped bundle = org.glassfish.webservices.jsr109-impl [70]
INFO: Stopped bundle = org.glassfish.web.war-util [122]
INFO: Stopped bundle = org.glassfish.common.container-common [106]
INFO: Stopped bundle = org.glassfish.web.jstl-connector [119]
INFO: Stopped bundle = org.glassfish.common.glassfish-api [107]
INFO: Stopped bundle = org.glassfish.connectors.connectors-internal-api [111]
INFO: Stopped bundle = org.glassfish.web.jsf-connector [126]
INFO: Stopped bundle = org.glassfish.admin.config-api [76]
INFO: Stopped bundle = org.glassfish.scripting.gf-jruby-connector [60]
INFO: Stopped bundle = GlassFish-Application-Common-Module [68]
INFO: Stopped bundle = org.glassfish.connectors.connectors-runtime [23]
INFO: Stopped bundle = org.glassfish.common.glassfish-ee-api [50]
INFO: Stopped bundle = org.glassfish.common.glassfish-naming [90]
INFO: Stopped bundle = org.glassfish.branding.branding [31]
INFO: removing service = org.glassfish.web.DirContextURLStreamHandlerService@12d26d2, contract = org.osgi.service.url.URLStreamHandlerService
INFO: Stopped bundle = org.glassfish.web.web-glue [113]
INFO: Stopped bundle = org.glassfish.deployment.deployment-common [94]
INFO: Stopped bundle = org.glassfish.common.glassfish-mbeanserver [7]
INFO: Stopped bundle = org.glassfish.web.gf-web-connector [121]
INFO: Stopped bundle = org.glassfish.common.internal-api [88]
INFO: Stopped bundle = org.glassfish.deployment.deployment-autodeploy [61]
INFO: Stopped bundle = org.glassfish.connectors.work-management [37]
INFO: Stopped bundle = org.glassfish.flashlight.flashlight-framework [97]
INFO: Stopped bundle = org.glassfish.security.security [63]
INFO: Stopped bundle = org.glassfish.transaction.jta [57]
INFO: Stopped bundle = org.glassfish.core.kernel [103]
INFO: Stopped bundle = com.sun.enterprise.osgi-adapter [6]
INFO: Launching GlassFish on Apache Felix OSGi platform
Welcome to Felix.
=================
INFO: Started bundle org.glassfish.common.glassfish-mbeanserver [7]
INFO: Started bundle org.glassfish.core.kernel [103]
INFO: Started bundle org.glassfish.common.common-util [84]
INFO: Started bundle GlassFish-Application-Common-Module [68]
INFO: APIClassLoader = Class Loader for Bundle [GlassFish-Application-Common-Module [68] ]
INFO: registering service = org.apache.felix.framework.StartLevelImpl@1982fc1, contract = org.osgi.service.startlevel.StartLevel, name = null
INFO: registering service = org.apache.felix.framework.PackageAdminImpl@1e4853f, contract = org.osgi.service.packageadmin.PackageAdmin, name = null
no resource bundle found for version, using default GlassFish version
INFO: Started bundle org.glassfish.branding.branding [31]
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: Started bundle org.glassfish.common.internal-api [88]
INFO: Started bundle org.glassfish.admin.config-api [76]
INFO: Started bundle org.glassfish.registration.glassfish-registration [98]
INFO: Started bundle org.glassfish.deployment.deployment-autodeploy [61]
INFO: Started bundle org.glassfish.deployment.deployment-common [94]
INFO: Started bundle org.glassfish.flashlight.flashlight-framework [97]
INFO: Listening on port 8080
INFO: Network listener http-listener-2 on port 8181 disabled per domain.xml
INFO: Listening on port 4848
INFO: Started bundle org.glassfish.common.container-common [106]
INFO: The Admin Console is already installed, but not yet loaded.
INFO: Started bundle org.glassfish.persistence.jpa-connector [65]
INFO: Started bundle org.glassfish.webservices.jsr109-impl [70]
INFO: Started bundle org.glassfish.scripting.gf-jruby-connector [60]
INFO: Started bundle org.glassfish.web.gf-web-connector [121]
INFO: Started bundle org.glassfish.security.security [63]
INFO: Started bundle org.glassfish.common.glassfish-naming [90]
INFO: Started bundle org.glassfish.common.glassfish-api [107]
INFO: security.secmgroff
INFO: Started bundle org.glassfish.connectors.connectors-runtime [23]
INFO: Started bundle org.glassfish.security.securitycommon [19]
INFO: Started bundle org.glassfish.transaction.jta [57]
INFO: Security startup service called
INFO: Started bundle org.glassfish.security.realms [74]
INFO: Started JMXConnector, JMXService URL = service:jmx:rmi:///jndi/rmi://RANDYS-LAPTOP:8686/jmxrmi
INFO: Security service(s) started successfully....
INFO: registering service = org.glassfish.web.DirContextURLStreamHandlerService@162f030, contract = org.osgi.service.url.URLStreamHandlerService, name = null
INFO: Started bundle org.glassfish.web.web-glue [113]
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Started bundle org.glassfish.deployment.dol [8]
INFO: Started bundle org.glassfish.web.web-core [130]
INFO: Dual registration of jndi stream handler: factory already defined
INFO: Unknown loader 113.0 class org.apache.felix.framework.searchpolicy.ContentClassLoader
INFO: Started bundle org.glassfish.web.jstl-connector [119]
INFO: Started bundle org.glassfish.web.jsf-connector [126]
INFO: Using com.sun.enterprise.transaction.JavaEETransactionManagerSimplifiedDelegate as the delegate
INFO: Started bundle org.glassfish.connectors.work-management [37]
INFO: Started bundle org.glassfish.common.glassfish-ee-api [50]
INFO: Started bundle org.glassfish.connectors.connectors-internal-api [111]
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Unknown loader 113.0 class org.apache.felix.framework.searchpolicy.ContentClassLoader
INFO: policy.loading
INFO: Started bundle org.glassfish.web.war-util [122]
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
INFO: Started bundle org.glassfish.security.websecurity [115]
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1bb35b class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1bb35b class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Loading WebApplication6 Application done is 10359 ms
INFO: GlassFish v3 Prelude startup time : Felix(4500ms) startup services(13328ms) total(17828ms)
INFO: classLoader = WebappClassLoader
  delegate: true
  repositories:
    WEB-INF/classes/
----------> Parent Classloader:
org.glassfish.internal.api.DelegatingClassLoader@1bb35b
INFO: SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@ef9d00
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1bb35b class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Unknown loader org.glassfish.internal.api.DelegatingClassLoader@1bb35b class org.glassfish.internal.api.DelegatingClassLoader
INFO: Loading application WebApplication6 at /WebApplication6
INFO: Deployment of WebApplication6 done is 3360 ms

I see several:

WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: javax/jms/MessageListener

I don't use java messaging explicitly.  Any ideas why the WS is not deploying?
Answer: Using ProcessExplorer, I found a bunch of java.exe's running with the following command-line:

"C:\Program Files\Java\jdk1.6.0_14\jre\bin\java" "-Djruby.home=C:\Program Files\NetBeans 6.5.1\ruby2\jruby-1.1.4" -Djdbc.drivers=org.apache.derby.jdbc.ClientDriver "-Djavax.net.ssl.trustStore=C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/config/cacerts.jks" "-Djavax.net.ssl.keyStore=C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/config/keystore.jks" "-Djava.security.policy=C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/config/server.policy" -Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory "-Djava.security.auth.login.config=C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/config/login.conf" "-Djava.endorsed.dirs=C:\Program Files\glassfish-v3-prelude\glassfish/lib/endorsed" "-Djava.ext.dirs=C:\Program Files\Java\jdk1.6.0_14\jre/lib/ext;C:\Program Files\Java\jdk1.6.0_14\jre/jre/lib/ext;C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/lib/ext;C:\Program Files\glassfish-v3-prelude\javadb/lib" -XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput "-XX:LogFile=C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1/logs/jvm.log" -Xmx512m -XX:NewRatio=2 -Xdebug -Xrunjdwp:transport=dt_socket,address=3251,server=y,suspend=n -client -jar "C:\Program Files\glassfish-v3-prelude\glassfish\modules\glassfish.jar" --domain domain1 --domaindir "C:\Program Files\glassfish-v3-prelude\glassfish\domains\domain1"

It appears that NetBeans doesn't close them when I restart.  Other than forcibly killing the .exe's does NetBeans have a feature to kill the old one when I do a build?


How to get administration views to work?

Question: As my content began to expand into a large repository I started to miss the feature of being able to filter content by a simple "title contains" criterion. I found out Administration Views that got installed by Admin Menu. However, the content view is contaminated by a known bug. It allegedly comes from incompatibility with VBO. This prevents the view from functioning or being edited.
Is anyone successfully running admin views, caring to list the module versions for Views, VBO, Admin Menu?
Answer: I'm sure your problem is already gone by now but for those who might be searching for ways to make Admin Views and VBO work, the versions I'm using are 7.x-1.3 and 7.x-3.2 respectively.
You would need to clear Drupal cache for the default admin pages to be overridden by the newly added Admin Views.


How does speaker design affect audible sound?

Question: Speaker design for guitar/bass cabinets seems to have been the same for the past 50 years. A traditional guitar/bass cabinet is usually made a wood, with 8-12 inches speakers mounted to the frame, etc.
PA speaker (and some bass cabinets) have adopted a "big" and "little" design

large bass speaker to cover bass frequencies
small tweeter to cover the rest of the EQ spectrum
sometimes has a cross-over to handle EQ variances between the two speakers

Some of the latest mixing speakers have what are called coaxial speakers. These involve a bass speaker with a tweeter mounted directly on top. All of the sound comes from one source, rather than two.
Obviously these designs are not limited to the paradigms mentioned.
I am looking for a credible source to explain how these designs differ from each other in terms of how we perceive sound.
For example, most guitar player's a familiar with the fact that their guitar amp sounds different depending on where they stand in the room.
Apparently, some modelers use powered coaxial monitors to alleviate this issue. Why is this so? What about the design makes this possible?
- What designs are best (acoustically speaking, no matter what) at
   delivering the full spectrum of EQ?
 - Is it impossible for sound to
   leave two speakers at the same time and reach your ears?
 - Are all of these differences negligible to an acoustic engineer and the design doesn't matter?
Comment: You have too many questions here - are you asking "what is the difference between coaxial and separate speakers for bass/treble?" or something else. Can you clarify, and remove the extra ones.
Comment: Also, the guitar amp sounding different has nothing to do with whether it has coaxial or separate speakers.
Comment: @DrMayhem It should make a difference. Every detail in the speaker's design has an influence, including materials and positioning.
Comment: JC - yes, but look at the wording in this question. "their guitar amp sounds different depending on where they stand in the room - use powered coaxial to alleviate" - speaker design is irrelevant here
Comment: Doc, I don't understand how you discounting speaker design. Perhaps we should chat?
Comment: Hey thanks for the edit on my answer.  You are correct about the spelling of coaxial.  Not sure where my brain was.  I think the spell checker did it.  That's my story and I'm stickin to it - lol.
Answer: If we first simplify things to consider that the speakers are in an infinite space with no walls, floors or reflective surfaces, many of the things you mention have to do with, as you say, the amount of time the sound takes to get to the ear from each driver.
Let's also pretend for a moment that people have just one ear!
If you were to place two speakers in space, there will be a plane of points halfway between them where you could stand and the sound would arrive simultaneously. This is a 'good thing' as you don't then get the effects of out-of-phase waveforms reinforcing and cancelling each other, and you aren't smearing the frequency spectrum in time.
Observers not on this plane are going to receive the sound from each speaker at different times. If, however, you could put the two drivers in exactly the same place, then observers everywhere in space will hear synchronized waveforms from both drivers.
In reality, even a single person is aurally 'in two places at once', as we have two ears - so the coaxial design can be seen as advantageous for stereo imaging.
Of course in practice drivers are not point sources, and if one is mounted in front of the other then there are still time-alignment issues that need to be dealt with. In some cases the more important advantage of the coaxial design is being able to put a 2-way system in a smaller space.
Moving on to guitar / bass speakers - guitar speakers have an advantage that they are typically not required to reproduce the full frequency range. Also, if multiple speakers are not acting as a 'point source', this is seen as just part of 'the sound of the cabinet', rather than being a problem with fidelity.
Bass speakers have the advantage that the phase cancellation /reinforcement effect due to slightly differently-positioned drivers will be less marked at lower frequencies, because as the wavelengths are longer the same time difference is a smaller phase difference.
In reality, speakers exist in acoustic environments where reflections cause sound reinforcement and cancellation just as multiple drivers would - so the acoustic environment is often as important as (and should be matched with) the monitoring system.
If we finally consider that it's easier to drive a bigger speaker to produce low frequencies, and a smaller one to produce high frequencies, that crossovers aren't perfect, and that it's easier to manufacture two separate drivers than one coaxial one - you can see that there is really no one best design. It's a question of how 'hi-fi' you need to be, what your acoustic environment is, where your audience is in relation to the speakers, cost considerations, and so on.
Answer: Not quite sure exactly what you are asking (recording, live sound?) but as a guitar player who also is responsible for the PA for my band, and as a songwriter with an in- home recording studio - I have studied on this and experimented over the years.
Here are some thoughts to consider.  Different speakers are designed differently to do different things.  A guitar cabinet or bass cabinet has a speaker designed to reproduce the sounds of the instrument (within a specific sonic frequency) in a manner that the guitar player (or bass player) can hear.  In many live applications the guitar cab is mic'ed and the sound is fed to the main and monitor speakers through one or more mixers - so it is sent to the audience through the main PA speakers and the musicians on stage through floor or flying monitor speakers.
Guitar cabinet speakers are not designed to direct sound to a large audience and tend to be very directional.  So they would sound different depending on the angle of the speaker to the listeners ears, and of course whether the cab was facing or behind the listener.  That's why in live settings with higher volumes for larger audience, the musicians will usually be listening to their instruments through the monitors, not the amps (even though they may also hear some of what is coming out of the amp).
Most of the time, guitar cabinets designed strictly for guitar (or bass), have one or more speakers (usually identical), that are optimized to produce the frequencies for the intended instrument - whether bass guitar or standard guitar.  Some acoustic amps with microphone inputs may also have two different sized speakers in order to cover the more varied range of vocals in addition to guitar.
Coaxial speakers were originally designed primarily to save space. By positioning a higher frequency driver inside the cone of a lower frequency driver, two drivers can occupy the same space as one. A true coaxial speaker is actually two separate speakers (drivers) mounted concentrically, each with their own terminals and usually with a built in crossover.
Recent developments in the design of high fidelity coaxial speakers have been geared more towards taming inconsistencies in the off axis sound reflections that are characteristic of a vertically stacked driver orientation. By putting both drivers in concentric relation to one another, the sound radiates from the same point in space and will reflect off of horizontal planes (walls) AND vertical planes (such as a ceiling) at the same angle.
PA (Public Address) speakers are designed to deliver sound to a large audience over a wide area.  The cabinets and speakers ideally should be designed for as wide a dispersion pattern as possible in order to broadcast clear sound to a wider area.  Typically at least two PA speakers will be used to broadcast sound to a wider area. In larger venues many more may be used. The placement and orientation of these PA speakers will depend on the acoustic properties of the venue (if indoors) and where the audience is in relation to the speakers.
A typical PA speaker for most popular music will have two speakers (known as drivers) in the enclosure - a low frequency driver and a high frequency driver.  You can find them with a low, mid and high frequency driver known as a 3 way speaker.
The PA speaker must cover the entire frequency spectrum as they will be tasked to deliver not only the sound of the instruments, but the vocals as well, to the audience.  For bass heavy music you will often have one or more sub-woofers incorporated in the the PA speaker array to handle the lowest frequencies (bass guitar and kick drum).
The low frequencies will be directed to the sub woofers through a crossover either in the speakers themselves or in the mixer, depending on the equipment used.  The cabinet of a sub-woofer (as well as many bass guitar cabinets) are designed to optimize the low frequencies.  The cabinets are engineered to reflect and radiate the sound waves coming from a large speaker cone moving over a larger area at a slower rate.  So the cabinet design itself will have a significant impact on the way these low frequency speakers sound.
PA speakers are constructed to withstand higher wattage amplifiers required to render distortion free sound to a larger audience.  Lower wattage amplification may not drive them sufficiently to sound good so the same type speaker would sound bad in a 100 watt guitar amp - but the speaker cone in the guitar amp would be reduced to shreds as soon as a 800 watt PA amp sent an electrical signal to the voice coil.
Some PA speaker systems feature an articulated array of speakers angled to point in different directions to widen the dispersion pattern.  In addition to the articulated speakers, the Bose L-1 and L-1 compact speakers for small to medium venues, also feature a line array system that uses the physics of the sonic wave form to allow the sound waves from multiple speakers to push each other along, thereby reaching a greater distance with lower volume.  In large venues, this line array phenomena is used by arranging multiple PA speakers in a vertical array - either stacked on the floor or stage or flying overhead from trusses.
Because of advancement in amplification technology allowing for high powered amplifiers that are extremely light weight, there is a trend in PA speaker design towards what are known as powered PA speakers.  These speaker cabinets have a built in amplifier just for the drivers inside that one cabinet - and tend to offer more headroom and higher volume before distortion than many of the passive speaker systems offer.
In live settings there is one other type speaker that you will see.  The stage monitors are designed to allow the musicians to hear what they are playing.  They are very similar in design to PA speakers in that they must deliver the entire frequency range, but are usually smaller and often wedge shaped so they will angle up towards the musician's ears when sitting on stage.
For studio use, the speakers are designed for close proximity monitoring (listening) in a very quiet room with controlled sonic properties.  They don't require as much amplification as a PA speaker and the design can focus more on optimal sound quality than ability to withstand high wattage amplification.  Studio monitors will generally be two or three way with possibly a low and mid and high frequency driver to cover then entire sonic frequency range.
But while studio monitors sound great in that very controlled listening environment, they would not be effective at all for live sound reinforcement.
It would be great if we could get the same high fidelity sound that studio monitors are capable of producing in a live music sound reinforcement application.  But even if we could, the varying demands (indoors, outdoors, acoustic properties of the room, ambient noise) of the various settings where live music is played, would have as much of an impact on what the listener perceived than the speaker design itself.
But I have been really impressed with the sound of some of the newer powered PA speakers.
Hope this will help shed some light on speaker design properties for different applications.


Server refused our key (AWS) - Putty

Question: I've just signed up to AWS and launched EC2, downloaded key (.pem) file then generated ppk file using puttykeygen. Using this ppk file I've tried to log in to the server via SSH using Putty but it's giving me Server refused our key error with pop up:
Disconnected: No support authentication methods available (server sent: publickey)

I've also used both ec2-user and root but both don't seem to work with same error.
I'm using Amazon Linux AMI so this page recommends using ec2-user which I am already using.
I've also followed the instructions on that page step by step but getting the same error above.
I've also Googled around but couldn't come to the resolution. Is this a bug in Putty or am I missing something?
Comment: Found out PuttyGen generates Public Key that is different from what is supplied from AWS under authorized_keys. I had to load private key then copy paste Public Key supplied in PuttyGen then add this to authorized_keys on AWS server after logging in via browser using Java. When I used the matching generated ppk file it worked instantly after that
Comment: Can you post the solution (in above comments) to the answer section below and accept it? It'll be useful to future reader because [comment has less visibility than answer](http://meta.serverfault.com/questions/1886/how-to-handle-unanswered-questions-that-have-the-answer-in-a-comment-or-edited-i/1931#1931) and this question won't floating in un-answered pool
Comment: @masegaloeh I just did. Tx :)
Comment: I've already tried that one and that didn't work so it's not a duplicate
Comment: double check the instance you installed & double check the format of your key file.  maybe contact amazon support through their forum https://forums.aws.amazon.com/message.jspa?messageID=371632
Answer: Found out PuttyGen generates Public Key that is different from what is supplied from AWS under authorized_keys. I had to load private key then copy paste Public Key supplied in PuttyGen then add this to authorized_keys on AWS server after logging in via browser using Java. When I used the matching generated ppk file it worked instantly after that

Server refused our key (AWS) - Putty


Can I simply delete the File Entity folder from Modules if I am using Media 7.x-1.3

Question: When I try to create new content with a linked YouTube video I am getting the following error:

Fatal error: Call to undefined function file_info_file_types() in /home/setstart/public_html/sites/all/modules/media/media.module on line 1084

I have inherited a site that use Media 7.x-1.3
I see that the following Module is also installed - File Entity 7.x-2.0-unstable7
I see from the following threads that the file entity submodule within Media should be used not the standalone one.
http://drupal.org/node/1516804
http://drupal.org/node/1850324
So it looks like File Entity 7.x-2.0-unstable7 should never have been installed.
Can I simply remove the independent File entity module? I see a lot of other modules state they depend on it (so I can't disable it from admin screen)
If not what is my best option? Upgrade to Media 2.x?
Comment: Deleting the folder outright will leave your site in a pretty miserable state (unusable until you fix the database manually), so I would highly recommend you don't do that. The best course of action would be to disable/uninstall all modules that are dependant on the erroneous file entity module; then you can remove that one cleanly, and put in whatever version is appropriate for the version of Media that you're using before re-enabling everything
Answer: Do you have backups from before the 2.x version of File entity was installed? That would be the ideal solution because frankly, things are bad. You can't just remove the File entity 2.x module directory, because at this point the module has been installed and your data is at quite a dirty state. The only real solution is to try an in-UI disable/uninstall of File entity and any Media related modules to try and get your site to a more clean state before again installing and enabling the proper versions you need/want.


Can we say the algorithm will converge with exact $k$ steps ($k$ is number of variables) in conjugate gradient method using exact line search?

Question: I am revisiting conjugate gradient here and have this question: Can we say the algorithm will converge with exact $k$ steps ($k$ is number of variables) in conjugate gradient method using exact line search? (Assuming a general non-linear function but we can do exact line search efficiently.)
Because the key idea of conjugate gradient method is "tuning next variable will not mess up with previously tuned variable". So, if exactly line search is used, we should be about to figure out the optimal value for each variable one at a time. With $k$ steps, we can reach the optimal point.
Am I correct?
Comment: Could you elaborate a bit more on which problem you want to apply the conjugate gradient method? As Theorem 2 of the linked document is exactly your statement for the problem "computing the minimum of a quadratic function", I suppose you want to solve a different problem, right?
Answer: You may have a look into this survey paper on conjugate gradient methods for continuously differentiable functions. There you can see that a lot of assumptions on the objective and the computed directions $d_i$ are required to only guarantee convergence (see for instance their Theorem 2).
So, the answer to your question is no, in general you need more than dimension-many steps to have convergence (if there is convergence at all) for general, non-linear functions.


Como passar parâmetros bidirecional para uma diretiva AngularJS

Question: Preciso que o atributo parameterID="{{autor.ID}} que na diretiva é parameterID: '@' seja atualizado assim que for mudado, ou seja, preciso que o bind seja biderecional, vi em varios lugares dizendo para usar o parameterID: '=' mas só que me deparo com esse erro.

ERRO: angular.js:14700 Error: [$compile:nonassign] http://errors.angularjs.org/1.6.6/$compile/nonassign?p0=undefined&p1=parameterID&p2=navigator
      at angular.js:88
      at x (angular.js:10619)
      at q (angular.js:10632)
      at angular.js:16659
      at m.$digest (angular.js:18253)
      at m.$apply (angular.js:18531)
      at l (angular.js:12547)
      at s (angular.js:12785)
      at XMLHttpRequest.y.onload (angular.js:12702)
Chamada do componente Navigator

<navigator edit="false" create="true" view="false" urlCreate="/Autor/Create" urlEdit="/Autor/Editar/{{autor.ID}}" urlList="/Autor" registroCadastradoComSucesso="{{registroCadastradoComSucesso}}" parameterID="{{autor.ID}}">

    </navigator>

Diretiva

angular.module('app').directive('navigator', [function () {
    return {
        templateUrl: './AngularJS/view/Navigator/Navigator.html',
        restrict: 'E',
        scope: {
            edit: '@edit',
            create: '@create',
            view: '@view',
            urlCreate: '@urlCreate',
            urlEdit: '@urlEdit',
            urlList: '@urlList',
            parameterID: '@parameterID',
            registroCadastradoComSucesso: '@registroCadastradoComSucesso'
        },
        transclude: true,
        link: function ($scope, element, attrs) {
            $scope.urlCreate = attrs.urlcreate;
            $scope.urlEdit = attrs.urledit;
            $scope.urlList = attrs.urllist;

            $scope.edit = attrs.edit;
            $scope.create = attrs.create;
            $scope.view = attrs.view;

            $scope.registroCadastradoComSucesso = attrs.registrocadastradocomsucesso;
            $scope.parameterID = attrs.parameterid;
        },
        controller: function ($scope) {
            $scope.remove = $scope.$parent.delete;
        }
    }

}]);

Pagina HTML do navigator

 Novo

 Novo

 Editar

 Editar

 Deletar

 Deletar

 Listar Autores

Comment: Tente passar a variável diretamente, sem os brackets: `parameterID="autor.ID"`
Answer: Já viu se o {{autor.id}} tem algum valor ou se ele vem undefined?
Testa com valor estático e vê se ele funciona.
Um detalhe que eu vi na documentação é que no .JS da diretiva você usa o padrão camel-case mas no HTML você substitui o camel-case por hífens (urlEdit ficaria url-edit no HTML)

 <navigator edit="false" create="true" view="false" url-create="/Autor/Create" url-edit="/Autor/Editar/{{autor.ID}}" url-list="/Autor" registro-cadastrado-com-sucesso="{{registroCadastradoComSucesso}}" parameter-id="{{autor.ID}}">

    </navigator>

Dá um control-f "Isolating the Scope of a Directive" aqui


find dropdown by attribute disabled false

Question: I have same dropdown many times in my file like:
<select style="width:40%;" name="article[subsection_id]" id="article_subsection_id" class="article_subsection_cls" disabled="disabled"><option value=""></option>

I want to find dropdown by class article_subsection_cls or id article_subsection_id and attribute disabled is false.
Answer: Use attribute equals selector with :not() pseudo selector
$('select#article_subsection_id:not([disabled="disabled"]),select.article_subsection_cls:not([disabled="disabled"])')

If disabled property updated dynamically in that case use filter() method
$('select.article_subsection_cls,select#article_subsection_id').filter(function(){ return !this.disabled; })

UPDATE : In case there is only one element use id selector
$('#article_subsection_id:not([disabled="disabled"])')

Or you can use :enabled selector

Although their resulting selections are usually the same, :enabled selector is subtly different from :not([disabled]); :enabled selects elements that have their boolean disabled property strictly equal to false, while :not([disabled]) selects elements that do not have a disabled attribute set (regardless of its value).

$('#article_subsection_id:enabled')

Comment: @Udaykumardas :  glad to help
Comment: @Udaykumardas : inside the same element
Comment: `$('select.article_subsection_cls').filter(function(){ return !this.disabled; }).find('[value="something"]')` or `$('select.article_subsection_cls:enabled [value="something"]')`
Comment: Actually i am getting the select element by using `$('select.article_subsection_cls').filter(function(){ return !this.disabled; })[0]` code.And want to set an option selected by value.
Comment: @Udaykumardas : yup, what you need to do with that ?
Comment: want to loop all options of this dropdown.
Comment: @Udaykumardas : you want to iterate the options of enabled select tag ? then `$('select.article_subsection_cls:enabled option').each(function(){/* code here */})`
Answer: You can use :enabled selector ,
var elements = $('#article_subsection_id:enabled,.article_subsection_cls:enabled');

Answer: you can use :not(:disabled) for selecting an element having "disabled=false"
$('#article_subsection_id:not(:disabled)')

Read more about :not selector


Consistent but apparently unsolvable system of equations

Question: I have started learning linear algebra. One of the exercise problems is as below.
Determine the value(s) of $h$ such that the matrix is the augmented matrix of a consistent linear system.
$$
\left [
        \begin{matrix}
        1 & 4 &| -2 \\
        3 & h &| -6 \\
        \end{matrix}
\right ]
$$
A simple row transformation of $R_2 = R_2 - 3R_1$ results in
$$
\left [
        \begin{matrix}
        1 & 4 &| -2 \\
        0 & h-12 &|\ \ \ \  0 \\
        \end{matrix}
\right ]
$$
I reasoned that if $h$ is $12$, though there wouldn't be any inconsistency, the system would effectively have only one equation to solve for two unknown variables and so $h \neq 12$ if we are to find the solution.
Generally how do we classify such systems, the ones which are consistent but appear unsolvable? On the other hand, is my reasoning wrong?
Answer: Your reasoning is correct. At $h = 12$, the system is consistent.
Such a system, in your case, when $h = 12$, or in general, when the augmented coefficient matrix of a system of linear equations has a row of zeros in its row-reduction, we say that the corresponding system has an infinite number of solutions.

Let's look at the system represented by your matrix.
Essentially, we can choose any arbitrary value for $y$: put $y = \alpha$.
Then $x = -2 - 4y = -2(1 + 2y) = -2(1 + 2\alpha)$
We can then represent the infinite "family" of solutions by the vector:
$$\begin{pmatrix}x \\y\end{pmatrix}:=\begin{pmatrix}-2(1 + 2\alpha) \\\alpha \end{pmatrix}$$
For any chosen value (scalar) $\alpha$, $x$ is then determined, so our solution puts some restrictions on the possible solutions, even though there are infinitely many choices for $\alpha$.
So the system having an infinite number of solutions is not equivalent to saying that every vector $\begin{pmatrix} x \\ y \end{pmatrix}$ is a solution to the system, since $x$ is a function of $y$.
Comment: Ah, makes sense. The text talked about infinite number of solutions for a system, but had presented no example and I was wondering how such a system would look like. Specifically, in this case, the infinite number of solutions is only when $h = 12$ right? The system has a unique solution if $h \neq 12$.
Comment: Thanks. I think your edit provided the necessary clarification.
Comment: Yes, exactly! $y$ would equal $0$, and $x$ would then be $-2$


Error When Changing User Role in Drush?

Question: I wanted to see if there is a way to change a user role using drush. I found this post explaining how to do it but I get an error. I replaced the actual username with "USERNAME".
drush user-add-role administrator USERNAME

> exception 'Drush\Role\RoleException' with message 'Could not find the
> role:      [error] administrator' in
> /usr/local/src/drush/lib/Drush/Role/RoleBase.php:46 Stack trace:
> #0 [internal function]: Drush\Role\RoleBase->__construct('administrator')
> #1 /usr/local/src/drush/includes/drush.inc(113): ReflectionClass->newInstanceArgs(Array)
> #2 /usr/local/src/drush/commands/core/role.drush.inc(273): drush_get_class('Drush\\Role\\Role', Array)
> #3 /usr/local/src/drush/commands/user/user.drush.inc(281): drush_role_get_class('administrator')
> #4 [internal function]: drush_user_add_role('administrator', 'USERNAME')
> #5 /usr/local/src/drush/includes/command.inc(368): call_user_func_array('drush_user_add_...', Array)
> #6 /usr/local/src/drush/includes/command.inc(219): _drush_invoke_hooks(Array, Array)
> #7 [internal function]: drush_command('administrator', 'USERNAME')
> #8 /usr/local/src/drush/includes/command.inc(187): call_user_func_array('drush_command', Array)
> #9 /usr/local/src/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
> #10 /usr/local/src/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
> #11 /usr/local/src/drush/drush.php(11): drush_main()
> #12 {main}

I am using Drupal Commons 7.50 and Drush 7.0.0.
Edit: Things I have tried:

spelling role correctly and making sure it exists
clearing cache
Comment: Probably a stupid question but does the site definitely have an "administrator" role? Have you double-checked the UI/database to be sure?
Comment: Not a stupid question. Apparently we had the role named "administrators". Awesome, thanks!
Comment: Changed the command to administrators but still get the same error.
Comment: Well that's some sort of progress I guess :) Try clearing the cache just in case
Comment: No such luck. I edited my answer to reflect things things tried.
Comment: `Changed the command to administrators but still get the same error.` @Christia  Are you sure it's the same error? did you do `drush cc all`? Before doing your user add drush command, are you inside of your Drupal folder/directory (Ex: `cd /var/www/drupal`)?
Answer: Syntax was wrong. It needed quotes and capitalization definitely matters.
drush user-add-role "administrator" USERNAME

Error When Changing User Role in Drush?


custom error message for validates_length_of :maximum and :minimum on ruby on rails

Question: I want to write a custom  error message for :minimum and other for :maximum
I have the following the code line
validates_length_of :user_name, :minimum=>5,:maximum=>30

  ej if the length of :user_name is < 5 "The user_name must to have 5 characters as minimum"
  ej if the length of :user_name is > 30 "The user_name must to have 30 characters as maximum"

Answer: The newer notation for this is:
validates :user_name,
  length: {
    minimum: 5,
    maximum: 30,
    too_short: "The user name must have at least %{count} characters.",
    too_long: "The user name must have no more than %{count} characters."
  }

More examples are listed in the documentation.
The old validates_length_of type methods are left in there for legacy support but should probably be avoided in new code.
Answer: maybe like
validates_length_of :user_name, :minimum =>5,:maximum=>30, :too_short => 'is too short', :too_long => 'is too long'
Comment: but how to remove the name of the model field in messege. I wrote this code:

  validates_length_of :subject, :maximum => 255, :too_long => 'checklist item is too long'

but my actual message  now is:  "Subject checklist item is too long"


Selecting an SVG as an Image Field value

Question: I have a Content Type, News, with an Image Field, News Icon.
When the field settings are viewed at /admin/structure/types/manage/news/fields/node.news.field_news_icon
I have supplied SVG as one of the allowed types.  I have also tried allowing only SVG.

We also have IMCE in use so I have SVG set up in the IMCE config like so at /admin/config/media/imce  I have also tried using a list separated by spaces including SVG.

The Widget settings for the field at /admin/structure/types/manage/news/form-display allow for the IMCE manager to be enabled.  I have tried disabling but it did not resolve the issue.

The widget displays and lists allowed types but no SVG.

IMCE allows upload of SVGs but when selecting one as the news_icon I get

The normal (non-IMCE) file browser gives the following when an SVG is selected for upload:

Is there a deeper setting I am missing to get SVG included in the list of allowed extensions for use as an Image Field value?
Answer: AFAIK the jpg/png/gif limitation is hardcoded in the image field, you can't solve this (only) with configuration.
SVG Image allows <code>.svg</code> files in core's image field. You can use the standard image formatter with it (or better: you must use the standard image formatter, it will not work with Focal Point or similar)
SVG formatter uses the file field and provides an SVG formatter for the file field.
Both also work with media entities, but I've not tested them with IMCE yet.
Comment: Yes, adding the file extension won't do anything. It is disabled in core I believe due to security. But there are modules that will allow it.
Comment: Thank you! Will post back here re IMCE for future readers after I get all working
Comment: Seems SVG wandered into core, currently `8.6.x-dev` (not backported to `8.5.x-dev` yet): https://www.drupal.org/project/drupal/issues/1014816. Though I couldn't apply the patch against the current `8.6.1` release.
Answer: SVG Image Field is an alternative to SVG Formatter and SVG Image that is worth a try.
Some of the advantages of this module over these other two:

Unlike SVG Formatter, you may set custom alt text on SVGs. SVG Formatter relies on core file field under the covers, which does not support alt at the database schema level.
Unlike SVG Image module, you may still use Crop API, Focal Point, and other raster-based image modules on your normal image fields without affecting SVGs because SVG Image Field provides a separate field type and doesn't alter or touch regular core image field.  The SVG Image module modifies core image fields to allow SVG files to be uploaded along side raster-image files like PNG, JPG, GIF, but comes with some costly tradeoffs and limitations.
Far less configuration required out of the box:  With SVG Formatter and SVG Image modules, the site builder must take additional steps to configure their fields to display all images appropriately, eg adding SVG extension to the file field settings, selecting a field formatter, playing with and testing formatter settings with different image types to see what breaks.
Less end-user confusion and error states when trying to combine with other image types:  With SVG Formatter, if user uploads non-SVG file it will break output. This isn't possible with SVG Image Field, because the file extensions are limited to only SVGs.
Similar to the above, with SVG Formatter, if user uploads png and the field is configured with an inline output as the formatter, it will break output.
SVG Image Field has an image preview feature on file upload out of the box. SVG Formatter does not.
For existing installations, there are fewer opportunities to break the site with a misconfiguration.  SVG Image Field solves the specific SVG use case, and doesn't interfere with other existing image field configs.

If you happen to be using Media in core, and Media Library check out my other post which explains how to set up SVG Image Field with Media module to end up with a single Media field on your node that can reference either Images or SVGs.


Bootstrap button group malfunction when they have tooltips

Question: I have a single group button with a tooltip enabled for each button.
On hover in the last button of the group, the tooltip causes misalignment and the border of the button is no longer rounded. I know that the  tooltip style is overriding the button style but I cannot find where is.
DEMO: Bootply
UPDATE:
Fixed by changing the  element with a <button> elemnt and then using a custom style
Button:
<button class="btn btn-small btn-danger" data-toggle="modal" title="Unlink" data-target="#@item.WOWorkPermitID"></button>

CSS:
.btn-group > .btn:last-of-type {
    -webkit-border-top-right-radius: 4px;
    -moz-border-top-right-radius: 4px;
    border-top-right-radius: 4px;
    -webkit-border-bottom-right-radius: 4px;
    -moz-border-bottom-right-radius: 4px;
    border-bottom-right-radius: 4px;
}

DEMO --> Bootply
Related post --> twitter bootstrap tooltips over buttons inside table not displaying correctly
Comment: this http://stackoverflow.com/questions/18488413/bootstrap-tooltip-with-dropdown-in-button-group-seems-to-have-an-effect seems to be the best answer
Answer: try
 $(".btn").tooltip({
    'placement': 'top',
    container: 'body'
 });

it worked to me :)
Comment: adding the `container` parameter worked for me. I didn't need to add any custom stylings
Answer: The last item isn't a button, it's an anchor. Try changing it to a button like the first two items.
Comment: I think that is not the problem. The '' item has a 'class="btn btn-small btn-danger"'. In addition, is working properly by removing the tooltip Javascript. Look at this DEMO using three buttons with tooltips --> http://bootply.com/72515
Comment: Yeah I saw that now, I've just tried stripping it down to the bare minimum and it's still happening, not sure if the tooltip control just doesn't play nicely with the button styling?
Comment: For sure!! That is! Althought the `` element is acting as a button, the CSS is not applying the `.btn-group > .btn:last-of-type` style when it has a tooltip, so the border is not rounded. I have fixed it by changing the `` element with a `` and then using a custom style. See my updated post.
Comment: Ahh cool, well done. I've also just done a project using Bootstrap and I remember their being a few oddities like this.
Comment: Thanks @Damon :) Even though my question (and subsequent posted solution) shows effort, there remain people on this website giving downvotes with no meaning omg!


Consequences of non normal-distribution multiple regression

Question: I am currently writing my thesis using multiple regression.
However my data does not meet the regression assumption of normal distribution.
I want to describe that, due to the non normal distribution, the interpretation of the data is limited. I don't want to transform the data, i just want to say what the impact of the non normal distribution on my regression results (N =110) is.
If have been googling a lot, however only found the assumptions, but never really consequences when i still conduct my tests.
Does any of you know, what the consequences of non normal distribution for my regression results are? And also very important, which paper could be cited?
I would be very grateful for your hint!
Comment: Does anybody actually have normal data? How non-normal are we talking? With 110 observations mild non-normality may be of little consequence. If you're constructing prediction intervals it might matter a lot more. What kinds of inference were you performing?
Answer: Regression does not assume normal distribution of your data.
Regression assumes normal distribution of the errors about predicted values of $y$ (i.e. $y_{i} - \hat{y}$).
You're welcome.
Comment: Good concise statement. Much more is easily accessible on this site e.g. http://stats.stackexchange.com/questions/16381/what-is-a-complete-list-of-the-usual-assumptions-for-linear-regression/16460#16460
Comment: Thanks Alexis - thats what I meant. So concluding from Nick's link, when my errors are not normally distributed, my beta values are wrong? Is that right? And why is this so?
Comment: Yes. See for example, Anscombe, F. J. (1973). Graphs in statistical analysis. *The American Statistician*, 27(1):17–21 for an example of what statistical outliers can do to bias regression estimates. However, the normality assumption may not be the worst assumption to violate, particularly for large data sets: Lumley, T. and Emerson, S. (2002). The Importance of the Normality As- sumption in Large Public Health Data Sets. *Annual Review of Public Health*, 23:151–69.
Comment: From Lumley and Emerson: "_In small samples most statistical methods do require distributional assumptions_". Yes, it's different when you can rely on asymptotic normality, but... is Jay interested in small or large samples? Is N=110 a large sample?
Comment: Hence, "particularly for large data sets."


Why don't NFL defenders wrap up during tackles as much as they used to?

Question: 20, 30 years ago, by far the most common tackling style was for a defender to wrap up the ball carrier and drag him to the ground.
In the last 10 years, glancing tackles have become a lot more common.  The kind where they just hit the ball carrier with no attempt to wrap their arms around him.
Why is this?  What's the advantage and disadvantage to this type of tackle, and why has it become more prominent in the NFL?
Answer: The only reason for this is because of the concussion protocols they have to follow. I to have seen this but the only reason they do that is to

Not get penalized
Stay Safe

Like the hit to Antonio Brown By Vontaze Burfict you could do that 20 - 30 years ago but not know because of all of the rules. Just because of the rules they are doing this.
Advantage is to stay safe but an disadvantage is that it is not very effective sometimes.
Comment: I don't see how not wrapping up follows from safety/concussion.  Wrapping up is the *safer* way to tackle, as opposed to glancing hits which have to be harder and therefore more likely to cause concussions.


What is Left and Right in the Either module in Flutter?

Question: I'm looking at some Flutter code that looks like this :
    try {
      return Right(_doSomethingAndReturnSingleValue());
    } on CustomException {
      return Left(CustomException());
    }

Left and Right are from the core either.dart package, this is the code :
class Left<L, R> extends Either<L, R> {
  final L _l;
  const Left(this._l);
  L get value => _l;
  @override B fold(B ifLeft(L l), B ifRight(R r)) => ifLeft(_l);
  @override bool operator ==(other) => other is Left && other._l == _l;
  @override int get hashCode => _l.hashCode;
}

class Right<L, R> extends Either<L, R> {
  final R _r;
  const Right(this._r);
  R get value => _r;
  @override B fold(B ifLeft(L l), B ifRight(R r)) => ifRight(_r);
  @override bool operator ==(other) => other is Right && other._r == _r;
  @override int get hashCode => _r.hashCode;
}

I'm really struggling to make any sense of what this logic is supposed to do.
Can anyone help me understand what Left() and Right() are for in Dart ?
Comment: check this one : https://www.youtube.com/watch?v=J-vk23f6i9U
Answer: Left and Right are two generic classes inherited from the same parent, which does almost same thing. The major difference is in the fold method implementation. The left class call the ifLeft callback and right class call the ifRight callback.
For example:
Either<CustomException, String> getSomething() {
   try {
      return Right(_doSomethingAndReturnSingleValue());
   } on CustomException {
      return Left(CustomException());
   }
}

No matter what happens the above function will return either an object of Either with CustomException (Means Left) or an object of Either with String (Means Right).
Now if you use the function like:
final eitherData = getSomething();

You will be getting an either object (Object of Left or Right). Instead of checking whether that eitherData is of type Left or Right, you can call the fold method on that object like below:
eitherData.fold<Widget>(
   (err) => Text('Error Happened: $err'), // ifLeft callback
   (data) => Text('Got data: $data'), // ifRight callback
)

As I mentioned earlier based on the object type the corresponding callback will get triggered and you can gracefully handle the success and error cases without writing any if else statements or type checks.


Why is the standard error of regression parameters not decreasing?

Question: I know that the standard error is calculated from looking at the sum of squared errors divided  by square root of n.
However, as we add more and more variables, we expect the sum of squared errors to decrease and eventually overfit. So I expect to see the standard error to decrease with each variable on the anova table but it doesn't.

Is it fitting a single variable each row or is the error calculated from the prediction with all previous rows too?
Comment: If you add more variables to a model you would in general expect the standard errors of the coefficients to increase so I am not sure what you are asking.
Answer: That looks like a table of jointly estimated coefficients, not an anova table.
This means the standard errors are all about the same value. You can also interpret the wald statistic and p-value as being "marginal" tests/effects. That is, if that predictor was last in a "sequential" anova table.


Monitor Network Activity of Applications and Users from the Command Line (like Top does for processor)

Question: Is there a linux command, that works like "top" (like top does for monitoring processor utilization), but shows network activity of users and applications realtime?
I want something that shows everything going on, where I don't have to specify each and everything to get an overview. Anything like this?
Comment: http://www.cyberciti.biz/tips/top-linux-monitoring-tools.html
Answer: Iptraf is pretty nice for live overviews, vnstat is a lightweight alternative for every-now-and-then statistics.
Answer: pktstat is a great cmdline utility; shows url paths etc
tcptrack is also good.
iptraf is also okay.
Answer: The best one I know of is ntop, but it display stats via a web interface on port 3000. Not sure if there's one that runs just via a terminal.


Need advice on implementing UI in WPF

Question: I need some advice on implementing UIs in WPF.
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
I've looked at MVP (and its WPF variant - MVVM), but having some trouble getting started.
Assuming I have a UI to build, here's what I think I should do:
1.
Create a "Main UI" Mediator class which specifies ALL high-level operations (LoadSettings(), SetVisibility() ) and events (not triggered by the user, e.g, model data changed) that my UI supports.
2.
Create the "Model" classes to represent the data
3.
Create "ViewModel" classes for my model classes.
4.
For complex behaviours (e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection), do not rely on ViewModels to update the UI. Instead, do it manually through the Main UI Mediator class.
5.
For simple behaviours (e.g, toggling the visibility/enabled states/etc), use WPF binding to bind the ViewModels' properties directly to the UI.
In this case, the Main UI Mediator class would maintain both the ViewModel and Model objects, and delegate user interactions (to the Model) and UI update requests (to the ViewModel/View) appropriately. The Mediator class also provides a centralised interface which specifies the functionalities of the UI, while acting as a Change Manager (described in GOF's Observer Pattern) to handle complex UI behaviour/reduce redundant UI updates.
Am I on the right track? Should I tweak my approach? Change it completely? At the moment, I lack the experience/knowledge to implement huge/complex UIs, so I don't really know whether I'm on the right track.
Thanks
Answer: This is a bit long, sorry about that!

So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.

Yep :)  Anytime you have to name a control and write "someControl dot blah" in your code-behind, that's a code smell. It's sometimes unavoidable, but try to limit it as much as possible. Your UI is a projection of the model - ViewModels and ValueConverters are a way to deal with the impedance mismatch between the two domains.
A few problems with your approach:

Create a "Main UI" Mediator class which specifies ALL high-level operations

Instead of doing this, your Window class acts as the "Controller"; the important thing is, use Commanding to define your top-level actions. This way, you can have UserControls decoupled from the Window class, because the UserControl will just call Commands.Open.Execute(null, this), and the Window can handle it, and the UserControl will never explicitly have a dependency on the Window.

Create "ViewModel" classes for my model classes.

In MVVM, the VM part is to help you out - if you can get away with binding directly to the model (i.e. the data doesn't change or you don't mind implementing INotifyPropertyChanged in your models), then doing this (even if you have to use a few IValueConverter classes) is okay. ViewModels are mostly used when the view is so different from the model representation that it'd be ugly to hack up your model, or to "tack on" extra properties that only make sense in this particular view.

while acting as a Change Manager...

Remember that WPF does this for you, via Dependency Properties and INotifyPropertyChanged; don't reinvent the wheel; if you write an OnDataUpdate() function, this is a sign you're not using data binding properly.

e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection

This is where Commanding is great - your CanExecute function can apply arbitrarily complex logic to decide whether a certain operation can be done, and if you bind it to UI elements like Menus or Buttons, they will automatically disable/enable as needed.
Comment: Hi Paul, thanks for the reply.

Just wanted to comment on the Change Manager bit.

I've used a fair bit of INotifyPropertyChanged in my code, and it's been great for immediately (and easily) updating the UI to reflect the changes (visibility, isenabled, content, etc).

However, I've also noticed that when working with complex behaviours (e.g, complex notification, delayed notification (update everything before requesting the UI to update), etc), the INotifyPropertyChanged sometimes gets invoked a little too often for comfort.
Comment: Got another question: currently MVVM relies heavily on binding and Commands. If I were to implement this in something other than WPF (like WinForms), what would the recommended approach be? The reason I mentioned the Mediator/Change Manager class in my question was because it felt like it would be something that I can easily port between WPF and WinForms (or any other GUI libraries).
Answer: It hasn't been mentioned, but do all of your UI design in XAML.
There is nothing worse than seeing WPF UI's being created via code-behind.

Need advice on implementing UI in WPF


Azure Active Directory - assign a group to an app programmatically

Question: From Azure portal, I am able to assign a group to an enterprise application.  I can also run powershell script under global admin cred as in  https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/assign-user-or-group-access-portal
Is there a way to assign groups to an application programmatically using app id, app secret from an Azure function app? this function is triggered by cosmos db.  When I add/remove groups to/from the cosmos db database, the function app is triggered to add/remove groups to/from an application.
Thanks,
Kevin
Comment: I added more details to my question. Thanks
Comment: Wouldn't you create a powershell script to do that programmatically?  It seems like the answer to your question is in your question.
Comment: I want to run from a function app, is that possible?  Thank you!
Comment: I would recommend editing your question to clarify exactly what you mean.  For example, is a "function app" something specific to Azure or are you talking about doing this programmatically from a function in an application you create (in which case you need to put information about the programming language and any frameworks you are using)?  Add that information to your original question so more people can try to answer.
Comment: If my answer is helpful for you, you can accept it as answer( click on the check mark beside the answer to toggle it from greyed out to filled in.). This can be beneficial to other community members. Thank you.
Answer: You can use Microsoft Graph API Create appRoleAssignment to assign a group to an app.
The C# code sample is here.
Remember to put the app role id into the request body. It is missing in the document. And you should specific the principalType as "Group".
Maybe this sample will be helpful.
Comment: I am able to add a group to an app from a console app. Thanks a lot Allen.
Comment: @KevinPham np:)


My question is about the Taylor formula of $f(x,y)=\sin x\sin y$

Question: I have to solve the following exercise:
Find the secondary approach of $f(x,y)=\sin x\sin y$ near the point $(0,0)$. How accurate is the approach if $|x|\leq 0{,}1$ and $|y|\leq0{,}1$?
(I have to prove that $|E|\leq {\frac{8}{6}}(0{,}1)^3$ )
$-$ I found :
the secondary approach is for $n=2$
\begin{align}f(x,y)= &f(0,0)+xf_x+yf_y+\frac{1}{2}(x^2f_{xx}+2xyf_{xy}+y^2f_{yy})\\&+ \frac{1}{6}(x^3f_{xxx}+3x^2yf_{xxy} +3y^2xf_{xyy}+y^3f_{yyy})(φ,n)\end{align}
$f(0,0)=0$
$f_x(0,0)=\cos0\sin0=0$, $f_y(0,0)=\sin0\cos0=0$
$f_{xx}(0,0)=-\sin 0\sin0=0$, $f_{yy}(0,0)=-\sin0\sin0=0$
$f_{xy}(0,0)=\cos0\cos0=1$
therefore $f(x,y)\simeq 0+0+0+\frac{1}{2}(x^20+2xy+y^20)=xy$,
the error estimation is $|E(x,y)|=\frac{1}{6}(x^3f_{xxx}+\dots+y^3f_{yyy})(φ,n)$
$-$How am I going to prove that $|E|\leq \frac{8}{6}(0{,}1)^3?$ I don't know what I have to do. Are the things that I've done above correct?
Comment: You can use [Lagrange's form of the remainder, as it looks for several variables](https://math.stackexchange.com/a/2443435/578878). The derivatives that appear therein evaluated at unknown points are nevertheless sines and cosines, which have uniform bounds, $1$.
Comment: This particular problem has the simplifying feature that the function is factorial, $f(x,y)=g_1(x)g_2(y)$. Therefore, you could deduce the bound from [Lagrange's remainder for one variable](https://en.wikipedia.org/wiki/Taylor%27s_theorem#Explicit_formulas_for_the_remainder) applied to $\sin(x)$ and $\sin(y)$ separately.
Comment: To continue on the path you delineate in your question (since, pace some comments above, the first question here is **not** to imagine other approaches), simply note that every third derivative involved in your last formula for $E$ is at most $1$, that the prefactors $x^iy^j$ involved are all bounded by $0.1^3$ and that the prefactor $\frac16$ then yields exactly the bound $\frac16\cdot8\cdot0.1^3$ you have been asked to show.
Answer: I suppose that in $0{,}1$, the comma is a decimal comma.
Observe that all partial derivatives at any order are the products of a sine or a cosine in $x$ and a sine or a cosine in $y$, up to a $-$ sign. So the absolute  value of these derivatives are bounded  by $1$, and by the triangle inequality,
$$|E(x,y)|=\frac{1}{6}|(x^3f_{xxx}+\dots+y^3f_{yyy})(φ,n)|\le \frac{1}{6}|(|x|^3 +3x^2|y|+3|x|y^2+|y|^3)$$
which is no more than $\;\dfrac{1}{6}(0.1+0.1)^3=\dfrac8610^{-3}\;$ on $\;[-0.1,0.1]\times[-0.1,0.1]$.


Launching custom chromecast receiver sometimes times out

Question: I have a custom Chromecast receiver that I launch from an Android app when the user selects their Chromecast device from the Cast button.  I find that I often get a timeout on the initial connection, but the second time it works fine.  Is the issue most likely my web server not responding fast enough, or are there other factors that might cause the timeout?
I'm getting the CastStatusCodes.TIMEOUT in onApplicationConnectionFailed().
My code to launch
(EDITED to include launchApplication)
<code>Builder builder = new GoogleApiClient.Builder(mContext);
builder.addApi(Cast.API, apiOptionsBuilder.build());
builder.addConnectionCallbacks(this);
builder.addOnConnectionFailedListener(this);
mApiClient = builder.build();

if (mApiClient == null) return;
mApiClient.connect();

...

Cast.CastApi.launchApplication(mApiClient, mApplicationId)
 .setResultCallback(new ResultCallback<Cast.ApplicationConnectionResult>() {

    @Override
    public void onResult(ApplicationConnectionResult result) {
        if (result.getStatus().isSuccess()) {
            onApplicationConnected(
                result.getApplicationMetadata(),
                result.getApplicationStatus(),
                result.getSessionId(),
                result.getWasLaunched());
        } else {
                onApplicationConnectionFailed(result.getStatus().getStatusCode());
        }
    }
});
</code>
Answer: The code you have posted is prior to loading the application so if you are getting a timeout in your onApplicationConnectionFailed, then it is further down in your code and not the part that you have posted here. If it is the loading of your application that fails, you need to check on your network and web server, etc.
Comment: Do you have any thoughts on the situation when receiver app **successfully**  launches after calling `launchApplication()` but `result.getStatus()` returns with TIMEOUT (instead of success)? Then receiver app closes after some time (due to no senders conncted to it).
Comment: If receiver gets the launch message, it will start the launch process and then responds to the sender; however if the response doesn't make it to the sender in time, sender considers that a timeout; in fact it wouldn't know the launch was successful or not since it didn't receive any message; so it is possible to see the app launched and yet sender throws a timeout error. I suggest you check your receiver log as well and see if there is anything there that can point you to the cause.


Formula for marginal probability in CRF++

Question: On the website for CRF++ http://crfpp.sourceforge.net/
they mention that marginal probabilities can be output for each possible label.
My question is, in CRF theory, what's the formula for this marginal probability? I think it's:
$$p_{_\theta}(Y_{_j} = y | X ) = \frac{\alpha_{_j}(y|X)\beta_{_j}(y|X)}{Z_{_\theta}(X)}$$
where Yj is a sebsequence of Y, which is the sequence of labels, conditioned on the observed variable X, and Z(X) is a normalization function of X, and α and β are the forward and backward probabilities used in forward-backward algorithms.
Is this correct?
Answer: According to An introduction to conditional random fields1 the marginal distribution in (4.20) is:
$p(y_t|x) = \frac{1}{Z(x)} \alpha_t(y_t) \beta_t(y_t)$ (p. 318).
The normalization function of X, $\alpha$ and $\beta$ are identical to what you mention. We can of course rewrite this to:
$p(y_t|x) = \frac{\alpha_t(y_t) \beta_t(y_t)}{Z(x)}$
Whether or not to include the $\theta$ and to use $X$ or $x$ seem like notation preferences. $y_t$ is a shorthand for $Y_t = y$ (p. 273), 2
$p_\theta(Y_t = y|X) = \frac{\alpha_t(Y_t = y) \beta_t(Y_t=y)}{Z_\theta(X)}$
I am not sure about $\alpha_t(y_t)$ being equal to $\alpha_t(y|X)$. Not sure of this is correct, but it might help someone.
1: Sutton, C., & McCallum, A. (2012). An introduction to conditional random fields. Foundations and Trends in Machine Learning, 4(4), 267-373.


Erro no isset PHP

Question: Está dando erro quando utilizo o isset com os métodos novos do PHP:
<?php
require './fb.php';
if (isset(filter_input(INPUT_SESSION, "fb_access_token")) && !empty(filter_input(INPUT_SESSION, "fb_access_token"))):
    echo "Ta logado!";
else:
    header("Location: login.php");
endif;

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in C:\wamp64\www\bw7\index.php on line 9

Ja utilizando variaveis globais, funciona:
<?php
require './fb.php';
if(isset($_SESSION["fb_access_token"])):
    echo "Ta logado!";
else:
    header("Location: login.php");
endif;

Por que?
Comment: Acabei de ver que o INPUT_SESSION não foi implementado ainda.
Comment: Não pode usar `isset()` em expressões, pode trocar por `empty()` caso a versão do php seja a 5.5 ou superior.
Comment: Mas o filter_input(INPUT_SESSION, "fb_access_token") não faz a mesma coisa do $_SESSION["fb_access_token"])?
Answer: isset() não foi feita para ser usada com expressões, a documentação diz qual é o proposito.

Determine if a variable is set and is not NULL.

Tradução:

Determinada se a variável está setada e não é nula.

Não faz sentido um código como
isset(count(false));

empty() a partir do php5.5 suporta expressões então nesse caso é o mais adequado. Se quer verificar se existe algo na sessão vá direto ao ponto com:
if(!empty($_SESSION["fb_access_token"])){
   echo 'logado';
}else{
    header("Location: login.php");
}

Relaciondas:
Posso usar empty e isset em uma variável?
Quando devo usar empty ou isset?
Answer: É por causa da expressão, tente fazer desta forma:
<?php
require './fb.php';
if (isset(filter_var("fb_access_token")) && !empty(filter_var("fb_access_token"))):
    echo "Ta logado!";
else:
    header("Location: login.php");
endif;

Erro no isset PHP


Using unix & php get subfolders' names to put into a .csv

Question: I have zip file that I get that, when unzipped, has several subfolders each containing a csv called report.csv:
the_folder/
    1234/report.csv
    abcd/report.csv
    jklm/report.csv
    5678/report.csv

Each CSV's has columns & content like:
almonds, biscuits, cookies, dog_biscuits
123, 321, 333, 444
555, 666, 777, 888
444, 551, 555, 999 (and so on for 75 lines or so)

I want to put their into a combined CSV file. I'd been using exec in a PHP file to do this:
exec("cat /path/the_folder/*/report.csv > /path/combined.csv");

And then using sed to remove the duplicate "almonds, biscuits, cookies, dog_biscuits" header rows.
Now I need to take the names of the subfolders and put them into the lines of combined.csv.
So, there will be a column added to the CSV ("subfolder_name") and then in that column the name of the folder that line had come from. Something like
almonds, biscuits, cookies, dog_biscuits, subfolder_name
123, 321, 333, 444, 1234
555, 666, 777, 888, 1234
444, 551, 555, 999, abcd
333, 333, 111, 222, abcd
111, 222, 444, 333, abcd (etc and so on for 300 lines)

What is the smartest, simplest, most efficient way to go about doing this?
Answer: Try this:
$folder_list = array(); // USE YOUR CODE TO GET FOLDER LIST
$combined_output = "";
$folder_i = 0;
foreach ($folder_list as $folder) {
   $file = file($folder . "/report.csv");
   foreach ($file as $line_i => $line) {
      if (($folder_i == 0 && $line_i == 0) || $line_i > 0) {
         $combined_output .= $line . PHP_EOL;
      }
   }
   $folder_i++;
}

$f = fopen("combined.csv", "w+");
fwrite($f, $combined_output);
fclose($f);

Comment: ahh tha totally makes sense thank you! and it doesn't even have to use all that "exec". Thanks a lot.
Answer: You can try
$folderList = array (
        "1234/report.csv",
        "abcd/report.csv",
        "jklm/report.csv",
        "5678/report.csv"
);

$combinedCSV = "result_combine.csv";
$headers = array (
        "almonds",
        "biscuits",
        "cookies",
        "dog_biscuits"
);
touch ( $combinedCSV );

$fp = fopen ( $combinedCSV, 'w' );
fputcsv ( $fp, $headers ); // Add headers
foreach ( $folderList as $file ) {
    if (($handle = fopen ( $file, "r" )) !== FALSE) {
        while ( ($data = fgetcsv ( $handle, 1000, "," )) !== FALSE ) {
            if ($data [0] == "almonds") // Remove Headers
                continue;
            fputcsv ( $fp, $data );
        }
        fclose ( $handle );
    }
}

fclose($fp);

I hope it helps
Thanks
Comment: Its ok you are welcome .. // Make sure you remove the multiple headers .. since they are all contained in all files
Answer: TXR:
@header
@(output)
@header, subfolder_name
@(end)
@(next :args)
@(collect)
@folder/@email@example.com
@  (next `@folder/@email@example.com`)
@header
@  (collect :vars ())
@line
@    (output)
@line, @subfolder
@    (end)
@  (end)
@(end)

Run:
$ txr catname.txr folder/*/*.csv
animal, sound, subfolder_name
dog, bark, abcd
horse, neigh, abcd
cat, meow, efgh
cow, moo, efgh

Data:
$ ls -R folder/
folder/:
abcd  efgh

folder/abcd:
a.csv

folder/efgh:
e.csv

$ cat folder/abcd/a.csv
animal, sound
dog, bark
horse, neigh

$ cat folder/efgh/e.csv
animal, sound
cat, meow
cow, moo


href não executa jQuery e nem function

Question: Ao clicar no link Responder o código não executa, não mostra o alert do jQuery e nem da function, tbm não mostra erro no console, não chega nem a executar.
$('#post-forum').last().append('
Responder
');

$('#responder').on('click', function (event) {
    // alert('teste');
    teste();
    event.preventDefault();
});

function teste() {
 alert('teste');
}

Comment: Tente mudar a primeira linha assim: `$('#post-forum').last().append('Responder');`
Comment: Obrigado, acabei de tentar, e tbm não funcionou, ele tenta pegar o valor do href.
Answer: Eu reparei que estás a apontar um .last() para um id na primeira linha do teu código, o que mais certamente deverá ser a razão pelo qual o código não está a executar.

id's são para ser utilizados apenas uma única vez no DOM.
  Para identificar mais que um elemento com o mesmo nome, devemos utilizar classes.

$('.post-forum').last().append('
Responder
');

$('#responder').on('click', function (event) {
    // alert('teste');
    teste();
    event.preventDefault();
});

function teste() {
    alert('teste');
}

1

2

3

href não executa jQuery e nem function


Definition of identity in a monoid

Question: I'm having trouble understanding the way the identity element is defined in Lang's Algebra. Below is the relevant information.
Suppose we have a monoid G with elements $x_{1},...,x_{n}$. We can define their products like so, $$\Pi_{v=1}^{n} = (x_{1}...x_{n-1})x_{n}$$ We define $$e=\Pi_{v=1}^{0}x_{n}$$ where $e$ is the identity element of the monoid. I do not understand why this definition of $e$ makes sense. It seems to me that this is saying $e=x_{1}x_{0}$, so in particular, $x_{0}$ is the inverse of $x_{1}$. Thank you in advance.
Comment: In this definition $v$ is supposed to run through the *set* $\{1,2,\cdots,n\}$.  So if $n=0$ this set is empty, and so you have the *empty product* which is defined to be the neutral element of the monoid -- this is the only reasonable way to define an empty product.  So Lang isn't defining the neutral element there, he's just giving a convention for empty products.
Comment: See also my [answer here](http://math.stackexchange.com/questions/6832/why-is-two-to-the-power-of-zero-equal-to-binary-one/6838#6838) on empty exponents, products and sums.
Answer: This is just an empty product - the notation $\prod_{v=i}^j$ is shorthand for $\prod_{i\leq v\leq j}$, and there is no $v$ such that $1\leq v\leq 0$, so $\prod_{v=1}^0 x_v$ is a product of no elements, not $x_1x_0$.
Answer: This expression is the empty product and not the product of $x_0$ with $x_1$. As it is mentioned in p.4 below this expression, it is a matter of convention to denote the identity element as the empty product.

Definition of identity in a monoid


Como gerar um grafico com uma curva semelhante ao "seno" em jquery flot?

Question: Amigos,
Estou usando o flot para um projetinho de simulacao de ECG (eletrocardiograma), e dei de cara com um problema, que acho que eh mais de matematica do que de programacao...
Entao desculpem se estou explicando mau.
BOM, meu problema eh fazer a transicao do batimento normal, para maior! (ou seja o que acontece quando se aplica o medicamento)
Por exemplo:
O batimento  esta em 70, e aplico adrenalina, e este deve ir a 210.
Fazer isso em linha reta eh tranquilo, como neste exemplo:(exemplo do proprio flot) (que vai de "6M" ate "TE")

Por favor veja o codigo de exemplo no fiddle

Mas eu preciso se que seja uma forma de onda como um "seno"  como este:(que vai de "6M" ate "TE")

EIS minha questao para o float:

Simplificando a pergunta, como eu faria no jquery flot (em realtime), para gerar um grafico que comeca em X e vai ate Y, com uma "curva" semelhante a um seno?
Comment: Se você conseguir fazer um [mcve] ou ao menos [edit] sua pergunta e colar o trecho de código que gera a rampa reta, fica mais fácil para ajudarmos com o "easing" da curva. Tem várias maneiras de fazer, mas ajudaria muito partir do seu código já existente. Vale notar que biblioteca de "easing" do jQuery (a mesma usada para animações) é uma boa referência (e talvez até seja o caso de reaproveitar). Basicamente essas fórmulas usam a rampa como entrada (de 0 a 1, por exemplo), e devolvem uma curva logaritmica.
Comment: Editei minha pergunta. Por favor veja o codigo de exemplo no fiddle
https://jsfiddle.net/Yamamila/5zmxc5Lu/40/
Answer: Em princípio, o que você procura é um Envelope, para modificar a onda principal. Para simplificar as coisas, você pode criar uma função que pegue um valor linear, e transforme numa curva.
Veja um exemplo bem simples:
function Easing( i ) {
    i *= 2;
    if (i<1) return 1/(2-i)-.5;
    return 1.5-1/i;
};

Se alimentar esta fórmula linearmente com um valor de 0 a 1, receberá de volta um valor também de 0 a 1, só que não linear.
O que você precisa fazer, no caso é pegar a amplitude da onda principal, e multiplicar pelo resultado da fórmula.
Segue um exemplo bem básico de uso. O código extenso é para desenhar o canvas, mas o que interessa é apenas a aplicação da fórmula:

function Easing( i ) {
 i *= 2;
 if (i<1) return 1/(2-i)-.5;
 return 1.5-1/i;
};

//demonstração:
var canvas = document.getElementById("out");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var data;

context.beginPath();
context.moveTo(0,height);
context.strokeStyle = 'red';
for(i=0; i<=100; i++)
{
  data = i/100; //linear
  context.lineTo(i/100*width,height-data*height);
  context.stroke();
}

context.beginPath();
context.moveTo(0,height);
context.strokeStyle = 'blue';
for(i=0; i<100; i++)
{
  data = Easing( i/100 ); //usando função
  context.lineTo(i/100*width,height-data*height);
  context.stroke();
}
#out {width:300px; height:200px; border:1px dotted #999}
<canvas id="out"></canvas>

Teste também no CODEPEN.
Lembre-se de que o próprio jQuery tem funções de easing, que já fazem coisa parecida. Normalmente são usadas para animações, mas nada impede de aplicar em gráficos:

https://jqueryui.com/easing/

Neste site tem uma série de fórmulas que podem te interessar:

http://www.gizma.com/easing/
Comment: @CamilaYamamoto adaptei a função no seu código. Na verdade, para usar envelopes, precisa resolver o conjunto todo, está um pouco complexa demais a função toda, mas aí já foge do foco da pergunta:  https://jsfiddle.net/5zmxc5Lu/44/ - como está um bocado simplificado, se você "desligar" o botão no meio da curva, não vai ficar legal o resultado, precisaria de uma atenuação. Mas se esperar chegar no máximo e clicar de novo, a curva fica razoável. Trocando a fórmula do Easing você muda a forma da curva.
Comment: você é o the best! :D
Comment: Estou tentando estudar como usar seu exemplo e,  como são valores fixos, parece funcionar bem mas no meu caso eh uma animação, e estou apanhando pra adaptar,  ja que os valores vão mudando, Na verdade acho que e falta de experiencia minha mesmo. Bom coloquei um exemplo no fiddle como você pediu. mas não consegui criar o tal envelope. ou seja transformar aquela reta em seno.
https://jsfiddle.net/Yamamila/5zmxc5Lu/40/
Comment: estou com mais uma duvida no post http://pt.stackoverflow.com/questions/168940/como-usar-transicoes-de-tempo-em-uma-animacao-canvas  , quem sabe você saiba como ajudar!  adoro suas  dicas!
Comment: Meu codigo nao ficou igual, mas estudar o codigo que voce deu de exemplo me possibilitou adaptar para minha necessidade!  e consegui fazer!   obrigadaaa!


Migrating from ADFS 1.1 to ADFS 2.0

Question: We're planning to migrate from ADFS 1.1 to ADFS 2.0 and I've been researching for a whitepaper on the subject with out much luck.
Any one has a reference to such?
Answer: This should help . http://technet.microsoft.com/en-us/library/ff678035(WS.10).aspx

Migrating from ADFS 1.1 to ADFS 2.0