qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | Run this command :
```
chmod -R 777 var/ pub/
``` | ```
Run this command:
sudo chmod -R 777 var/
``` |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | Change the user for Magento directory and then set permission for all folders
```
sudo chown -R "$USER":www-data /webdirectory
cd <your Magento install dir>
find . -type f -exec chmod 644 {} \; // 644 permission for files
find . -type d -exec chmod 755 {} \; // 755 permission for directory
find ./var -type d -exec chmod 777 {} \; // 777 permission for var folder
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc
chmod 644 ./app/etc/*.xml
chown -R :<web server group> .
chmod u+x bin/magento
``` | Run this command For Ubuntu
---------------------------
sudo chmod -R 777 var/\* pub/\* generated/\* |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | First Set proper permission to your setup as per magento2 [permission](https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html) guidelines.
You need to add your current group to apache user.
**For Ubuntu:**
```
sudo usermod -a -G www-data $USER
```
**For CentOs:**
```
sudo usermod -a -G apache $USER
```
If you have any issue after this, then you can simply grant ownership of any inaccessible files or folders by below command.
**For the entire folder.**
```
sudo chown -R www-data:www-data /var/www/html/your-project/var
```
**For single file.**
```
sudo chown www-data:www-data /var/www/html/your-project/var/somefile.php
``` | Run this command :
```
chmod -R 777 var/ pub/
``` |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | First Set proper permission to your setup as per magento2 [permission](https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html) guidelines.
You need to add your current group to apache user.
**For Ubuntu:**
```
sudo usermod -a -G www-data $USER
```
**For CentOs:**
```
sudo usermod -a -G apache $USER
```
If you have any issue after this, then you can simply grant ownership of any inaccessible files or folders by below command.
**For the entire folder.**
```
sudo chown -R www-data:www-data /var/www/html/your-project/var
```
**For single file.**
```
sudo chown www-data:www-data /var/www/html/your-project/var/somefile.php
``` | Run this command For Ubuntu
---------------------------
sudo chmod -R 777 var/\* pub/\* generated/\* |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | First Set proper permission to your setup as per magento2 [permission](https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html) guidelines.
You need to add your current group to apache user.
**For Ubuntu:**
```
sudo usermod -a -G www-data $USER
```
**For CentOs:**
```
sudo usermod -a -G apache $USER
```
If you have any issue after this, then you can simply grant ownership of any inaccessible files or folders by below command.
**For the entire folder.**
```
sudo chown -R www-data:www-data /var/www/html/your-project/var
```
**For single file.**
```
sudo chown www-data:www-data /var/www/html/your-project/var/somefile.php
``` | Change the user for Magento directory and then set permission for all folders
```
sudo chown -R "$USER":www-data /webdirectory
cd <your Magento install dir>
find . -type f -exec chmod 644 {} \; // 644 permission for files
find . -type d -exec chmod 755 {} \; // 755 permission for directory
find ./var -type d -exec chmod 777 {} \; // 777 permission for var folder
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc
chmod 644 ./app/etc/*.xml
chown -R :<web server group> .
chmod u+x bin/magento
``` |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | First Set proper permission to your setup as per magento2 [permission](https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html) guidelines.
You need to add your current group to apache user.
**For Ubuntu:**
```
sudo usermod -a -G www-data $USER
```
**For CentOs:**
```
sudo usermod -a -G apache $USER
```
If you have any issue after this, then you can simply grant ownership of any inaccessible files or folders by below command.
**For the entire folder.**
```
sudo chown -R www-data:www-data /var/www/html/your-project/var
```
**For single file.**
```
sudo chown www-data:www-data /var/www/html/your-project/var/somefile.php
``` | Check below command for set permission.
```
find var vendor pub/static pub/media app/etc -type f -exec chmod u+w {} \; && find var vendor pub/static pub/media app/etc -type d -exec chmod u+w {} \; && chmod u+x bin/magento
``` |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | From Magento DevDocs:
The sections that follow discuss requirements for one or two Magento file system owners. That means:
**One user**: Typically necessary on shared hosting providers, which allow you to access only one user on the server This user can log in, transfer files using FTP, and this user also runs the web server.
```
find app/code var/view_preprocessed vendor pub/static app/etc generated/code generated/metadata \( -type f -or -type d \) -exec chmod u-w {} + && chmod o-rwx app/etc/env.php && chmod u+x bin/magento
```
**Two users**: We recommend two users if you run your own Magento server: one to transfer files and run command-line utilities, and a separate user for the web server software. When possible, this is preferable because it’s more secure.
```
find var generated pub/static pub/media app/etc -type f -exec chmod g+w {} + && find var generated pub/static pub/media app/etc -type d -exec chmod g+ws {} +
```
Check this DevDocs page for more info:
<https://devdocs.magento.com/guides/v2.3/config-guide/prod/prod_file-sys-perms.html> | Run this command For Ubuntu
---------------------------
sudo chmod -R 777 var/\* pub/\* generated/\* |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | Check below command for set permission.
```
find var vendor pub/static pub/media app/etc -type f -exec chmod u+w {} \; && find var vendor pub/static pub/media app/etc -type d -exec chmod u+w {} \; && chmod u+x bin/magento
``` | ```
Run this command:
sudo chmod -R 777 var/
``` |
167,559 | I currently have a error in my 1.9.3.2 store.
When a customer wants to reset their password, the Magento Report error page is displayed.
When check the report, I get the following error:
```
a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
```
Problem is related to the update to 1.9.3.2, where the table was not created.
Should this solve the issue?
```
CREATE TABLE `customer_flowpassword` (
`flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id',
`ip` varchar(50) NOT NULL COMMENT 'User IP',
`email` varchar(255) NOT NULL COMMENT 'Requested email for change',
`requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change',
PRIMARY KEY (`flowpassword_id`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`),
KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ;
```
How can I solve that? | 2017/04/04 | [
"https://magento.stackexchange.com/questions/167559",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] | From Magento DevDocs:
The sections that follow discuss requirements for one or two Magento file system owners. That means:
**One user**: Typically necessary on shared hosting providers, which allow you to access only one user on the server This user can log in, transfer files using FTP, and this user also runs the web server.
```
find app/code var/view_preprocessed vendor pub/static app/etc generated/code generated/metadata \( -type f -or -type d \) -exec chmod u-w {} + && chmod o-rwx app/etc/env.php && chmod u+x bin/magento
```
**Two users**: We recommend two users if you run your own Magento server: one to transfer files and run command-line utilities, and a separate user for the web server software. When possible, this is preferable because it’s more secure.
```
find var generated pub/static pub/media app/etc -type f -exec chmod g+w {} + && find var generated pub/static pub/media app/etc -type d -exec chmod g+ws {} +
```
Check this DevDocs page for more info:
<https://devdocs.magento.com/guides/v2.3/config-guide/prod/prod_file-sys-perms.html> | Change the user for Magento directory and then set permission for all folders
```
sudo chown -R "$USER":www-data /webdirectory
cd <your Magento install dir>
find . -type f -exec chmod 644 {} \; // 644 permission for files
find . -type d -exec chmod 755 {} \; // 755 permission for directory
find ./var -type d -exec chmod 777 {} \; // 777 permission for var folder
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc
chmod 644 ./app/etc/*.xml
chown -R :<web server group> .
chmod u+x bin/magento
``` |
23,122,645 | I need your help,
Is there perhaps a more efficient method to code an SQL statement to connect to the database and retrieve numerical values? My way of logic is this. Use the SQL Count to tally, store the numeric value into a var (similar to excel labelled cells), and then use the vars and output the results to an HTML table
I am wondering whether there maybe a more efficient way/method of doing so, if not am I politically correct to about the method below? I'm guessing that connecting to the DB multiple times would be somewhat slower?
I am using the Active Data Object connecting to an MS Access database (mdb file) for my own perusal.
```
var a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17
var b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17
var c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17
var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13,e14,e15,e16,e17
var f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17
var g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17
var h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14,h15,h16,h17
var i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17
var j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a3 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAB' AND [DATE RECEIVED] BETWEEN #"+date1)+"# AND #"+date1_2+"#"
a4 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a5 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a7 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a8 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBE' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a9 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBM' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a10 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
``` | 2014/04/17 | [
"https://Stackoverflow.com/questions/23122645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474921/"
] | The best place to look is the [spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835). For example,
```
b {
let x = e
op x
}
```
gets translated to
```
T(let x = e in op x, [], fun v -> v, true)
=> T(op x, {x}, fun v -> let x = e in v, true)
=> [| op x, let x = e in b.Yield(x) |]{x}
=> b.Op(let x = e in in b.Yield(x), x)
```
So this shows where things have gone wrong, though it doesn't present an obvious solution. Clearly, `Yield` needs to be generalized since it needs to take arbitrary tuples (based on how many variables are in scope). Perhaps more subtly, it also shows that `x` is not in scope in the call to `add` (see that unbound `x` as the second argument to `b.Op`?). To allow your custom operators to use bound variables, their arguments need to have the `[<ProjectionParameter>]` attribute (and take functions from arbitrary variables as arguments), and you'll also need to set `MaintainsVariableSpace` to `true` if you want bound variables to be available to later operators. This will change the final translation to:
```
b.Op(let x = e in b.Yield(x), fun x -> x)
```
Building up from this, it seems that there's no way to avoid passing the set of bound values along to and from each operation (though I'd love to be proven wrong) - this will require you to add a `Run` method to strip those values back off at the end. Putting it all together, you'll get a builder which looks like this:
```
type ListBuilder() =
member x.Yield(vars) = Items [],vars
[<CustomOperation("add",MaintainsVariableSpace=true)>]
member x.Add((Items current,vars), [<ProjectionParameter>]f) =
Items (current @ [f vars]),vars
[<CustomOperation("addMany",MaintainsVariableSpace=true)>]
member x.AddMany((Items current, vars), [<ProjectionParameter>]f) =
Items (current @ f vars),vars
member x.Run(l,_) = l
``` | The most complete examples I've seen are in [§6.3.10 of the spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835), especially this one:
```
/// Computations that can cooperatively yield by returning a continuation
type Eventually<'T> =
| Done of 'T
| NotYetDone of (unit -> Eventually<'T>)
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Eventually =
/// The bind for the computations. Stitch 'k' on to the end of the computation.
/// Note combinators like this are usually written in the reverse way,
/// for example,
/// e |> bind k
let rec bind k e =
match e with
| Done x -> NotYetDone (fun () -> k x)
| NotYetDone work -> NotYetDone (fun () -> bind k (work()))
/// The return for the computations.
let result x = Done x
type OkOrException<'T> =
| Ok of 'T
| Exception of System.Exception
/// The catch for the computations. Stitch try/with throughout
/// the computation and return the overall result as an OkOrException.
let rec catch e =
match e with
| Done x -> result (Ok x)
| NotYetDone work ->
NotYetDone (fun () ->
let res = try Ok(work()) with | e -> Exception e
match res with
| Ok cont -> catch cont // note, a tailcall
| Exception e -> result (Exception e))
/// The delay operator.
let delay f = NotYetDone (fun () -> f())
/// The stepping action for the computations.
let step c =
match c with
| Done _ -> c
| NotYetDone f -> f ()
// The rest of the operations are boilerplate.
/// The tryFinally operator.
/// This is boilerplate in terms of "result", "catch" and "bind".
let tryFinally e compensation =
catch (e)
|> bind (fun res -> compensation();
match res with
| Ok v -> result v
| Exception e -> raise e)
/// The tryWith operator.
/// This is boilerplate in terms of "result", "catch" and "bind".
let tryWith e handler =
catch e
|> bind (function Ok v -> result v | Exception e -> handler e)
/// The whileLoop operator.
/// This is boilerplate in terms of "result" and "bind".
let rec whileLoop gd body =
if gd() then body |> bind (fun v -> whileLoop gd body)
else result ()
/// The sequential composition operator
/// This is boilerplate in terms of "result" and "bind".
let combine e1 e2 =
e1 |> bind (fun () -> e2)
/// The using operator.
let using (resource: #System.IDisposable) f =
tryFinally (f resource) (fun () -> resource.Dispose())
/// The forLoop operator.
/// This is boilerplate in terms of "catch", "result" and "bind".
let forLoop (e:seq<_>) f =
let ie = e.GetEnumerator()
tryFinally (whileLoop (fun () -> ie.MoveNext())
(delay (fun () -> let v = ie.Current in f v)))
(fun () -> ie.Dispose())
// Give the mapping for F# computation expressions.
type EventuallyBuilder() =
member x.Bind(e,k) = Eventually.bind k e
member x.Return(v) = Eventually.result v
member x.ReturnFrom(v) = v
member x.Combine(e1,e2) = Eventually.combine e1 e2
member x.Delay(f) = Eventually.delay f
member x.Zero() = Eventually.result ()
member x.TryWith(e,handler) = Eventually.tryWith e handler
member x.TryFinally(e,compensation) = Eventually.tryFinally e compensation
member x.For(e:seq<_>,f) = Eventually.forLoop e f
member x.Using(resource,e) = Eventually.using resource e
``` |
23,122,645 | I need your help,
Is there perhaps a more efficient method to code an SQL statement to connect to the database and retrieve numerical values? My way of logic is this. Use the SQL Count to tally, store the numeric value into a var (similar to excel labelled cells), and then use the vars and output the results to an HTML table
I am wondering whether there maybe a more efficient way/method of doing so, if not am I politically correct to about the method below? I'm guessing that connecting to the DB multiple times would be somewhat slower?
I am using the Active Data Object connecting to an MS Access database (mdb file) for my own perusal.
```
var a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17
var b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17
var c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17
var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13,e14,e15,e16,e17
var f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17
var g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17
var h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14,h15,h16,h17
var i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17
var j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a3 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAB' AND [DATE RECEIVED] BETWEEN #"+date1)+"# AND #"+date1_2+"#"
a4 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a5 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a7 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a8 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBE' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a9 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBM' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a10 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
``` | 2014/04/17 | [
"https://Stackoverflow.com/questions/23122645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474921/"
] | The most complete examples I've seen are in [§6.3.10 of the spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835), especially this one:
```
/// Computations that can cooperatively yield by returning a continuation
type Eventually<'T> =
| Done of 'T
| NotYetDone of (unit -> Eventually<'T>)
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Eventually =
/// The bind for the computations. Stitch 'k' on to the end of the computation.
/// Note combinators like this are usually written in the reverse way,
/// for example,
/// e |> bind k
let rec bind k e =
match e with
| Done x -> NotYetDone (fun () -> k x)
| NotYetDone work -> NotYetDone (fun () -> bind k (work()))
/// The return for the computations.
let result x = Done x
type OkOrException<'T> =
| Ok of 'T
| Exception of System.Exception
/// The catch for the computations. Stitch try/with throughout
/// the computation and return the overall result as an OkOrException.
let rec catch e =
match e with
| Done x -> result (Ok x)
| NotYetDone work ->
NotYetDone (fun () ->
let res = try Ok(work()) with | e -> Exception e
match res with
| Ok cont -> catch cont // note, a tailcall
| Exception e -> result (Exception e))
/// The delay operator.
let delay f = NotYetDone (fun () -> f())
/// The stepping action for the computations.
let step c =
match c with
| Done _ -> c
| NotYetDone f -> f ()
// The rest of the operations are boilerplate.
/// The tryFinally operator.
/// This is boilerplate in terms of "result", "catch" and "bind".
let tryFinally e compensation =
catch (e)
|> bind (fun res -> compensation();
match res with
| Ok v -> result v
| Exception e -> raise e)
/// The tryWith operator.
/// This is boilerplate in terms of "result", "catch" and "bind".
let tryWith e handler =
catch e
|> bind (function Ok v -> result v | Exception e -> handler e)
/// The whileLoop operator.
/// This is boilerplate in terms of "result" and "bind".
let rec whileLoop gd body =
if gd() then body |> bind (fun v -> whileLoop gd body)
else result ()
/// The sequential composition operator
/// This is boilerplate in terms of "result" and "bind".
let combine e1 e2 =
e1 |> bind (fun () -> e2)
/// The using operator.
let using (resource: #System.IDisposable) f =
tryFinally (f resource) (fun () -> resource.Dispose())
/// The forLoop operator.
/// This is boilerplate in terms of "catch", "result" and "bind".
let forLoop (e:seq<_>) f =
let ie = e.GetEnumerator()
tryFinally (whileLoop (fun () -> ie.MoveNext())
(delay (fun () -> let v = ie.Current in f v)))
(fun () -> ie.Dispose())
// Give the mapping for F# computation expressions.
type EventuallyBuilder() =
member x.Bind(e,k) = Eventually.bind k e
member x.Return(v) = Eventually.result v
member x.ReturnFrom(v) = v
member x.Combine(e1,e2) = Eventually.combine e1 e2
member x.Delay(f) = Eventually.delay f
member x.Zero() = Eventually.result ()
member x.TryWith(e,handler) = Eventually.tryWith e handler
member x.TryFinally(e,compensation) = Eventually.tryFinally e compensation
member x.For(e:seq<_>,f) = Eventually.forLoop e f
member x.Using(resource,e) = Eventually.using resource e
``` | Following a similar struggle to Joel's (and not finding §6.3.10 of the spec that helpful) my issue with getting the For construct to generate a list came down to getting types to line up properly (no special attributes required). In particular I was slow to realise that For would build a list of lists, and therefore need flattening, despite the best efforts of the compiler to put me right. Examples that I found on the web were always wrappers around seq{}, using the yield keyword, repeated use of which invokes a call to Combine, which does the flattening. In case a concrete example helps, the following excerpt uses for to build a list of integers - my ultimate aim being to create lists of components for rendering in a GUI (with some additional laziness thrown in). Also [In depth talk on CE here](http://fpish.net/course/298) which elaborates on kvb's points above.
```
module scratch
type Dispatcher = unit -> unit
type viewElement = int
type lazyViews = Lazy<list<viewElement>>
type ViewElementsBuilder() =
member x.Return(views: lazyViews) : list<viewElement> = views.Value
member x.Yield(v: viewElement) : list<viewElement> = [v]
member x.ReturnFrom(viewElements: list<viewElement>) = viewElements
member x.Zero() = list<viewElement>.Empty
member x.Combine(listA:list<viewElement>, listB: list<viewElement>) = List.concat [listA; listB]
member x.Delay(f) = f()
member x.For(coll:seq<'a>, forBody: 'a -> list<viewElement>) : list<viewElement> =
// seq {for v in coll do yield! f v} |> List.ofSeq
Seq.map forBody coll |> Seq.collect id |> List.ofSeq
let ve = new ViewElementsBuilder()
let makeComponent(m: int, dispatch: Dispatcher) : viewElement = m
let makeComponents() : list<viewElement> = [77; 33]
let makeViewElements() : list<viewElement> =
let model = {| Scores = [33;23;22;43;] |> Seq.ofList; Trainer = "John" |}
let d:Dispatcher = fun() -> () // Does nothing here, but will be used to raise messages from UI
ve {
for score in model.Scores do
yield makeComponent (score, d)
yield makeComponent (score * 100 / 50 , d)
if model.Trainer = "John" then
return lazy
[ makeComponent (12, d)
makeComponent (13, d)
]
else
return lazy
[ makeComponent (14, d)
makeComponent (15, d)
]
yield makeComponent (33, d)
return! makeComponents()
}
``` |
23,122,645 | I need your help,
Is there perhaps a more efficient method to code an SQL statement to connect to the database and retrieve numerical values? My way of logic is this. Use the SQL Count to tally, store the numeric value into a var (similar to excel labelled cells), and then use the vars and output the results to an HTML table
I am wondering whether there maybe a more efficient way/method of doing so, if not am I politically correct to about the method below? I'm guessing that connecting to the DB multiple times would be somewhat slower?
I am using the Active Data Object connecting to an MS Access database (mdb file) for my own perusal.
```
var a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17
var b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17
var c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17
var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13,e14,e15,e16,e17
var f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17
var g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17
var h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14,h15,h16,h17
var i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17
var j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a3 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAB' AND [DATE RECEIVED] BETWEEN #"+date1)+"# AND #"+date1_2+"#"
a4 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a5 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a7 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a8 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBE' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a9 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBM' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a10 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
``` | 2014/04/17 | [
"https://Stackoverflow.com/questions/23122645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474921/"
] | The best place to look is the [spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835). For example,
```
b {
let x = e
op x
}
```
gets translated to
```
T(let x = e in op x, [], fun v -> v, true)
=> T(op x, {x}, fun v -> let x = e in v, true)
=> [| op x, let x = e in b.Yield(x) |]{x}
=> b.Op(let x = e in in b.Yield(x), x)
```
So this shows where things have gone wrong, though it doesn't present an obvious solution. Clearly, `Yield` needs to be generalized since it needs to take arbitrary tuples (based on how many variables are in scope). Perhaps more subtly, it also shows that `x` is not in scope in the call to `add` (see that unbound `x` as the second argument to `b.Op`?). To allow your custom operators to use bound variables, their arguments need to have the `[<ProjectionParameter>]` attribute (and take functions from arbitrary variables as arguments), and you'll also need to set `MaintainsVariableSpace` to `true` if you want bound variables to be available to later operators. This will change the final translation to:
```
b.Op(let x = e in b.Yield(x), fun x -> x)
```
Building up from this, it seems that there's no way to avoid passing the set of bound values along to and from each operation (though I'd love to be proven wrong) - this will require you to add a `Run` method to strip those values back off at the end. Putting it all together, you'll get a builder which looks like this:
```
type ListBuilder() =
member x.Yield(vars) = Items [],vars
[<CustomOperation("add",MaintainsVariableSpace=true)>]
member x.Add((Items current,vars), [<ProjectionParameter>]f) =
Items (current @ [f vars]),vars
[<CustomOperation("addMany",MaintainsVariableSpace=true)>]
member x.AddMany((Items current, vars), [<ProjectionParameter>]f) =
Items (current @ f vars),vars
member x.Run(l,_) = l
``` | The tutorial at "F# for fun and profit" is first class in this regard.
<http://fsharpforfunandprofit.com/posts/computation-expressions-intro/> |
23,122,645 | I need your help,
Is there perhaps a more efficient method to code an SQL statement to connect to the database and retrieve numerical values? My way of logic is this. Use the SQL Count to tally, store the numeric value into a var (similar to excel labelled cells), and then use the vars and output the results to an HTML table
I am wondering whether there maybe a more efficient way/method of doing so, if not am I politically correct to about the method below? I'm guessing that connecting to the DB multiple times would be somewhat slower?
I am using the Active Data Object connecting to an MS Access database (mdb file) for my own perusal.
```
var a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17
var b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17
var c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17
var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13,e14,e15,e16,e17
var f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17
var g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17
var h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14,h15,h16,h17
var i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17
var j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a3 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAB' AND [DATE RECEIVED] BETWEEN #"+date1)+"# AND #"+date1_2+"#"
a4 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a5 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a7 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a8 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBE' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a9 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBM' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a10 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
``` | 2014/04/17 | [
"https://Stackoverflow.com/questions/23122645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474921/"
] | The best place to look is the [spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835). For example,
```
b {
let x = e
op x
}
```
gets translated to
```
T(let x = e in op x, [], fun v -> v, true)
=> T(op x, {x}, fun v -> let x = e in v, true)
=> [| op x, let x = e in b.Yield(x) |]{x}
=> b.Op(let x = e in in b.Yield(x), x)
```
So this shows where things have gone wrong, though it doesn't present an obvious solution. Clearly, `Yield` needs to be generalized since it needs to take arbitrary tuples (based on how many variables are in scope). Perhaps more subtly, it also shows that `x` is not in scope in the call to `add` (see that unbound `x` as the second argument to `b.Op`?). To allow your custom operators to use bound variables, their arguments need to have the `[<ProjectionParameter>]` attribute (and take functions from arbitrary variables as arguments), and you'll also need to set `MaintainsVariableSpace` to `true` if you want bound variables to be available to later operators. This will change the final translation to:
```
b.Op(let x = e in b.Yield(x), fun x -> x)
```
Building up from this, it seems that there's no way to avoid passing the set of bound values along to and from each operation (though I'd love to be proven wrong) - this will require you to add a `Run` method to strip those values back off at the end. Putting it all together, you'll get a builder which looks like this:
```
type ListBuilder() =
member x.Yield(vars) = Items [],vars
[<CustomOperation("add",MaintainsVariableSpace=true)>]
member x.Add((Items current,vars), [<ProjectionParameter>]f) =
Items (current @ [f vars]),vars
[<CustomOperation("addMany",MaintainsVariableSpace=true)>]
member x.AddMany((Items current, vars), [<ProjectionParameter>]f) =
Items (current @ f vars),vars
member x.Run(l,_) = l
``` | Following a similar struggle to Joel's (and not finding §6.3.10 of the spec that helpful) my issue with getting the For construct to generate a list came down to getting types to line up properly (no special attributes required). In particular I was slow to realise that For would build a list of lists, and therefore need flattening, despite the best efforts of the compiler to put me right. Examples that I found on the web were always wrappers around seq{}, using the yield keyword, repeated use of which invokes a call to Combine, which does the flattening. In case a concrete example helps, the following excerpt uses for to build a list of integers - my ultimate aim being to create lists of components for rendering in a GUI (with some additional laziness thrown in). Also [In depth talk on CE here](http://fpish.net/course/298) which elaborates on kvb's points above.
```
module scratch
type Dispatcher = unit -> unit
type viewElement = int
type lazyViews = Lazy<list<viewElement>>
type ViewElementsBuilder() =
member x.Return(views: lazyViews) : list<viewElement> = views.Value
member x.Yield(v: viewElement) : list<viewElement> = [v]
member x.ReturnFrom(viewElements: list<viewElement>) = viewElements
member x.Zero() = list<viewElement>.Empty
member x.Combine(listA:list<viewElement>, listB: list<viewElement>) = List.concat [listA; listB]
member x.Delay(f) = f()
member x.For(coll:seq<'a>, forBody: 'a -> list<viewElement>) : list<viewElement> =
// seq {for v in coll do yield! f v} |> List.ofSeq
Seq.map forBody coll |> Seq.collect id |> List.ofSeq
let ve = new ViewElementsBuilder()
let makeComponent(m: int, dispatch: Dispatcher) : viewElement = m
let makeComponents() : list<viewElement> = [77; 33]
let makeViewElements() : list<viewElement> =
let model = {| Scores = [33;23;22;43;] |> Seq.ofList; Trainer = "John" |}
let d:Dispatcher = fun() -> () // Does nothing here, but will be used to raise messages from UI
ve {
for score in model.Scores do
yield makeComponent (score, d)
yield makeComponent (score * 100 / 50 , d)
if model.Trainer = "John" then
return lazy
[ makeComponent (12, d)
makeComponent (13, d)
]
else
return lazy
[ makeComponent (14, d)
makeComponent (15, d)
]
yield makeComponent (33, d)
return! makeComponents()
}
``` |
23,122,645 | I need your help,
Is there perhaps a more efficient method to code an SQL statement to connect to the database and retrieve numerical values? My way of logic is this. Use the SQL Count to tally, store the numeric value into a var (similar to excel labelled cells), and then use the vars and output the results to an HTML table
I am wondering whether there maybe a more efficient way/method of doing so, if not am I politically correct to about the method below? I'm guessing that connecting to the DB multiple times would be somewhat slower?
I am using the Active Data Object connecting to an MS Access database (mdb file) for my own perusal.
```
var a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17
var b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17
var c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17
var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13,e14,e15,e16,e17
var f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17
var g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17
var h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14,h15,h16,h17
var i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17
var j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a3 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAB' AND [DATE RECEIVED] BETWEEN #"+date1)+"# AND #"+date1_2+"#"
a4 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFAD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a5 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBA' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a7 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBD' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a8 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBE' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a9 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
DB_connect()
SQL = "SELECT COUNT(*) FROM tbl_imts WHERE [REQUEST TYPE]='MINISTERIAL DOCKET' AND [OPI]='ASFBM' AND [DATE RECEIVED] BETWEEN #"+date1+"# AND #"+date1_2+"#"
a10 = Number(cn.Execute(SQL).Fields(0).Value)
cn.Close()
``` | 2014/04/17 | [
"https://Stackoverflow.com/questions/23122645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474921/"
] | The tutorial at "F# for fun and profit" is first class in this regard.
<http://fsharpforfunandprofit.com/posts/computation-expressions-intro/> | Following a similar struggle to Joel's (and not finding §6.3.10 of the spec that helpful) my issue with getting the For construct to generate a list came down to getting types to line up properly (no special attributes required). In particular I was slow to realise that For would build a list of lists, and therefore need flattening, despite the best efforts of the compiler to put me right. Examples that I found on the web were always wrappers around seq{}, using the yield keyword, repeated use of which invokes a call to Combine, which does the flattening. In case a concrete example helps, the following excerpt uses for to build a list of integers - my ultimate aim being to create lists of components for rendering in a GUI (with some additional laziness thrown in). Also [In depth talk on CE here](http://fpish.net/course/298) which elaborates on kvb's points above.
```
module scratch
type Dispatcher = unit -> unit
type viewElement = int
type lazyViews = Lazy<list<viewElement>>
type ViewElementsBuilder() =
member x.Return(views: lazyViews) : list<viewElement> = views.Value
member x.Yield(v: viewElement) : list<viewElement> = [v]
member x.ReturnFrom(viewElements: list<viewElement>) = viewElements
member x.Zero() = list<viewElement>.Empty
member x.Combine(listA:list<viewElement>, listB: list<viewElement>) = List.concat [listA; listB]
member x.Delay(f) = f()
member x.For(coll:seq<'a>, forBody: 'a -> list<viewElement>) : list<viewElement> =
// seq {for v in coll do yield! f v} |> List.ofSeq
Seq.map forBody coll |> Seq.collect id |> List.ofSeq
let ve = new ViewElementsBuilder()
let makeComponent(m: int, dispatch: Dispatcher) : viewElement = m
let makeComponents() : list<viewElement> = [77; 33]
let makeViewElements() : list<viewElement> =
let model = {| Scores = [33;23;22;43;] |> Seq.ofList; Trainer = "John" |}
let d:Dispatcher = fun() -> () // Does nothing here, but will be used to raise messages from UI
ve {
for score in model.Scores do
yield makeComponent (score, d)
yield makeComponent (score * 100 / 50 , d)
if model.Trainer = "John" then
return lazy
[ makeComponent (12, d)
makeComponent (13, d)
]
else
return lazy
[ makeComponent (14, d)
makeComponent (15, d)
]
yield makeComponent (33, d)
return! makeComponents()
}
``` |
33,194 | I have a Page layout like this
```
Parent Page
- Sub page 1
-- sub sub 1
-- sub sub 2
-- sub sub 4
- Sub page 2
-- sub sub 1
-- sub sub 2
-- sub sub 4
```
I want to query every single child page, regardless of how deep I go. This is my query but it only returns direct children(sub page 1 and 2)
```
query_posts('post_type=page&order=ASC&orderby=menu_order&depth=4&post_parent='.$post->ID);
```
How can I do this? | 2011/11/08 | [
"https://wordpress.stackexchange.com/questions/33194",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9026/"
] | I'm pretty sure you can use `get_pages` (<http://codex.wordpress.org/Function_Reference/get_pages>) function to solve this. It has `child_of` parameter which does exactly what you wanted.
The only problem is that it returns posts and not set `$wp_query`, so you can't use it as loop, but you can always call `setup_postdata` and then use template tags as in normal posts loop.
```
<?php
$mypages = get_pages( array( 'child_of' => <PARENT_PAGE_ID>) );
foreach( $mypages as $page ):
?>
<h2><a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo apply_filters('the_title', $page->post_title); ?></a></h2>
<div class="entry"><?php echo apply_filters( 'the_content', $page->post_content ); ?></div>
<?php endforeach; ?>
``` | try this
```
function wpse33151_getSubpages() {
global $post;
$parents = get_post_ancestors($post->post_id);
krsort($parents);
$parents = array_merge(array(), $parents);
if (is_home() || is_single()) {
$id = get_option('page_for_posts');
$parent = get_post_ancestors($id);
$id = $parent[0];
} elseif($parents) {
$id = $parents[0];
} else {
$id = $post->ID;
}
$children = wp_list_pages('title_li=&child_of=' . $id . '&echo=0');
$out = null;
if ($children) {
$out = '';
$out .= '' . get_the_title($id) . '';
$out .= '';
$out .= $children;
$out .= '
';
$out .= '';
}
return $out;
}
``` |
60,390,234 | I am very new to Laravel and working on a project. I have a user table,category table(category\_id,category\_name) and pets table(id,user\_id,category\_id,breed,description....).How can i make the user add post and make his id and cagtegory\_id that he had chosen from select option save in user\_id and category\_id in pets table ?? | 2020/02/25 | [
"https://Stackoverflow.com/questions/60390234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11399857/"
] | Your problem comes from your data :
* Your are trying to outputs 14 879 values from an input of shape (batch\_size, 100), it's impossible for your network to be able to learn something from your data.
* As said by @Nopileos, a batch size of 10 000 is way way too hudge, i don't think you have hundred of millions inputs so considere using a batch size more reasonable !
Add your inputs/labels shape and what its corresponding too if you want us to help you to give some intuitions ! | If you are running out of memory, decrease your chunk size. Lower it to 10, and see if that works. Larger chunk size means your computer has to hold more information in RAM at one time. |
376,431 | Let $\beta\omega$ be collection of all ultrafilters on $\omega$ (principal and non-principal). We endow $\beta\omega$ with an operation $+$ in the following way. For ${\bf a}, {\bf b}\in \beta\omega$, set $${\bf a}+{\bf b} = \big\{ N\subseteq \omega:\{x \in \omega:\{y\in\omega: x+y\in N\}\in {\bf b}\}\in {\bf a}\big\}.$$
Standard exercises show that ${\bf a}+{\bf b}\in \beta\omega$, and that the operation $+:\beta\omega \times \beta\omega \to \beta\omega$ is associative.
If we identify a member $n\in\omega$ with the principal ultrafilter containing the singleton $\{n\}$ as an element, the addition just introduced agrees with the addition given in $\omega$. In $\omega$, we have the following "completion property": given $a, b\in \omega$, there is $x\in \omega$ such that $a+x=b$ or $b+x=a$.
This motivates the following question: if ${\bf a},{\bf b} \in \beta\omega$, is there ${\bf x}\in\beta\omega$ with ${\bf a}+{\bf x} = {\bf b}$ or ${\bf b}+{\bf x} = {\bf a}$? | 2020/11/13 | [
"https://mathoverflow.net/questions/376431",
"https://mathoverflow.net",
"https://mathoverflow.net/users/8628/"
] | No. Kunen proved that there are many weak P-points in $\beta\omega-\omega$, which means they are nonprincipal ultrafilters that are not in the closure of any countable set of other nonprincipal ultrafilters. In particular, a weak P-point is never a sum of nonprincipal ultrafilters because $\mathbf a+\mathbf b$ is in the closure of the set $\{\mathbf b+n:n\in\omega\}$. | Write $(\alpha x)\ P(x)$ for the statement $\{x:P(x)\}\in\alpha$. Now suppose that the set $\{1,2,4,8,\dots\}\in\alpha$. If $\beta+\gamma=\alpha$, then $(\beta x)\ (\gamma y)\ x+y\in\{1,2,4,8,\dots\}$. In particular, if $\beta$ is non-principal, then there must exist $x\_1\ne x\_2$ such that $(\gamma y)\ x\_1+y\in\{1,2,4,8,\dots\}$ and $(\gamma y)\ x\_2+y\in\{1,2,4,8,\dots\}$. But the set of $y$ with that property is finite, so this can't happen unless $\gamma$ is principal.
To put it a different way, if $\alpha$ is a sum $\beta+\gamma$ of two non-principal ultrafilters and $A\in\alpha$, then many shifts of $A$ must belong to $\gamma$, so their finite intersections must belong to $\gamma$. It's easy to find infinite sets $A$ for which this doesn't happen, and it's also easy to make sure they belong to $\alpha$. |
58,375,636 | I have a list with two elements
element 1:
```
no:1,
vendor: a,
Description: Nice,
price :10
```
element 2:
```
no:1
vendor:a,
Description: Nice,
price:20
```
i have lot more fields in list elements so i cannot use new to sum the price
if everything is same except price i need to combine two elements into a single element by summing price.
o/p element 1:
```
no:1,
vendor:a,
Description:Nice,
price:30
```
Tried below one but not sure how to sum the price and return the entire fields with out using new
```cs
list.GroupBy(y => new { y.Description,y.vendor, y.no})
.Select(x => x.ToList().OrderBy(t => t.Price)).FirstOrDefault()
``` | 2019/10/14 | [
"https://Stackoverflow.com/questions/58375636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6398876/"
] | I couldn't get `@ApiModelProperty(dataType = "")` to work, but I found a more convenient way configuring a direct substitute in the Swagger configuration using `directModelSubstitute` method of the `Docket` instance in [this response](https://stackoverflow.com/a/29355873/469218).
```
@Configuration
@EnableSwagger2
class SwaggerConfig() {
@Bean
fun api(): Docket {
return Docket(DocumentationType.SWAGGER_2)
.directModelSubstitute(ObjectId::class.java, String::class.java)
}
}
```
Java equivalent:
```
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.directModelSubstitute(ObjectId.class, String.class);
}
``` | For OpenApi (Swagger 3.0) and SpringDoc the following global configuration could be used.
```
static {
SpringDocUtils.getConfig().replaceWithSchema(ObjectId.class, new StringSchema());
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):
```
public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
``` | ```
public static bool Contains(this string input, string findMe, StringComparison comparisonType)
{
return String.IsNullOrWhiteSpace(input) ? false : input.IndexOf(findMe, comparisonType) > -1;
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | ```
fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())
``` | Use **String.Equals** Method
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.Equals(description, StringComparison.OrdinalIgnoreCase));
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | You can use string.Compare
```
lst.Where(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0);
```
if you just want to check contains then use "Any"
```
lst.Any(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0)
``` | Use **String.Equals** Method
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.Equals(description, StringComparison.OrdinalIgnoreCase));
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | ```
fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())
``` | Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):
```
public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | >
> [StringComparison.InvariantCultureIgnoreCase](https://learn.microsoft.com/en-us/dotnet/api/system.stringcomparer.invariantcultureignorecase?view=netframework-4.8) just do the job for me:
>
>
>
```
.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));
``` | Use **String.Equals** Method
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.Equals(description, StringComparison.OrdinalIgnoreCase));
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | If the LINQ query is executed in database context, a call to `Contains()` is mapped to the `LIKE` operator:
`.Where(a => a.Field.Contains("hello"))`
becomes `Field LIKE '%hello%'`. The `LIKE` operator is case insensitive by default, but that can be changed by [changing the collation of the column](https://clicdatacoder.wordpress.com/2012/07/10/using-case-sensitive-comparisons-in-linq-to-entity/comment-page-1/).
If the LINQ query is executed in .NET context, you can use [IndexOf()](http://msdn.microsoft.com/en-us/library/ms224425), but that method is not supported in LINQ to SQL.
LINQ to SQL [does not support methods](http://msdn.microsoft.com/en-us/library/bb882672.aspx) that take a CultureInfo as parameter, probably because it can not guarantee that the SQL server handles cultures the same as .NET. This is not completely true, because it *does* support `StartsWith(string, StringComparison)`.
However, it does not seem to support a method which evaluates to `LIKE` in LINQ to SQL, and to a case insensitive comparison in .NET, making it impossible to do case insensitive Contains() in a consistent way. | >
> [StringComparison.InvariantCultureIgnoreCase](https://learn.microsoft.com/en-us/dotnet/api/system.stringcomparer.invariantcultureignorecase?view=netframework-4.8) just do the job for me:
>
>
>
```
.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | Assuming we're working with strings here, here's another "elegant" solution using `IndexOf()`.
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.IndexOf(description, StringComparison.OrdinalIgnoreCase) != -1);
}
``` | Honestly, this doesn't need to be difficult. It may seem that on the onset, but it's not. Here's a simple linq query in C# that does exactly as requested.
In my example, I'm working against a list of persons that have one property called FirstName.
```
var results = ClientsRepository().Where(c => c.FirstName.ToLower().Contains(searchText.ToLower())).ToList();
```
This will search the database on lower case search but return full case results. |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):
```
public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
``` | You can use string.Compare
```
lst.Where(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0);
```
if you just want to check contains then use "Any"
```
lst.Any(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0)
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | ```
fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())
``` | ```
public static bool Contains(this string input, string findMe, StringComparison comparisonType)
{
return String.IsNullOrWhiteSpace(input) ? false : input.IndexOf(findMe, comparisonType) > -1;
}
``` |
3,360,772 | This code is case sensitive, how to make it case insensitive?
```
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
``` | 2010/07/29 | [
"https://Stackoverflow.com/questions/3360772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351564/"
] | IndexOf works best in this case
```
return this
.ObjectContext
.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION.IndexOf(description, StringComparison.OrdinalIgnoreCase)>=0);
``` | You can use string.Compare
```
lst.Where(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0);
```
if you just want to check contains then use "Any"
```
lst.Any(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0)
``` |
15,555,800 | is there anything wrong with this coffee script? Its working fine on this fiddle
<http://jsfiddle.net/Dtwigs/ThnKc/2/>
but when i try to convert it to coffee script it does not want to seem to work
```
$(document).on "change", "#print_size_options_LargeFormatBlackWhite", (event) ->
selected = undefined
index = undefined
selected = $(this).val()
index = $("select").index(this)
if selected is "customSize"
$($(".custom_size")[index]).fadeIn()
else
$($(".custom_size")[index]).fadeOut()
``` | 2013/03/21 | [
"https://Stackoverflow.com/questions/15555800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502223/"
] | There are a few issues with your fiddle.
1. You're using the same ID for multiple elements - you should make it a class.
2. You're adding the change event to the document, it's probably better to add it to a more precise selector, namely the selects.
3. If you're going to write it in JS in the first place, there's not much gain from using a CoffeeScript converter.
I've fixed some issues with the fiddle and updated it [here](http://jsfiddle.net/phenomnomnominal/ThnKc/5/).
The new CoffeeScript looks like this:
```
$(".print_size_options_LargeFormatBlackWhite").change ->
selected = $(this).val()
index = $("select").index this
func = if selected is ".custom_size" then 'fadeIn' else 'fadeOut'
$($('.custom_size')[index])[func]()
``` | The only difference I can see is that you write (event) here when on fiddle is (evt).
Are you considering using <http://js2coffee.org/> for the conversion? |
41,507 | >
> **Possible Duplicate:**
>
> [Is it possible to go back in time?](https://physics.stackexchange.com/questions/2166/is-it-possible-to-go-back-in-time)
>
> [Is time travel possible?](https://physics.stackexchange.com/questions/7823/is-time-travel-possible)
>
>
>
According to Stephen Hawking, time travel to the future is not only possible but proven, however time travel to the past is impossible, however this doesn't make sense. It seems to me that an extension to Newtons laws of motion could be that there is something opposite of motion which exists in the universe. The concept is that the universe (or a universe) is ending, and sort of crunches itself up, this would result in negative motion, which in theory would result in backwards time as well. He believes it's not possible because of the crazy scientist theory, where a scientist uses his vortex to kill himself in the past, so who shot him? Well the answer to this is very simple, the scientist would require a dieing universe to perform the time travel, and he himself would have to be in it for him to travel through time, therefore, he wouldn't survive, as he would perish inside of the dieing universe, and never get the chance to shoot himself. Also, he had a party, where future scientists were invited. He wrote up a invitation which would be preserved through time for his future guests. However, his experiment isn't all that swift, because, a number of things can go wrong with his invitation over time, which would mean his "party people" would never arrive, because they never received the invitation. It's kind of like those that say the infinite universe is impossible, because someone in this infinite universe would have blown it up, it just simply does not preclude the existence of the infinite universe, but that's another topic. | 2012/10/23 | [
"https://physics.stackexchange.com/questions/41507",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/14310/"
] | >
> **Does Stephen Hawking not believe in Negative movement?**
>
>
>
Yes,
...
Stephen Hawking does not believe that it is possible to travel into the past.
>
> We are all travelling forward in time anyway. We can fast forward by going off in a rocket at high speed and return to find everyone on Earth much older or dead. Einstein's general theory of relativity seems to offer the possibility that we could warp space-time so much that we could travel back in time. However, it is likely that warping would trigger a bolt of radiation that would destroy the spaceship and maybe the space-time itself. I have experimental evidence that time travel is not possible. I gave a party for time-travelers, but I didn't send out the invitations until after the party. I sat there a long time, but no one came.
>
>
>
(from Hawking on June 16 2012)


If I ever get a time machine, the first time and place I'll go to will be to Hawking's party. Before setting off I'll look up yestermorrows horse race results so Stephen and I can give all the bookmakers money to his favourite charity. It willan have on-been a hoot!
I must be hiding behind the balloons. | We know time travel to the future is possible because we all do it. More specifically, we know time travel to the future at a rate faster than one second per second is possible because particles in the Large Hadron Collider do it.
Time travel to the past is a different matter because it implies we could create [closed timelike curves](http://en.wikipedia.org/wiki/Closed_timelike_curves). If CTCs existed they would allow causality to be violated and invalidate just about all the assumptions that modern physics is based on. Since modern physics works very well we conclude that CTCs don't exist.
The fact CTCs don't exist doesn't mean they're impossible, though it does imply that at best they're very unlikely to occur. No-one has managed to prove that CTCs are impossible, but then no-one has managed to prove they're possible. At the moment no-one knows for sure whether CTCs can exist, but bear in mind my comments above i.e. we **can** be sure there are they aren't common. |
21,207 | I have a Capital One credit card that I got in college with a limit of $1,300 and a $39 annual fee. They've never raised the limit for me over the years even though my credit score is north of 700. I have a balance of $0 and I haven't used the card in years.
I wanted to close that card and get a different card, something that gets miles/points and has a decent limit. Most of my other cards have limits that are above $10,000.
I did a search here and most people said to just let the unused cards continue on because of the debt-to-limit ratio portion of the credit score, but the posts didn't reference yearly fees and it didn't take into account that a new card will have a better ratio with a higher limit.
With the yearly fee in mind I'm inclined to cancel, but are there any measurable negative effects to asking for a credit card closure?
Thanks | 2013/03/19 | [
"https://money.stackexchange.com/questions/21207",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/9506/"
] | Sorry to hear about your difficult circumstances.
**Secured Credit Card**
You may want to suggest a secured credit card. These are credit cards that are backed by a deposit that she would place with the credit issuer. The card issuer provides a line of credit backed by the deposit, with a credit limit not greater than the deposit. In this way, the card issuer is not putting any of their own money at risk. These cards are often used by students or high-risk borrowers to establish credit, and function like a normal credit card. This may be a good option for her to establish a history of handling credit responsibly. Given all of the activity you described, it's very likely the process of rehabilitating her credit will take a number of years.
I would strongly recommend that you not assist her in placing the deposit for a secured credit card. If she can't put aside enough money for a deposit (often $500 or less), it's unlikely she'll be able to set aside the money to pay her card statements each month.
Best of luck - I hope things work out well. | I've read multiple times that the way to rebuild the credit score is to get a credit card and then have some minor charges on it every month and have them paid in full every month. Old negative events age and this disciplined activity rebuild the score to some not to horrible levels.
Now it's true that it's hard to get reasonably good credit cards when your credit score is poor. Yet it's not necessary to have a good credit card for this case - such things as large credit limit are not needed. All that's needed is a long grace period so that there's no interest between the moment a charge is done and a moment the bill is paid in full at the end of the month. Yes, the card may have rather high interest and rather low credit limit, but it doesn't really matter.
I've read once on MSN Money that people are offered credit even while they're in the middle of bankruptcy, so it's not impossible to get a credit card in the described situation.
Goes without saying that a lot of discipline will be needed to have all this implemented. |
21,207 | I have a Capital One credit card that I got in college with a limit of $1,300 and a $39 annual fee. They've never raised the limit for me over the years even though my credit score is north of 700. I have a balance of $0 and I haven't used the card in years.
I wanted to close that card and get a different card, something that gets miles/points and has a decent limit. Most of my other cards have limits that are above $10,000.
I did a search here and most people said to just let the unused cards continue on because of the debt-to-limit ratio portion of the credit score, but the posts didn't reference yearly fees and it didn't take into account that a new card will have a better ratio with a higher limit.
With the yearly fee in mind I'm inclined to cancel, but are there any measurable negative effects to asking for a credit card closure?
Thanks | 2013/03/19 | [
"https://money.stackexchange.com/questions/21207",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/9506/"
] | Sorry to hear about your difficult circumstances.
**Secured Credit Card**
You may want to suggest a secured credit card. These are credit cards that are backed by a deposit that she would place with the credit issuer. The card issuer provides a line of credit backed by the deposit, with a credit limit not greater than the deposit. In this way, the card issuer is not putting any of their own money at risk. These cards are often used by students or high-risk borrowers to establish credit, and function like a normal credit card. This may be a good option for her to establish a history of handling credit responsibly. Given all of the activity you described, it's very likely the process of rehabilitating her credit will take a number of years.
I would strongly recommend that you not assist her in placing the deposit for a secured credit card. If she can't put aside enough money for a deposit (often $500 or less), it's unlikely she'll be able to set aside the money to pay her card statements each month.
Best of luck - I hope things work out well. | I was in the same chicken and egg situation regarding credit cards. I did two things:
1. I got a credit card from [Capital One](https://www.capitalone.com/) that had a $60 annual fee in exchange for not caring that my credit history was bad. I used that card to pay for everything to build my credit history back up.
2. I got a cell phone by putting a $200 security deposit down for a year and paid the bills automatically using the credit card.
Now that I have recent good credit history, Capital One has offered to raise my limit. I assume that it is because my credit score has improved and I can probably now switch to a credit card that doesn't have an annual fee. |
21,207 | I have a Capital One credit card that I got in college with a limit of $1,300 and a $39 annual fee. They've never raised the limit for me over the years even though my credit score is north of 700. I have a balance of $0 and I haven't used the card in years.
I wanted to close that card and get a different card, something that gets miles/points and has a decent limit. Most of my other cards have limits that are above $10,000.
I did a search here and most people said to just let the unused cards continue on because of the debt-to-limit ratio portion of the credit score, but the posts didn't reference yearly fees and it didn't take into account that a new card will have a better ratio with a higher limit.
With the yearly fee in mind I'm inclined to cancel, but are there any measurable negative effects to asking for a credit card closure?
Thanks | 2013/03/19 | [
"https://money.stackexchange.com/questions/21207",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/9506/"
] | Sorry to hear about your difficult circumstances.
**Secured Credit Card**
You may want to suggest a secured credit card. These are credit cards that are backed by a deposit that she would place with the credit issuer. The card issuer provides a line of credit backed by the deposit, with a credit limit not greater than the deposit. In this way, the card issuer is not putting any of their own money at risk. These cards are often used by students or high-risk borrowers to establish credit, and function like a normal credit card. This may be a good option for her to establish a history of handling credit responsibly. Given all of the activity you described, it's very likely the process of rehabilitating her credit will take a number of years.
I would strongly recommend that you not assist her in placing the deposit for a secured credit card. If she can't put aside enough money for a deposit (often $500 or less), it's unlikely she'll be able to set aside the money to pay her card statements each month.
Best of luck - I hope things work out well. | I want to be a bit contrarian here. It may be true that to rebuild credit it *helps* to have credit, but it's not the most important thing. If your description of your wife's history is correct, the most important thing is to fix her tendency to 'spend out of control', especially on get-rich-quick schemes. She may well be on the way to fixing that, but in those circumstances every source of credit is a temptation to spend. Why put that temptation in her way? Whatever tiny postive effect having a credit card has on her credit score will be wiped out if in six months time she suddenly maxes out that card and can't pay it off.
I don't want to play credit counsellor, and you should get some professional advice, but her credit score will improve by itself if she takes on no new debt, pays off what she has, and cuts up any credit cards she owns. |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | findbars
--------
The lme4 package provides `findbars`:
```
library(lme4)
fo <- Y~X1+(1|fac1)+(1|fac2)
findbars(fo)
## [[1]]
## 1 | fac1
##
## [[2]]
## 1 | fac2
```
If character strings are needed we can use the following. `deparse1` will handle certain uncommon cases that `deparse` fails at but `deparse` will mostly work as an alternative if it is necessary that this work in versions of R earlier than R 4.0.0.
```
sapply(findbars(fo), deparse1)
## [1] "1 | fac1" "1 | fac2"
```
If the desired result is the RHS of the formula but without the fixed effects terms then we can reconstitute the above by adding back the parentheses and using `reformulate`. Omit [[2]] if a formula object is desired. Discussion above regarding `deparse1` applies here too.
```
reformulate(sprintf("(%s)", sapply(findbars(fo), deparse1)))[[2]]
## (1 | fac1) + (1 | fac2)
```
terms/labels
------------
Another way to get character result is to use `labels` which will extract them from `terms` . Use `reformulate`, as above, if a formula is desired. This does not use any packages.
```
X <- grep("|", labels(terms(fo)), fixed = TRUE, value = TRUE)
X
## [1] "1 | fac1" "1 | fac2"
```
As above, the formula and right hand side of it can be generated from `X` like this:
```
reformulate(sprintf("(%s)", X))
reformulate(sprintf("(%s)", X))[[2]]
```
getTerms
--------
Another approach is to use `getTerms` from [Terms of a sum in a R expression](https://stackoverflow.com/questions/53300717/terms-of-a-sum-in-a-r-expression/53300817#53300817) This short function recursively walks the formula to extract the terms. It does not use any packages.
```
XX <- grep("|", sapply(getTerms(fo[[3]]), deparse1), fixed = TRUE, value = TRUE)
XX
## [1] "(1 | fac1)" "(1 | fac2)"
```
The formula and right hand side of it can be generated like this:
```
reformulate(XX)
reformulate(XX)[[2]]
``` | No regex required , however, it's still string manipulation.
```
# stringsplit the output of your formula()
# remove the first entry
# remove spaces with gsub()
# paste it back together
inp <- "X1 + (1| fac1) + (1| fac2)"
paste(gsub(" ", "", unlist(strsplit(inp, "+", fixed = T))[-1], fixed = T),
collapse = " + ")
# [1] "(1|fac1) + (1|fac2)"
``` |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | No regex required , however, it's still string manipulation.
```
# stringsplit the output of your formula()
# remove the first entry
# remove spaces with gsub()
# paste it back together
inp <- "X1 + (1| fac1) + (1| fac2)"
paste(gsub(" ", "", unlist(strsplit(inp, "+", fixed = T))[-1], fixed = T),
collapse = " + ")
# [1] "(1|fac1) + (1|fac2)"
``` | After seeing G Grthendieck's answer I realise I'm probably reinventing the wheel, but here's a way to get the random effects parts out of a model without using regex. It uses recursion to examine each call in the formula's AST and keeps only those in parentheses, which it then rebuilds into an expression. I may be wrong, but this feels safer than switching between character strings and language objects. It could be modified to pull out only `|` calls.
```r
get_random_effects <- function(mod)
{
rip_formula <- function(form)
{
if(rlang::is_formula(form)) form <- as.list(form)[-c(1:2)][[1]]
if(is.call(form)) {
call_list <- as.list(form)
if(as.character(call_list[[1]]) == "+")
return(unlist(lapply(call_list[-1], rip_formula)))
if(as.character(call_list[[1]]) == "(")
return(form)
}
}
re_list <- rip_formula(formula(mod))
while(length(re_list) > 2)
re_list <- c(as.call(list(bquote(`+`), re_list[1:2])), re_list[-(1:2)])
as.call(list(bquote(`+`), re_list[[1]], re_list[[2]]))
}
```
So it's now as easy as:
```
get_random_effects(mymodel)
#> (1 | fac1) + (1 | fac2)
``` |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | No regex required , however, it's still string manipulation.
```
# stringsplit the output of your formula()
# remove the first entry
# remove spaces with gsub()
# paste it back together
inp <- "X1 + (1| fac1) + (1| fac2)"
paste(gsub(" ", "", unlist(strsplit(inp, "+", fixed = T))[-1], fixed = T),
collapse = " + ")
# [1] "(1|fac1) + (1|fac2)"
``` | You can use the [insight-package](https://easystats.github.io/insight/) to access various model information, like formula, predictors, data etc. *insight* provides type-safe "generics" that work for many different models. In this case, you could use `find_formula()` or `find_random()`:
```r
library(insight)
library(lme4)
data(sleepstudy)
sleepstudy$mygrp <- sample(1:5, size = 180, replace = TRUE)
sleepstudy$mysubgrp <- NA
for (i in 1:5) {
filter_group <- sleepstudy$mygrp == i
sleepstudy$mysubgrp[filter_group] <-
sample(1:30, size = sum(filter_group), replace = TRUE)
}
m <- lmer(
Reaction ~ Days + (1 | mygrp / mysubgrp) + (1 | Subject),
data = sleepstudy
)
#> boundary (singular) fit: see ?isSingular
find_formula(m)
#> $conditional
#> Reaction ~ Days
#>
#> $random
#> $random[[1]]
#> ~1 | mysubgrp:mygrp
#>
#> $random[[2]]
#> ~1 | mygrp
#>
#> $random[[3]]
#> ~1 | Subject
find_random(m)
#> $random
#> [1] "mysubgrp:mygrp" "mygrp" "Subject"
#>
find_random(m, split_nested = TRUE)
#> $random
#> [1] "mysubgrp" "mygrp" "Subject"
find_random(m, split_nested = TRUE, flatten = TRUE)
#> [1] "mysubgrp" "mygrp" "Subject"
```
`find_formula()` and `find_random()` also work for models with zero-inflation part that have random effects, e.g. for models from the *glmmTMB* or *brms* packages. The "counterpart" to find possible random slopes would be [`find_random_slopes()`](https://easystats.github.io/insight/reference/find_random_slopes.html). |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | findbars
--------
The lme4 package provides `findbars`:
```
library(lme4)
fo <- Y~X1+(1|fac1)+(1|fac2)
findbars(fo)
## [[1]]
## 1 | fac1
##
## [[2]]
## 1 | fac2
```
If character strings are needed we can use the following. `deparse1` will handle certain uncommon cases that `deparse` fails at but `deparse` will mostly work as an alternative if it is necessary that this work in versions of R earlier than R 4.0.0.
```
sapply(findbars(fo), deparse1)
## [1] "1 | fac1" "1 | fac2"
```
If the desired result is the RHS of the formula but without the fixed effects terms then we can reconstitute the above by adding back the parentheses and using `reformulate`. Omit [[2]] if a formula object is desired. Discussion above regarding `deparse1` applies here too.
```
reformulate(sprintf("(%s)", sapply(findbars(fo), deparse1)))[[2]]
## (1 | fac1) + (1 | fac2)
```
terms/labels
------------
Another way to get character result is to use `labels` which will extract them from `terms` . Use `reformulate`, as above, if a formula is desired. This does not use any packages.
```
X <- grep("|", labels(terms(fo)), fixed = TRUE, value = TRUE)
X
## [1] "1 | fac1" "1 | fac2"
```
As above, the formula and right hand side of it can be generated from `X` like this:
```
reformulate(sprintf("(%s)", X))
reformulate(sprintf("(%s)", X))[[2]]
```
getTerms
--------
Another approach is to use `getTerms` from [Terms of a sum in a R expression](https://stackoverflow.com/questions/53300717/terms-of-a-sum-in-a-r-expression/53300817#53300817) This short function recursively walks the formula to extract the terms. It does not use any packages.
```
XX <- grep("|", sapply(getTerms(fo[[3]]), deparse1), fixed = TRUE, value = TRUE)
XX
## [1] "(1 | fac1)" "(1 | fac2)"
```
The formula and right hand side of it can be generated like this:
```
reformulate(XX)
reformulate(XX)[[2]]
``` | A simple solution that may not generalise:
```
# This model may not make much sense, just for reproducibility
mymodel <- lmer(Petal.Length~Sepal.Width+(1|Species) + (1|Petal.Width),iris)
stringr::str_extract_all(formula(mymodel),"\\(.*\\)")[3]
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
```
To "automatically" drop all empty elements:
```
purrr::compact(stringr::str_extract_all(formula(mymodel),"\\(.*\\)"))
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
``` |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | A simple solution that may not generalise:
```
# This model may not make much sense, just for reproducibility
mymodel <- lmer(Petal.Length~Sepal.Width+(1|Species) + (1|Petal.Width),iris)
stringr::str_extract_all(formula(mymodel),"\\(.*\\)")[3]
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
```
To "automatically" drop all empty elements:
```
purrr::compact(stringr::str_extract_all(formula(mymodel),"\\(.*\\)"))
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
``` | After seeing G Grthendieck's answer I realise I'm probably reinventing the wheel, but here's a way to get the random effects parts out of a model without using regex. It uses recursion to examine each call in the formula's AST and keeps only those in parentheses, which it then rebuilds into an expression. I may be wrong, but this feels safer than switching between character strings and language objects. It could be modified to pull out only `|` calls.
```r
get_random_effects <- function(mod)
{
rip_formula <- function(form)
{
if(rlang::is_formula(form)) form <- as.list(form)[-c(1:2)][[1]]
if(is.call(form)) {
call_list <- as.list(form)
if(as.character(call_list[[1]]) == "+")
return(unlist(lapply(call_list[-1], rip_formula)))
if(as.character(call_list[[1]]) == "(")
return(form)
}
}
re_list <- rip_formula(formula(mod))
while(length(re_list) > 2)
re_list <- c(as.call(list(bquote(`+`), re_list[1:2])), re_list[-(1:2)])
as.call(list(bquote(`+`), re_list[[1]], re_list[[2]]))
}
```
So it's now as easy as:
```
get_random_effects(mymodel)
#> (1 | fac1) + (1 | fac2)
``` |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | A simple solution that may not generalise:
```
# This model may not make much sense, just for reproducibility
mymodel <- lmer(Petal.Length~Sepal.Width+(1|Species) + (1|Petal.Width),iris)
stringr::str_extract_all(formula(mymodel),"\\(.*\\)")[3]
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
```
To "automatically" drop all empty elements:
```
purrr::compact(stringr::str_extract_all(formula(mymodel),"\\(.*\\)"))
[[1]]
[1] "(1 | Species) + (1 | Petal.Width)"
``` | You can use the [insight-package](https://easystats.github.io/insight/) to access various model information, like formula, predictors, data etc. *insight* provides type-safe "generics" that work for many different models. In this case, you could use `find_formula()` or `find_random()`:
```r
library(insight)
library(lme4)
data(sleepstudy)
sleepstudy$mygrp <- sample(1:5, size = 180, replace = TRUE)
sleepstudy$mysubgrp <- NA
for (i in 1:5) {
filter_group <- sleepstudy$mygrp == i
sleepstudy$mysubgrp[filter_group] <-
sample(1:30, size = sum(filter_group), replace = TRUE)
}
m <- lmer(
Reaction ~ Days + (1 | mygrp / mysubgrp) + (1 | Subject),
data = sleepstudy
)
#> boundary (singular) fit: see ?isSingular
find_formula(m)
#> $conditional
#> Reaction ~ Days
#>
#> $random
#> $random[[1]]
#> ~1 | mysubgrp:mygrp
#>
#> $random[[2]]
#> ~1 | mygrp
#>
#> $random[[3]]
#> ~1 | Subject
find_random(m)
#> $random
#> [1] "mysubgrp:mygrp" "mygrp" "Subject"
#>
find_random(m, split_nested = TRUE)
#> $random
#> [1] "mysubgrp" "mygrp" "Subject"
find_random(m, split_nested = TRUE, flatten = TRUE)
#> [1] "mysubgrp" "mygrp" "Subject"
```
`find_formula()` and `find_random()` also work for models with zero-inflation part that have random effects, e.g. for models from the *glmmTMB* or *brms* packages. The "counterpart" to find possible random slopes would be [`find_random_slopes()`](https://easystats.github.io/insight/reference/find_random_slopes.html). |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | findbars
--------
The lme4 package provides `findbars`:
```
library(lme4)
fo <- Y~X1+(1|fac1)+(1|fac2)
findbars(fo)
## [[1]]
## 1 | fac1
##
## [[2]]
## 1 | fac2
```
If character strings are needed we can use the following. `deparse1` will handle certain uncommon cases that `deparse` fails at but `deparse` will mostly work as an alternative if it is necessary that this work in versions of R earlier than R 4.0.0.
```
sapply(findbars(fo), deparse1)
## [1] "1 | fac1" "1 | fac2"
```
If the desired result is the RHS of the formula but without the fixed effects terms then we can reconstitute the above by adding back the parentheses and using `reformulate`. Omit [[2]] if a formula object is desired. Discussion above regarding `deparse1` applies here too.
```
reformulate(sprintf("(%s)", sapply(findbars(fo), deparse1)))[[2]]
## (1 | fac1) + (1 | fac2)
```
terms/labels
------------
Another way to get character result is to use `labels` which will extract them from `terms` . Use `reformulate`, as above, if a formula is desired. This does not use any packages.
```
X <- grep("|", labels(terms(fo)), fixed = TRUE, value = TRUE)
X
## [1] "1 | fac1" "1 | fac2"
```
As above, the formula and right hand side of it can be generated from `X` like this:
```
reformulate(sprintf("(%s)", X))
reformulate(sprintf("(%s)", X))[[2]]
```
getTerms
--------
Another approach is to use `getTerms` from [Terms of a sum in a R expression](https://stackoverflow.com/questions/53300717/terms-of-a-sum-in-a-r-expression/53300817#53300817) This short function recursively walks the formula to extract the terms. It does not use any packages.
```
XX <- grep("|", sapply(getTerms(fo[[3]]), deparse1), fixed = TRUE, value = TRUE)
XX
## [1] "(1 | fac1)" "(1 | fac2)"
```
The formula and right hand side of it can be generated like this:
```
reformulate(XX)
reformulate(XX)[[2]]
``` | After seeing G Grthendieck's answer I realise I'm probably reinventing the wheel, but here's a way to get the random effects parts out of a model without using regex. It uses recursion to examine each call in the formula's AST and keeps only those in parentheses, which it then rebuilds into an expression. I may be wrong, but this feels safer than switching between character strings and language objects. It could be modified to pull out only `|` calls.
```r
get_random_effects <- function(mod)
{
rip_formula <- function(form)
{
if(rlang::is_formula(form)) form <- as.list(form)[-c(1:2)][[1]]
if(is.call(form)) {
call_list <- as.list(form)
if(as.character(call_list[[1]]) == "+")
return(unlist(lapply(call_list[-1], rip_formula)))
if(as.character(call_list[[1]]) == "(")
return(form)
}
}
re_list <- rip_formula(formula(mod))
while(length(re_list) > 2)
re_list <- c(as.call(list(bquote(`+`), re_list[1:2])), re_list[-(1:2)])
as.call(list(bquote(`+`), re_list[[1]], re_list[[2]]))
}
```
So it's now as easy as:
```
get_random_effects(mymodel)
#> (1 | fac1) + (1 | fac2)
``` |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | findbars
--------
The lme4 package provides `findbars`:
```
library(lme4)
fo <- Y~X1+(1|fac1)+(1|fac2)
findbars(fo)
## [[1]]
## 1 | fac1
##
## [[2]]
## 1 | fac2
```
If character strings are needed we can use the following. `deparse1` will handle certain uncommon cases that `deparse` fails at but `deparse` will mostly work as an alternative if it is necessary that this work in versions of R earlier than R 4.0.0.
```
sapply(findbars(fo), deparse1)
## [1] "1 | fac1" "1 | fac2"
```
If the desired result is the RHS of the formula but without the fixed effects terms then we can reconstitute the above by adding back the parentheses and using `reformulate`. Omit [[2]] if a formula object is desired. Discussion above regarding `deparse1` applies here too.
```
reformulate(sprintf("(%s)", sapply(findbars(fo), deparse1)))[[2]]
## (1 | fac1) + (1 | fac2)
```
terms/labels
------------
Another way to get character result is to use `labels` which will extract them from `terms` . Use `reformulate`, as above, if a formula is desired. This does not use any packages.
```
X <- grep("|", labels(terms(fo)), fixed = TRUE, value = TRUE)
X
## [1] "1 | fac1" "1 | fac2"
```
As above, the formula and right hand side of it can be generated from `X` like this:
```
reformulate(sprintf("(%s)", X))
reformulate(sprintf("(%s)", X))[[2]]
```
getTerms
--------
Another approach is to use `getTerms` from [Terms of a sum in a R expression](https://stackoverflow.com/questions/53300717/terms-of-a-sum-in-a-r-expression/53300817#53300817) This short function recursively walks the formula to extract the terms. It does not use any packages.
```
XX <- grep("|", sapply(getTerms(fo[[3]]), deparse1), fixed = TRUE, value = TRUE)
XX
## [1] "(1 | fac1)" "(1 | fac2)"
```
The formula and right hand side of it can be generated like this:
```
reformulate(XX)
reformulate(XX)[[2]]
``` | You can use the [insight-package](https://easystats.github.io/insight/) to access various model information, like formula, predictors, data etc. *insight* provides type-safe "generics" that work for many different models. In this case, you could use `find_formula()` or `find_random()`:
```r
library(insight)
library(lme4)
data(sleepstudy)
sleepstudy$mygrp <- sample(1:5, size = 180, replace = TRUE)
sleepstudy$mysubgrp <- NA
for (i in 1:5) {
filter_group <- sleepstudy$mygrp == i
sleepstudy$mysubgrp[filter_group] <-
sample(1:30, size = sum(filter_group), replace = TRUE)
}
m <- lmer(
Reaction ~ Days + (1 | mygrp / mysubgrp) + (1 | Subject),
data = sleepstudy
)
#> boundary (singular) fit: see ?isSingular
find_formula(m)
#> $conditional
#> Reaction ~ Days
#>
#> $random
#> $random[[1]]
#> ~1 | mysubgrp:mygrp
#>
#> $random[[2]]
#> ~1 | mygrp
#>
#> $random[[3]]
#> ~1 | Subject
find_random(m)
#> $random
#> [1] "mysubgrp:mygrp" "mygrp" "Subject"
#>
find_random(m, split_nested = TRUE)
#> $random
#> [1] "mysubgrp" "mygrp" "Subject"
find_random(m, split_nested = TRUE, flatten = TRUE)
#> [1] "mysubgrp" "mygrp" "Subject"
```
`find_formula()` and `find_random()` also work for models with zero-inflation part that have random effects, e.g. for models from the *glmmTMB* or *brms* packages. The "counterpart" to find possible random slopes would be [`find_random_slopes()`](https://easystats.github.io/insight/reference/find_random_slopes.html). |
62,966,802 | I'm trying to check how many slashes the window URL contains.
```
//var url = "www.myurl.com/segment1/segment2segment3";
var url = windowURL.indexOf.href;
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
```
This gives errors of saying windowURL is not defined. Any ideas?
Thanks!
Edit:
I'm trying this now, which retrieves the URL but gives the wrong number of slashes, given that **I thought the code below omitted the https:// slashes.** Maybe I'm wrong? I want it to omit those...
```
var url = window.location.href;
alert(url);
var segment = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2);
alert(segment);
``` | 2020/07/18 | [
"https://Stackoverflow.com/questions/62966802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4908082/"
] | After seeing G Grthendieck's answer I realise I'm probably reinventing the wheel, but here's a way to get the random effects parts out of a model without using regex. It uses recursion to examine each call in the formula's AST and keeps only those in parentheses, which it then rebuilds into an expression. I may be wrong, but this feels safer than switching between character strings and language objects. It could be modified to pull out only `|` calls.
```r
get_random_effects <- function(mod)
{
rip_formula <- function(form)
{
if(rlang::is_formula(form)) form <- as.list(form)[-c(1:2)][[1]]
if(is.call(form)) {
call_list <- as.list(form)
if(as.character(call_list[[1]]) == "+")
return(unlist(lapply(call_list[-1], rip_formula)))
if(as.character(call_list[[1]]) == "(")
return(form)
}
}
re_list <- rip_formula(formula(mod))
while(length(re_list) > 2)
re_list <- c(as.call(list(bquote(`+`), re_list[1:2])), re_list[-(1:2)])
as.call(list(bquote(`+`), re_list[[1]], re_list[[2]]))
}
```
So it's now as easy as:
```
get_random_effects(mymodel)
#> (1 | fac1) + (1 | fac2)
``` | You can use the [insight-package](https://easystats.github.io/insight/) to access various model information, like formula, predictors, data etc. *insight* provides type-safe "generics" that work for many different models. In this case, you could use `find_formula()` or `find_random()`:
```r
library(insight)
library(lme4)
data(sleepstudy)
sleepstudy$mygrp <- sample(1:5, size = 180, replace = TRUE)
sleepstudy$mysubgrp <- NA
for (i in 1:5) {
filter_group <- sleepstudy$mygrp == i
sleepstudy$mysubgrp[filter_group] <-
sample(1:30, size = sum(filter_group), replace = TRUE)
}
m <- lmer(
Reaction ~ Days + (1 | mygrp / mysubgrp) + (1 | Subject),
data = sleepstudy
)
#> boundary (singular) fit: see ?isSingular
find_formula(m)
#> $conditional
#> Reaction ~ Days
#>
#> $random
#> $random[[1]]
#> ~1 | mysubgrp:mygrp
#>
#> $random[[2]]
#> ~1 | mygrp
#>
#> $random[[3]]
#> ~1 | Subject
find_random(m)
#> $random
#> [1] "mysubgrp:mygrp" "mygrp" "Subject"
#>
find_random(m, split_nested = TRUE)
#> $random
#> [1] "mysubgrp" "mygrp" "Subject"
find_random(m, split_nested = TRUE, flatten = TRUE)
#> [1] "mysubgrp" "mygrp" "Subject"
```
`find_formula()` and `find_random()` also work for models with zero-inflation part that have random effects, e.g. for models from the *glmmTMB* or *brms* packages. The "counterpart" to find possible random slopes would be [`find_random_slopes()`](https://easystats.github.io/insight/reference/find_random_slopes.html). |
8,736,137 | I'm using the JQuery UI datepicker plugin with
```
changeMonth: true,
changeYear: true
```
But the text field that holds the date only updates when the user actually clicks a day. If the user selects a month and year and then clicks outside the datepicker popup, I want the field to contain the first day of the month and year selected.
Currently the text field doesn't update unless the user actually clicks a particular day. Can anyone familiar with the plugin tell me if there is a way to fix this? | 2012/01/05 | [
"https://Stackoverflow.com/questions/8736137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692456/"
] | You could populate the text of the field yourself by defining the onChangeMonthYear callback function
From the docs:
onChangeMonthYear: Allows you to define your own event when the datepicker moves to a new month and/or year. The function receives the selected year, month (1-12), and the datepicker instance as parameters. this refers to the associated input field.
Code examples
Supply a callback function to handle the onChangeMonthYear event as an init option.
```
$('.selector').datepicker({
onChangeMonthYear: function(year, month, inst) { ... }
});
```
so this is what you would want:
```
$('.selector').datepicker({
onChangeMonthYear: function(year, month, inst) {
$(this).val(month + "/" + year);
}
});
```
[Example here](http://jsfiddle.net/GDvEk/) | mybe you can use something like this:
```
$('.selector').datepicker({
onChangeMonthYear: function(year, month, inst) {
var day = $(this).datepicker('getDate').getDate();
$(this).datepicker( "setDate", month+'/'+day+'/'+year);
}
});
```
Be carefully with location date format.
Complete example code here: <http://jsfiddle.net/FagGK/> |
49,167,367 | I have two query results.I need to merge the query result based on a condition.
```
$portfolio = DB::table('architects_portfolio')->get();
$img=DB::table('architects_portfolio_images')
->distinct()->get(['architects_images_id']);
```
and my condition to merge is
```
architects_portfolio.id = architects_portfolio_images.architects_images_id
```
I have my first table 'architects\_portfolio' which contain portfolio and second table 'architects\_portfolio\_images' which contain images of portfolio.I need to get only one image for now.But I get all images of portfolio now by using below code.But I need only one
```
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::join('architects_portfolio_images as images', 'architects_portfolio.id', '=', 'images.architects_images_id')
->where('architects_portfolio.architects_id', $architect->id)
->select('architects_portfolio.id', 'architects_portfolio.architects_id', 'architects_portfolio.name', 'architects_portfolio.description', 'images.filename','images.architects_images_id')
->distinct()->get(['images.architects_images_id']);
```
My tables
[architects\_potfolio](https://i.stack.imgur.com/E380l.png)
[architects\_portfolio\_images](https://i.stack.imgur.com/vkKOp.png) | 2018/03/08 | [
"https://Stackoverflow.com/questions/49167367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9418590/"
] | ```
$querys = DB::table('architects_portfolio');
$querys->select('architects_portfolio_images.architects_images_id');
$querys->join('architects_portfolio','architects_portfolio.id','=','architects_portfolio_images.architects_images_id')->distinct()->get();
``` | The best way is to use [relationships](https://laravel.com/docs/5.6/eloquent-relationships), then you could just load portfolios with related images:
```
$portfolios = ArhitectPortfolio::with('images')->get();
```
To make it work, you just need to define the `images` relationship in the `ArhitectPortfolio` model:
```
public function images()
{
return $this->hasMany(ArchitectPortfolioImage::class, 'architects_images_id');
}
``` |
49,167,367 | I have two query results.I need to merge the query result based on a condition.
```
$portfolio = DB::table('architects_portfolio')->get();
$img=DB::table('architects_portfolio_images')
->distinct()->get(['architects_images_id']);
```
and my condition to merge is
```
architects_portfolio.id = architects_portfolio_images.architects_images_id
```
I have my first table 'architects\_portfolio' which contain portfolio and second table 'architects\_portfolio\_images' which contain images of portfolio.I need to get only one image for now.But I get all images of portfolio now by using below code.But I need only one
```
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::join('architects_portfolio_images as images', 'architects_portfolio.id', '=', 'images.architects_images_id')
->where('architects_portfolio.architects_id', $architect->id)
->select('architects_portfolio.id', 'architects_portfolio.architects_id', 'architects_portfolio.name', 'architects_portfolio.description', 'images.filename','images.architects_images_id')
->distinct()->get(['images.architects_images_id']);
```
My tables
[architects\_potfolio](https://i.stack.imgur.com/E380l.png)
[architects\_portfolio\_images](https://i.stack.imgur.com/vkKOp.png) | 2018/03/08 | [
"https://Stackoverflow.com/questions/49167367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9418590/"
] | You should try this:
```
$rsltArchitectDetails = DB::table('architects_portfolio')
->select('architects_portfolio_images.architects_images_id')
->join('architects_portfolio_images', 'architects_portfolio.id' , '=', 'architects_portfolio_images.architects_images_id')
->distinct()
->get();
``` | The best way is to use [relationships](https://laravel.com/docs/5.6/eloquent-relationships), then you could just load portfolios with related images:
```
$portfolios = ArhitectPortfolio::with('images')->get();
```
To make it work, you just need to define the `images` relationship in the `ArhitectPortfolio` model:
```
public function images()
{
return $this->hasMany(ArchitectPortfolioImage::class, 'architects_images_id');
}
``` |
49,167,367 | I have two query results.I need to merge the query result based on a condition.
```
$portfolio = DB::table('architects_portfolio')->get();
$img=DB::table('architects_portfolio_images')
->distinct()->get(['architects_images_id']);
```
and my condition to merge is
```
architects_portfolio.id = architects_portfolio_images.architects_images_id
```
I have my first table 'architects\_portfolio' which contain portfolio and second table 'architects\_portfolio\_images' which contain images of portfolio.I need to get only one image for now.But I get all images of portfolio now by using below code.But I need only one
```
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::join('architects_portfolio_images as images', 'architects_portfolio.id', '=', 'images.architects_images_id')
->where('architects_portfolio.architects_id', $architect->id)
->select('architects_portfolio.id', 'architects_portfolio.architects_id', 'architects_portfolio.name', 'architects_portfolio.description', 'images.filename','images.architects_images_id')
->distinct()->get(['images.architects_images_id']);
```
My tables
[architects\_potfolio](https://i.stack.imgur.com/E380l.png)
[architects\_portfolio\_images](https://i.stack.imgur.com/vkKOp.png) | 2018/03/08 | [
"https://Stackoverflow.com/questions/49167367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9418590/"
] | Instead of merging we can make use of following code
```
$data = Architect::where("user_id", $user_id)->first();
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::where('architects_portfolio.architects_id', $architect->id)->paginate(6);
foreach ($portfolio as $r) {
$image = ArchitectsPortfolioImages::where('architects_images_id', $r->id)->first();
if ($image) {
$r->filename = $image->filename;
}
}
``` | The best way is to use [relationships](https://laravel.com/docs/5.6/eloquent-relationships), then you could just load portfolios with related images:
```
$portfolios = ArhitectPortfolio::with('images')->get();
```
To make it work, you just need to define the `images` relationship in the `ArhitectPortfolio` model:
```
public function images()
{
return $this->hasMany(ArchitectPortfolioImage::class, 'architects_images_id');
}
``` |
43,120,132 | There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).
I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.
This Service uses a Factory sometimes to delegate the instanciation of an object.
But this factory obviously needs to interact by itself with the database to instanciate my object properly.
Is it a good/bad practice to pass the Database context to the Create method for example?
Like this :
```
var myNewObject = MyFactory.Create(myDatabaseContext);
```
the other way would be to let the Service always be **the only one** to talk with the database.
```
var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;
```
Any advices? | 2017/03/30 | [
"https://Stackoverflow.com/questions/43120132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2432679/"
] | The idea of passing the database context into the factory create method is called method injection. This is a form of dependency injection, so you are on the right track.
You can use dependency injection to manage your database context inside of your factory via the constructor. The factory could look something like this:
```
public class MyFactory
{
private readonly IMyDbContext dbContext;
public MyFactory(IMyDbContext dbContext)
{
this.dbContext = dbContext;
}
public object Create()
{
// Use the dbContext, etc
}
}
```
Constructor injection is usually favored because it leaves method signatures less cluttered. We will also most likely have one type of database context so there will be no need to take advantage of polymorphism based on some other runtime information.
You can choose to use a Dependency Injection Container like [Ninject](http://www.ninject.org/) or, my favorite, [SimpleInjector](https://simpleinjector.org/index.html) to manage the dependencies for you.
It is OK to have the DbContext only used by the factory. One thing you may want to watch out for is that a user of your factory may not realize that the factory is calling to the database. This could be a bad thing and have negative performance implications. Typically, construction information is passed into the factory method, not initialized into the factory method from the DB. You could even take it a step further and use the [Repository Pattern](https://msdn.microsoft.com/en-us/library/ff649690.aspx) to abstract away some more of the data access logic if you think it is necessary and you don't have that already.
To learn more about Dependency Injection, in case you are unfamiliar, [you can start here](https://msdn.microsoft.com/en-us/library/dn178469(v=pandp.30).aspx).
My ideal structure may look like this:
```
public class MyFactory : IFactory
{
public object Create(object someProperty)
{
// build object
}
}
public class MyService
{
private readonly IMyDbContext dbContext;
private readonly IFactory factory;
public MyService(IMyDbContext dbContext, IFactory factory)
{
this.dbContext = dbContext;
this.factory = factory;
}
public void DoWork()
{
var property = dbContext.Get(something);
var newObj = factory.Create(property);
// Use stuff
}
}
``` | In the project I am working on, we try to keep all database access inside the Service. If the Factory needs objects that must be loaded from the DB, the Service should load them and pass them to the Factory. If the object returned by the Factory shall be persisted, the Service should add it to the DbContext.
This corresponds to the second way you have shown. The advantage is that the Factory can be unit tested without any need to mock the DbContext.
If you want to keep the DB access inside the Factory anyways, I would inject the DbContext into the constructor of the Factory, instead of passing it to the Create() method.
The Service gets an instance of the Factory injected in turn (instead of accessing static methods of the Factory). Again, this will make mocking much easier.
```
public class Service {
private readonly IMyDbContext _myDatabaseContext;
private readonly IMyFactory _myfactory;
public Service (IMyDbContext myDbContext, IMyFactory myfactory) {
_myDatabaseContext = myDbContext;
_myfactory = myfactory
}
public void Create() {
var extraProperty = myDatabaseContext.Get(something);
var myNewObject = _myFactory.Create(extraProperty);
_myDatabaseContext.Add(myNewObject);
_myDatabaseContext.SaveChanges();
}
}
``` |
54,189,829 | I am writing a recursive function that will create empty buckets according to n. However my code is not working. No matter what n is it'll only print none.
Can someone help me with where I am going wrong?
for example if n is 5 it should print [[], [], [], [], []]
```
def emptyBuckets(n):
assert n > 0
bucket = []
# Base case: only one empty bucket
if n == 1:
return bucket
else:
return (bucket.append(emptyBuckets(n-1))
print (emptyBuckets(5))
``` | 2019/01/14 | [
"https://Stackoverflow.com/questions/54189829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10875651/"
] | ```
$form = $this->createForm(MyFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/**
* Do your stuff when form is valid
*/
} else {
/**
* Here you can get the input data even failed with $form->getData()
*/
dump($form->getData());
}
```
`$form->getData()` gives me the values of input that didn't failed in the else:
```
array:4 [▼
"first_dropdown" => "hello"
]
``` | $advert = new Advert();
```
$form = $this->createForm(AdvertType::class, $advert, ['method' => 'POST'])
->handleRequest($request);
if (false === $form->isSubmitted()) {
$form->submit([]);
}
if (false === $form->isValid()) {
return ['form' => $form];
}
$manager = $this->getDoctrine()->getManager();
$this->appendTags($advert);
$manager->persist($advert);
$manager->flush();
return $advert;
``` |
54,189,829 | I am writing a recursive function that will create empty buckets according to n. However my code is not working. No matter what n is it'll only print none.
Can someone help me with where I am going wrong?
for example if n is 5 it should print [[], [], [], [], []]
```
def emptyBuckets(n):
assert n > 0
bucket = []
# Base case: only one empty bucket
if n == 1:
return bucket
else:
return (bucket.append(emptyBuckets(n-1))
print (emptyBuckets(5))
``` | 2019/01/14 | [
"https://Stackoverflow.com/questions/54189829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10875651/"
] | ```
$form = $this->createForm(MyFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/**
* Do your stuff when form is valid
*/
} else {
/**
* Here you can get the input data even failed with $form->getData()
*/
dump($form->getData());
}
```
`$form->getData()` gives me the values of input that didn't failed in the else:
```
array:4 [▼
"first_dropdown" => "hello"
]
``` | I needed something like below, in my form type class eg. DocType in buildForm() method I did:
```
$request = Request::createFromGlobals();
$myObjectId = $request->request->get('doc')['object']; // selected option of the first dropdown
$object = ($obectId) ? $objectRepository->find($objectId) : null;
```
Then I could use fetched object, to populate second dropdown, using query builder. |
61,247,862 | I want to convert sql query to entity framework core.
SQL query is
```
select * from Departments where id in(select DepartmentId from SubDepartments where id in(select SubDeptId from Tests where id in(select TestId from PatientTests where PatientId=3)))
``` | 2020/04/16 | [
"https://Stackoverflow.com/questions/61247862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6288727/"
] | You've got a few things to address here so lets break it down a little bit.
1) When you call `upload_to_s3()` you need to call it with the function parameters you've declared it with, a filename and a bucket key. So it would be `upload_to_s3(filename, bucket_key)` for example.
2) It's a been a while since I used Windows & Python but ask yourself if it uses `\` instead of `/` in file paths, also make sure the file is definitely in the location you expect.
3) For the S3 upload the `Body:` is the actual data you want to upload, not the filename of the data. You have called it inside `open(...) as file` so you now have an object called `file` that represents it. | I guess you are using put\_object() the wrong way. It is used to save an **'object'** on s3 & **not a file** i.e you need to first read the file content using pandas.read\_csv() or something else & then replace the 'Body' part with the object obtained on reading.Something like this
```
df= pandas.read_csv('C:\Users\U12345/IdeaProjects/xxx/test.csv')
response = s3_client.put_object(Body=df,
Bucket=output_bucket,
Key='test.csv',
ACL="bucket-owner-full-control")
```
If you wish to upload the file directly, you should use
```
s3 = boto3.resource('s3')
s3.meta.client.upload_file('C:\Users\U12345/IdeaProjects/xxx/test.csv', output_bucket, 'test.csv')
``` |
61,247,862 | I want to convert sql query to entity framework core.
SQL query is
```
select * from Departments where id in(select DepartmentId from SubDepartments where id in(select SubDeptId from Tests where id in(select TestId from PatientTests where PatientId=3)))
``` | 2020/04/16 | [
"https://Stackoverflow.com/questions/61247862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6288727/"
] | I guess you are using put\_object() the wrong way. It is used to save an **'object'** on s3 & **not a file** i.e you need to first read the file content using pandas.read\_csv() or something else & then replace the 'Body' part with the object obtained on reading.Something like this
```
df= pandas.read_csv('C:\Users\U12345/IdeaProjects/xxx/test.csv')
response = s3_client.put_object(Body=df,
Bucket=output_bucket,
Key='test.csv',
ACL="bucket-owner-full-control")
```
If you wish to upload the file directly, you should use
```
s3 = boto3.resource('s3')
s3.meta.client.upload_file('C:\Users\U12345/IdeaProjects/xxx/test.csv', output_bucket, 'test.csv')
``` | in the last line
```
upload_to_s3()
```
you haven't actually given the function any parameters. inside the brackets put in the params:
```
(source_filename: str, key: str)
```
ie give the function it's filename and bucket |
61,247,862 | I want to convert sql query to entity framework core.
SQL query is
```
select * from Departments where id in(select DepartmentId from SubDepartments where id in(select SubDeptId from Tests where id in(select TestId from PatientTests where PatientId=3)))
``` | 2020/04/16 | [
"https://Stackoverflow.com/questions/61247862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6288727/"
] | You've got a few things to address here so lets break it down a little bit.
1) When you call `upload_to_s3()` you need to call it with the function parameters you've declared it with, a filename and a bucket key. So it would be `upload_to_s3(filename, bucket_key)` for example.
2) It's a been a while since I used Windows & Python but ask yourself if it uses `\` instead of `/` in file paths, also make sure the file is definitely in the location you expect.
3) For the S3 upload the `Body:` is the actual data you want to upload, not the filename of the data. You have called it inside `open(...) as file` so you now have an object called `file` that represents it. | in the last line
```
upload_to_s3()
```
you haven't actually given the function any parameters. inside the brackets put in the params:
```
(source_filename: str, key: str)
```
ie give the function it's filename and bucket |
16,044,839 | What is the most appropriate protocol (**SOAP** or **REST** with JSON format) to use with a **mobile OS** Android or iOS application that uses a web services exposed by a Java/Java EE application?
Which one is going to be more performant and providing security, atomic transaction and reliability? | 2013/04/16 | [
"https://Stackoverflow.com/questions/16044839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408361/"
] | You'll need to define your security requirements a little better.
SOAP with WS-Security can be used to ensure the integrity of message, and that only the appropriate process can use the data.
It this is what you mean by security, you're better of with SOAP as it has handling capabilities for this.
REST is built ontop of standard HTTP operations: GET,PUT,DELETE,POST, and as such, security is based on two areas:
1. End to End security, provided by SSL (HTTP)
2. Authentication, which range from basic HTTP authentication, to custom providers, such as OAUTH2.
From a development perspective, REST based APIs, using JSON dataformat are easier to work with. | My vote goes with REST with JSON. |
858,000 | >
> let $A=\{x^3+y^3+z^3-3xyz\mid x,y,z\in \mathbb {Z}\}$, prove that:
>
>
> if $a,b\in A$, then $ab\in A$,
>
>
>
I think we must find $A,B,C$ such
$$A^3+B^3+C^3-3ABC=(a^3+b^3+c^3-3abc)(x^3+y^3+z^3-3xyz)$$
where $A,B,C,a,b,c,x,y,z\in \mathbb Z$, but I can't find it.
I think this result is interesting, I hope someone can solve it.
Thank you | 2014/07/06 | [
"https://math.stackexchange.com/questions/858000",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58742/"
] | Hint :
Consider the matrix :
$$\mathcal{D}\_{a,b,c}=\begin{pmatrix}
a&b&c\\
c&a&b\\
b&c&a\\
\end{pmatrix}$$
See, $$\mathcal{D}\_{a,b,c}\times \mathcal{D}\_{x,y,z}=\mathcal{D}\_{p,q,r}$$
Now $\det (\mathcal{D}\_{a,b,c})=a^3+b^3+c^3-3abc$
Looks like this hint solved the problem almost. :P | This answer is contained in the other, but by symmetry it is natural to write
$$A=ax+by+cz$$
$$B=cx+ay+bz$$
$$C=bx+cy+az$$ and its easy to see this satisfies the equation given by OP. |
6,231,198 | I have a problem with the new Xcode (today I upgraded). When I push on my file `view.xib`, I see the `XML` code, and not the graphics interface. Why? How can I see the "interface builder? | 2011/06/03 | [
"https://Stackoverflow.com/questions/6231198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608294/"
] | Interesting that this is the second time someone has had this problem. You can open the `File Inspector` on the Utilities bar on the right ( Opt+Cmd+1 ). Change the `File Type` under `Identity and Type` to the topmost choice. It should be `Default - com.apple.InterfaceBuilder3.CocoaTouch.XIB`. | Perhaps you should look at this Article, it will explain a lot for you:
[Xcode 4 Transition Guide: Designing User Interfaces in Xcode 4:](http://developer.apple.com/library/ios/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/InterfaceBuilder/InterfaceBuilder.html) |
6,231,198 | I have a problem with the new Xcode (today I upgraded). When I push on my file `view.xib`, I see the `XML` code, and not the graphics interface. Why? How can I see the "interface builder? | 2011/06/03 | [
"https://Stackoverflow.com/questions/6231198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608294/"
] | Right Click on the .xib file and select "Open As". Then select "Xcode.IDEKit.TouchCodeIntegration.EditorDocument.CocoaTouch-title" | Perhaps you should look at this Article, it will explain a lot for you:
[Xcode 4 Transition Guide: Designing User Interfaces in Xcode 4:](http://developer.apple.com/library/ios/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/InterfaceBuilder/InterfaceBuilder.html) |
40,245 | ### Background
I have no experience with midi (other than what I've read online) and I don't yet have any midi equipment to play with (but I have several devices working their way through the mail system).
### Question
Is it possible to have multiple midi keyboard controllers set to the same midi channel, but transposed to different octaves, controlling the same sound generator? Perhaps a better way to ask that is what problems am I likely to encounter having multiple keyboard controllers daisy-chained together that are set to the same channel?
### Details
I'm getting a Memotron M2D sound generator - it only listens on one channel, but it has three voices that can be split across different key ranges of the 128 midi notes (C0 to C10 or whichever numbering you prefer). Eventually, I plan to midify an old organ pedal board and combine this with two (small) midi keyboard controllers so that I have a different voice for each manual. From all my reading, it seems like I should be able to set all these to the same channel, daisy chain them into the M2D and as long as I have the octave ranges set so they don't overlap and match the mapping in the M2D this should work. However, I can't find any discussion of merging multiple controllers into a single device (lots of discussions of chaining multiple controllers to multiple devices or one controller to multiple devices). From what I've read, the biggest potential problem seems to be that a controller may not merge the data it's receiving on the "in" port with the data it's sending out - i.e., it may simply drop all the incoming midi data and only send out it's own data. However, for *dumb* controllers (i.e., that have no sound generating ability, like the Arturia Keylab) I can't imagine why the data coming into the "in" port wouldn't be passed along to the "out" port, so something like the example below should work (in my mind).
```
keyboard 1 (chan 1) -> Arturia keyboard 2 (chan 1) -> M2D (listening on chan 1)
```
But, I have zero experience with midi at this point. | 2015/12/14 | [
"https://music.stackexchange.com/questions/40245",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/25237/"
] | Those letters are just section identification. They are not meant to indicate notes to play. You might use them in a rehearsal where someone says "Ok let's all play section **C** now". | They aren't played.
They are used to identify parts of the composition. This way you are able to communicate about the piece by using the letters. |
40,245 | ### Background
I have no experience with midi (other than what I've read online) and I don't yet have any midi equipment to play with (but I have several devices working their way through the mail system).
### Question
Is it possible to have multiple midi keyboard controllers set to the same midi channel, but transposed to different octaves, controlling the same sound generator? Perhaps a better way to ask that is what problems am I likely to encounter having multiple keyboard controllers daisy-chained together that are set to the same channel?
### Details
I'm getting a Memotron M2D sound generator - it only listens on one channel, but it has three voices that can be split across different key ranges of the 128 midi notes (C0 to C10 or whichever numbering you prefer). Eventually, I plan to midify an old organ pedal board and combine this with two (small) midi keyboard controllers so that I have a different voice for each manual. From all my reading, it seems like I should be able to set all these to the same channel, daisy chain them into the M2D and as long as I have the octave ranges set so they don't overlap and match the mapping in the M2D this should work. However, I can't find any discussion of merging multiple controllers into a single device (lots of discussions of chaining multiple controllers to multiple devices or one controller to multiple devices). From what I've read, the biggest potential problem seems to be that a controller may not merge the data it's receiving on the "in" port with the data it's sending out - i.e., it may simply drop all the incoming midi data and only send out it's own data. However, for *dumb* controllers (i.e., that have no sound generating ability, like the Arturia Keylab) I can't imagine why the data coming into the "in" port wouldn't be passed along to the "out" port, so something like the example below should work (in my mind).
```
keyboard 1 (chan 1) -> Arturia keyboard 2 (chan 1) -> M2D (listening on chan 1)
```
But, I have zero experience with midi at this point. | 2015/12/14 | [
"https://music.stackexchange.com/questions/40245",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/25237/"
] | Both are right, these marks are to denote the section you are playing and you don't play anything specifically for them. The proper name for these marks are **rehearsal marks**.
In an sense you can look at them as practice checkpoints as they are typically where you would want to start playing if you needed more practice on that section instead of playing the whole piece. It is much easier to reference a section by letter rather than measure number which can not only be hard to spot, but can lead to problems if you need to count the measures on your score as sometimes counting is hard. | Those letters are just section identification. They are not meant to indicate notes to play. You might use them in a rehearsal where someone says "Ok let's all play section **C** now". |
40,245 | ### Background
I have no experience with midi (other than what I've read online) and I don't yet have any midi equipment to play with (but I have several devices working their way through the mail system).
### Question
Is it possible to have multiple midi keyboard controllers set to the same midi channel, but transposed to different octaves, controlling the same sound generator? Perhaps a better way to ask that is what problems am I likely to encounter having multiple keyboard controllers daisy-chained together that are set to the same channel?
### Details
I'm getting a Memotron M2D sound generator - it only listens on one channel, but it has three voices that can be split across different key ranges of the 128 midi notes (C0 to C10 or whichever numbering you prefer). Eventually, I plan to midify an old organ pedal board and combine this with two (small) midi keyboard controllers so that I have a different voice for each manual. From all my reading, it seems like I should be able to set all these to the same channel, daisy chain them into the M2D and as long as I have the octave ranges set so they don't overlap and match the mapping in the M2D this should work. However, I can't find any discussion of merging multiple controllers into a single device (lots of discussions of chaining multiple controllers to multiple devices or one controller to multiple devices). From what I've read, the biggest potential problem seems to be that a controller may not merge the data it's receiving on the "in" port with the data it's sending out - i.e., it may simply drop all the incoming midi data and only send out it's own data. However, for *dumb* controllers (i.e., that have no sound generating ability, like the Arturia Keylab) I can't imagine why the data coming into the "in" port wouldn't be passed along to the "out" port, so something like the example below should work (in my mind).
```
keyboard 1 (chan 1) -> Arturia keyboard 2 (chan 1) -> M2D (listening on chan 1)
```
But, I have zero experience with midi at this point. | 2015/12/14 | [
"https://music.stackexchange.com/questions/40245",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/25237/"
] | Both are right, these marks are to denote the section you are playing and you don't play anything specifically for them. The proper name for these marks are **rehearsal marks**.
In an sense you can look at them as practice checkpoints as they are typically where you would want to start playing if you needed more practice on that section instead of playing the whole piece. It is much easier to reference a section by letter rather than measure number which can not only be hard to spot, but can lead to problems if you need to count the measures on your score as sometimes counting is hard. | They aren't played.
They are used to identify parts of the composition. This way you are able to communicate about the piece by using the letters. |
280,672 | I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)? | 2008/11/11 | [
"https://Stackoverflow.com/questions/280672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36525/"
] | As you mention in the comments that you want to "merge" the databases, this sounds like you need to write custom code to do this, as presumably there could be conficts - the same key in both, but with different details against it, for example. | I guess you are using [Java DB (aka Derby)](http://developers.sun.com/javadb/) - in which case, assuming you just can't use a single instance, you can do a [backup/restore](http://db.apache.org/derby/docs/10.3/adminguide/). |
280,672 | I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)? | 2008/11/11 | [
"https://Stackoverflow.com/questions/280672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36525/"
] | In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked:
```
Customer:
SiteCode varchar,
CustomerID varchar,
....
primary key(siteCode, CustomerID)
```
So now you would take your databases, and match up each record by primary key. Where there are conflicts you would have to provide a report to the end-user, on what data was different.
Say machine1:
```
SiteCode|CustomerID|CustName |phone |email
1 XXX |0001 |Customer1 |555.555.1212 |darth@example.com
```
and on machine2:
```
SiteCode|CustomerID|CustName |phone |email
2 XXY |0001 |customer2 |555.555.1213 |darth@nowhere.com
3 XXX |0001 |customer1 |555.555.1212 |darth@nowhere.com
```
When performing a resolution:
* Record 1 and 3 are in conflict, because the PK matches, but the data doesnt (email is different).
* Record 2 is unique, and can freely exist in both databases.
There is *NO* way to do this automatically without error or data corruption or referential integrity issues. | I guess you are using [Java DB (aka Derby)](http://developers.sun.com/javadb/) - in which case, assuming you just can't use a single instance, you can do a [backup/restore](http://db.apache.org/derby/docs/10.3/adminguide/). |
280,672 | I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)? | 2008/11/11 | [
"https://Stackoverflow.com/questions/280672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36525/"
] | As you mention in the comments that you want to "merge" the databases, this sounds like you need to write custom code to do this, as presumably there could be conficts - the same key in both, but with different details against it, for example. | Why dont you have the database on one pc. and have all other pc's request data from the host pc |
280,672 | I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)? | 2008/11/11 | [
"https://Stackoverflow.com/questions/280672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36525/"
] | In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked:
```
Customer:
SiteCode varchar,
CustomerID varchar,
....
primary key(siteCode, CustomerID)
```
So now you would take your databases, and match up each record by primary key. Where there are conflicts you would have to provide a report to the end-user, on what data was different.
Say machine1:
```
SiteCode|CustomerID|CustName |phone |email
1 XXX |0001 |Customer1 |555.555.1212 |darth@example.com
```
and on machine2:
```
SiteCode|CustomerID|CustName |phone |email
2 XXY |0001 |customer2 |555.555.1213 |darth@nowhere.com
3 XXX |0001 |customer1 |555.555.1212 |darth@nowhere.com
```
When performing a resolution:
* Record 1 and 3 are in conflict, because the PK matches, but the data doesnt (email is different).
* Record 2 is unique, and can freely exist in both databases.
There is *NO* way to do this automatically without error or data corruption or referential integrity issues. | Why dont you have the database on one pc. and have all other pc's request data from the host pc |
4,249,767 | This is a random question that came to me, obviously I wouldn't want to do it because it is bad practice, but is it possible to compile and run code from a file without an extension? Does this work with c,c++, java, python, any languages? If it does, than is the extension more of a stylist property or does it have a purpose for something else? | 2010/11/22 | [
"https://Stackoverflow.com/questions/4249767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411201/"
] | Extension doesn't mean anything. Just a way to help you keep track of what file is what. (also helps stuff like a GUI explorer open the file in the right program).
(Java might care becuase the language spec says a source files end in .java, but there may be a way to hack it). | This is really compiler dependent. For example, I would imagine that there are C/C++ compiler dispatchers that make some assumptions based on the file ending in .c or .cpp but there may also be command line options to explicitly specify how a file should be handled. |
4,249,767 | This is a random question that came to me, obviously I wouldn't want to do it because it is bad practice, but is it possible to compile and run code from a file without an extension? Does this work with c,c++, java, python, any languages? If it does, than is the extension more of a stylist property or does it have a purpose for something else? | 2010/11/22 | [
"https://Stackoverflow.com/questions/4249767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411201/"
] | Extension doesn't mean anything. Just a way to help you keep track of what file is what. (also helps stuff like a GUI explorer open the file in the right program).
(Java might care becuase the language spec says a source files end in .java, but there may be a way to hack it). | This depends more on the used compiler than on the language. E.g. gcc/g++ has a commandline option `-x <language>` that allows to override the detection based on the file extension. One use-case is using `-` (i.e. stdin) as input. |
4,249,767 | This is a random question that came to me, obviously I wouldn't want to do it because it is bad practice, but is it possible to compile and run code from a file without an extension? Does this work with c,c++, java, python, any languages? If it does, than is the extension more of a stylist property or does it have a purpose for something else? | 2010/11/22 | [
"https://Stackoverflow.com/questions/4249767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411201/"
] | Extension doesn't mean anything. Just a way to help you keep track of what file is what. (also helps stuff like a GUI explorer open the file in the right program).
(Java might care becuase the language spec says a source files end in .java, but there may be a way to hack it). | Many compilers can accept multiple types of files in a build, and use the extension of a file to determine what to do with it. For example, one might be able to say:
```
acmecompile foo.c bar.c fred.cpp wow.asm lib1.lib compilething.obj -o result.exe
```
It would use the extensions of the various files to determine that the first two should be fed through the C compiler, the next through a C++ compiler, and the next through an assembler. The last two should be fed directly to the linker.
Often, there will be some means of telling a compiler that a particular file should be handled a particular way regardless of its extension; for example, it may sometimes be desirable to some files in a multi-targeted application compile as C for some targets and C++ for others (on one of my projects, the primary target is built in C and uses hardware I/O registers; while another target, built with C++, replaces those registers with properties). |
4,249,767 | This is a random question that came to me, obviously I wouldn't want to do it because it is bad practice, but is it possible to compile and run code from a file without an extension? Does this work with c,c++, java, python, any languages? If it does, than is the extension more of a stylist property or does it have a purpose for something else? | 2010/11/22 | [
"https://Stackoverflow.com/questions/4249767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411201/"
] | This is really compiler dependent. For example, I would imagine that there are C/C++ compiler dispatchers that make some assumptions based on the file ending in .c or .cpp but there may also be command line options to explicitly specify how a file should be handled. | Many compilers can accept multiple types of files in a build, and use the extension of a file to determine what to do with it. For example, one might be able to say:
```
acmecompile foo.c bar.c fred.cpp wow.asm lib1.lib compilething.obj -o result.exe
```
It would use the extensions of the various files to determine that the first two should be fed through the C compiler, the next through a C++ compiler, and the next through an assembler. The last two should be fed directly to the linker.
Often, there will be some means of telling a compiler that a particular file should be handled a particular way regardless of its extension; for example, it may sometimes be desirable to some files in a multi-targeted application compile as C for some targets and C++ for others (on one of my projects, the primary target is built in C and uses hardware I/O registers; while another target, built with C++, replaces those registers with properties). |
4,249,767 | This is a random question that came to me, obviously I wouldn't want to do it because it is bad practice, but is it possible to compile and run code from a file without an extension? Does this work with c,c++, java, python, any languages? If it does, than is the extension more of a stylist property or does it have a purpose for something else? | 2010/11/22 | [
"https://Stackoverflow.com/questions/4249767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411201/"
] | This depends more on the used compiler than on the language. E.g. gcc/g++ has a commandline option `-x <language>` that allows to override the detection based on the file extension. One use-case is using `-` (i.e. stdin) as input. | Many compilers can accept multiple types of files in a build, and use the extension of a file to determine what to do with it. For example, one might be able to say:
```
acmecompile foo.c bar.c fred.cpp wow.asm lib1.lib compilething.obj -o result.exe
```
It would use the extensions of the various files to determine that the first two should be fed through the C compiler, the next through a C++ compiler, and the next through an assembler. The last two should be fed directly to the linker.
Often, there will be some means of telling a compiler that a particular file should be handled a particular way regardless of its extension; for example, it may sometimes be desirable to some files in a multi-targeted application compile as C for some targets and C++ for others (on one of my projects, the primary target is built in C and uses hardware I/O registers; while another target, built with C++, replaces those registers with properties). |
199,613 | Sometimes, when changing the resolution on windows, it just changes it and does nothing more. On some computers, it asks "do you want to keep these display settings?" and if you click nothing within 15 seconds it reverts them. What controls whether the dialog appears? How can I disable it? | 2010/10/14 | [
"https://superuser.com/questions/199613",
"https://superuser.com",
"https://superuser.com/users/4668/"
] | If there's a way to disable the dialog once and for all, I don't know what it is, but I do know how to do it for individual video modes. Prepare for a complicated answer to a simple question.
The thing that determines whether that dialog appears is whether the mode you're switching to has been used on that system before. It therefore stands to reason that convincing Windows that the mode you want to use had been used before would disable the dialog.
So, I did some digging for where this information might be stored, and it seems that, on XP at least, the place is the registry path
`HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Control Panel\Settings\Video\[key named after your video adapter's device ID]\[key named after your monitor and its GUID]`
Under this path, there are keys named in the format "[width]x[height] x [refresh rate]Hz". Under those keys, there are DWORD values for color depths in the format "[depth] bpp", which are set to 1 if that depth has been used at that resolution and refresh rate. So, if you wanted to disable the dialog for 1280x720@60Hz and 32 bit color, you would make a key called "1280x720 x 60Hz" and put a DWORD value in it called "32 bpp" and set it to 1.
Now, you don't say what you need this for, so I don't know how you would want to deploy it, or even how you could, given that GUID in there; if it's not for a large number of installations, I would say this is more trouble than it's worth. | I'm not sure, but may it be that this is only asked with analogue connectors like VGA? Because there's no check if the connected device can handle that resolution. DVI/HDMI both have those capability informations. |
199,613 | Sometimes, when changing the resolution on windows, it just changes it and does nothing more. On some computers, it asks "do you want to keep these display settings?" and if you click nothing within 15 seconds it reverts them. What controls whether the dialog appears? How can I disable it? | 2010/10/14 | [
"https://superuser.com/questions/199613",
"https://superuser.com",
"https://superuser.com/users/4668/"
] | Right Click on your desktop and go to "Properties". Under the Settings Tab, Click Advanced. Under the General tab, there is a Compatibility section. The settings are technically there. What I found works is to set it to "Ask me before applying changes". When the window pops up click the "Do not ask me again" check box.
You shouldn't have that prompt anymore.
Hope that helps. | I'm not sure, but may it be that this is only asked with analogue connectors like VGA? Because there's no check if the connected device can handle that resolution. DVI/HDMI both have those capability informations. |
199,613 | Sometimes, when changing the resolution on windows, it just changes it and does nothing more. On some computers, it asks "do you want to keep these display settings?" and if you click nothing within 15 seconds it reverts them. What controls whether the dialog appears? How can I disable it? | 2010/10/14 | [
"https://superuser.com/questions/199613",
"https://superuser.com",
"https://superuser.com/users/4668/"
] | If there's a way to disable the dialog once and for all, I don't know what it is, but I do know how to do it for individual video modes. Prepare for a complicated answer to a simple question.
The thing that determines whether that dialog appears is whether the mode you're switching to has been used on that system before. It therefore stands to reason that convincing Windows that the mode you want to use had been used before would disable the dialog.
So, I did some digging for where this information might be stored, and it seems that, on XP at least, the place is the registry path
`HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Control Panel\Settings\Video\[key named after your video adapter's device ID]\[key named after your monitor and its GUID]`
Under this path, there are keys named in the format "[width]x[height] x [refresh rate]Hz". Under those keys, there are DWORD values for color depths in the format "[depth] bpp", which are set to 1 if that depth has been used at that resolution and refresh rate. So, if you wanted to disable the dialog for 1280x720@60Hz and 32 bit color, you would make a key called "1280x720 x 60Hz" and put a DWORD value in it called "32 bpp" and set it to 1.
Now, you don't say what you need this for, so I don't know how you would want to deploy it, or even how you could, given that GUID in there; if it's not for a large number of installations, I would say this is more trouble than it's worth. | Right Click on your desktop and go to "Properties". Under the Settings Tab, Click Advanced. Under the General tab, there is a Compatibility section. The settings are technically there. What I found works is to set it to "Ask me before applying changes". When the window pops up click the "Do not ask me again" check box.
You shouldn't have that prompt anymore.
Hope that helps. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | As the other answerers have already pointed out, lasers are by definition light, and light by definition always travels through space at the speed of light in whatever medium it's travelling through. So you have two options: either it must travel through some medium with a lower speed of light, or it must travel through more space than just the Euclidean straight-line distance from the start to the end of its trajectory.
Other answers have already proposed either changing the medium or changing the trajectory to not be a straight line. I think there is only one more possibility: warp space around the laser beam, so that the straight line trajectory covers more spatial distance than it would in a flat spacetime. An [Alcubierre warp drive](https://en.wikipedia.org/wiki/Alcubierre_drive) is a hypothetical device which warps space in order to achieve "faster-than-light" travel for something which cannot travel *through* space faster than light; imagine something like this in reverse, which warps space to achieve "slower-than-light" travel for something which cannot travel *through* space slower than light.
Now, why anyone would go to all this trouble in order to make their weapons slower is beyond me... but if you can invent a plausible reason for it in your story, go for it. | You haven't included a hard science tag, so, sure! Just have a gun that alters the local speed of light so that lasers go slower than the speed of light. Perhaps they could store up light to make a more powerful laser.
You control the physical laws of your universe, you can them do whatever you want. It may not be physically possible in our universe, but in a sci fi universe it can be. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Lasers are not plasma weapons.
Plasma is a "soup" of free electrons and ionized atomic nuclei.
Lasers are coherent beams of photons.
Photons travel always at the velocity of light in the medium they propagate in ($c$ in vacuum, $c/n$ in a medium other than vacuum, with $n$ being its refractive index). End of the story.
**N.B.** Since $n$ is always bigger than 1, in any medium other than vacuum the photons travel slower than *the speed of light in vacuum*. | If the goal is to be able to watch the beam of light travel like in movies, that's not going to work.
However, one possibility is that pulling the trigger only begins the process of sending the beam - like a camera flash, there's a charge-up followed by a discharge a little bit later. The charge-up can't happen in advance because it leaks away too quickly to be practical, though. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Not an actual laser, no. Laser is *light*, and by definition, the speed of any light is the speed of light. *In vacuo* that is ~300.000 km/s or so.
But you can *cheat*. Your "laser" might be some mixture of (*waves hands quickly*) light ions in an electromagnetically bound [self-contained matrix](https://en.wikipedia.org/wiki/Rydberg_matter), sort of a [Kugelblitz](https://en.wikipedia.org/wiki/Ball_lightning). The energy contents of the "package" is several orders of magnitude beyond that of a simple laser, which explains why it is preferred to the latter, even though its speed is lower and avoiding a hit is possible. You could call this a Kugelblitz device, a Rydberg projector, or a "soliton gun". | You haven't included a hard science tag, so, sure! Just have a gun that alters the local speed of light so that lasers go slower than the speed of light. Perhaps they could store up light to make a more powerful laser.
You control the physical laws of your universe, you can them do whatever you want. It may not be physically possible in our universe, but in a sci fi universe it can be. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Lasers are not plasma weapons.
Plasma is a "soup" of free electrons and ionized atomic nuclei.
Lasers are coherent beams of photons.
Photons travel always at the velocity of light in the medium they propagate in ($c$ in vacuum, $c/n$ in a medium other than vacuum, with $n$ being its refractive index). End of the story.
**N.B.** Since $n$ is always bigger than 1, in any medium other than vacuum the photons travel slower than *the speed of light in vacuum*. | Realistically no, a electromagnetic wave will only propagate at the speed of light in that material.(air) It can change very slightly with things like [temperature and pressure](http://www.madsci.org/posts/archives/1998-02/888690999.Ph.r.html) but not to the extreme levels needed for it to be perceptible to human senses. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Lasers are not plasma weapons.
Plasma is a "soup" of free electrons and ionized atomic nuclei.
Lasers are coherent beams of photons.
Photons travel always at the velocity of light in the medium they propagate in ($c$ in vacuum, $c/n$ in a medium other than vacuum, with $n$ being its refractive index). End of the story.
**N.B.** Since $n$ is always bigger than 1, in any medium other than vacuum the photons travel slower than *the speed of light in vacuum*. | Not an actual laser, no. Laser is *light*, and by definition, the speed of any light is the speed of light. *In vacuo* that is ~300.000 km/s or so.
But you can *cheat*. Your "laser" might be some mixture of (*waves hands quickly*) light ions in an electromagnetically bound [self-contained matrix](https://en.wikipedia.org/wiki/Rydberg_matter), sort of a [Kugelblitz](https://en.wikipedia.org/wiki/Ball_lightning). The energy contents of the "package" is several orders of magnitude beyond that of a simple laser, which explains why it is preferred to the latter, even though its speed is lower and avoiding a hit is possible. You could call this a Kugelblitz device, a Rydberg projector, or a "soliton gun". |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Lasers are not plasma weapons.
Plasma is a "soup" of free electrons and ionized atomic nuclei.
Lasers are coherent beams of photons.
Photons travel always at the velocity of light in the medium they propagate in ($c$ in vacuum, $c/n$ in a medium other than vacuum, with $n$ being its refractive index). End of the story.
**N.B.** Since $n$ is always bigger than 1, in any medium other than vacuum the photons travel slower than *the speed of light in vacuum*. | You haven't included a hard science tag, so, sure! Just have a gun that alters the local speed of light so that lasers go slower than the speed of light. Perhaps they could store up light to make a more powerful laser.
You control the physical laws of your universe, you can them do whatever you want. It may not be physically possible in our universe, but in a sci fi universe it can be. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | If you mean lasers going slower than $c$, as in the speed of light in a vacuum, then your only choice is shooting them in a medium other than the vacuum of space. Light is slower when travelling through a gas medium such as an atmosphere. However, the difference in speed between a vacuum and an atmosphere such as ours is practically negligible.
You would need a very special medium such as a [Bose-Einstein condensate](https://en.wikipedia.org/wiki/Bose%E2%80%93Einstein_condensate) to really slow down light (its speed falls to 17m/s in such a medium).
Notice that in any case slowing down a laser will not allow you to see it coming.
As an alternative, consider [laser powered rockets](https://en.wikipedia.org/wiki/Laser_propulsion). Basically you shoot a rocket, but instead of the rocket burning fuel in order to accelerate, you push it with lasers. This allows them to go arbitrarily much further and faster, and depending on the power you spend they might hit the target as a red or white hot stream of molten metal that from a distance might look like a laser beam as seen in some videogames. | Not an actual laser, no. Laser is *light*, and by definition, the speed of any light is the speed of light. *In vacuo* that is ~300.000 km/s or so.
But you can *cheat*. Your "laser" might be some mixture of (*waves hands quickly*) light ions in an electromagnetically bound [self-contained matrix](https://en.wikipedia.org/wiki/Rydberg_matter), sort of a [Kugelblitz](https://en.wikipedia.org/wiki/Ball_lightning). The energy contents of the "package" is several orders of magnitude beyond that of a simple laser, which explains why it is preferred to the latter, even though its speed is lower and avoiding a hit is possible. You could call this a Kugelblitz device, a Rydberg projector, or a "soliton gun". |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | **Don't shoot straight.**
Suppose I want to go get some Jolly Ranchers. The bodega that has all the flavors is 1 mile away. My Chevy Nova only goes 100 miles per hour. But I want it to take all day to get there.
I take a circuitous route. I set off in the opposite direction and go through town, laying on the horn, taking in the sights.
So too your laser. You can have it get there slowly even at the speed of light if you send your light somewhere else, reflect it, reflect it, curve it, reflect it etc.
If you are not talking about a banked shot from the Death star but little flying lasers of the "pew pew" variety, you could create extradimensional reflectors. Extra dimensions do not violate physics. If your beam is bouncing off reflectors in adjacent third dimensions that could slow it down; from your standpoint it is going in a straight line but it is actually going much, much farther when you count the extradimensional excursions. | You haven't included a hard science tag, so, sure! Just have a gun that alters the local speed of light so that lasers go slower than the speed of light. Perhaps they could store up light to make a more powerful laser.
You control the physical laws of your universe, you can them do whatever you want. It may not be physically possible in our universe, but in a sci fi universe it can be. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | Yes, but not in a way you will like.
A laser is electromagnetic radiation which never has mass and will only travel at lightspeed. While we have slowed down light, it requires a medium or material to do it\*. So unless that medium or material is inbetween you and your target all the time you are out of luck.
However, what if you change this around? Rather than fire a beam of light, you fire a carrier that holds the light? Say you use a way to stop the light using a metamaterial, and at impact this light is released? It would have the added benefit of being potentially bullet-shaped and capable, but all the lightbeams and pulsed flashes you expect are gone.
\*from @CortAmmon 's comment: <https://en.wikipedia.org/wiki/Slow_light> | If the goal is to be able to watch the beam of light travel like in movies, that's not going to work.
However, one possibility is that pulling the trigger only begins the process of sending the beam - like a camera flash, there's a charge-up followed by a discharge a little bit later. The charge-up can't happen in advance because it leaks away too quickly to be practical, though. |
210,499 | In science-fiction, what are referred to as "laser guns" are usually just plasma weapons that travel slower than the speed of light. But I want to have *actual* laser - not plasma - weapons in my universe, but I don't want them to travel at the speed of light. Is that possible? | 2021/08/20 | [
"https://worldbuilding.stackexchange.com/questions/210499",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88454/"
] | If you mean lasers going slower than $c$, as in the speed of light in a vacuum, then your only choice is shooting them in a medium other than the vacuum of space. Light is slower when travelling through a gas medium such as an atmosphere. However, the difference in speed between a vacuum and an atmosphere such as ours is practically negligible.
You would need a very special medium such as a [Bose-Einstein condensate](https://en.wikipedia.org/wiki/Bose%E2%80%93Einstein_condensate) to really slow down light (its speed falls to 17m/s in such a medium).
Notice that in any case slowing down a laser will not allow you to see it coming.
As an alternative, consider [laser powered rockets](https://en.wikipedia.org/wiki/Laser_propulsion). Basically you shoot a rocket, but instead of the rocket burning fuel in order to accelerate, you push it with lasers. This allows them to go arbitrarily much further and faster, and depending on the power you spend they might hit the target as a red or white hot stream of molten metal that from a distance might look like a laser beam as seen in some videogames. | If the goal is to be able to watch the beam of light travel like in movies, that's not going to work.
However, one possibility is that pulling the trigger only begins the process of sending the beam - like a camera flash, there's a charge-up followed by a discharge a little bit later. The charge-up can't happen in advance because it leaks away too quickly to be practical, though. |
28,101,097 | In Python 3, is there a difference between using these two expressions?
`item not in list`
vs.
`not item in list` | 2015/01/23 | [
"https://Stackoverflow.com/questions/28101097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068700/"
] | The two expressions are equivalent, but the first one is more idiomatic, so it's preferred. | `item not in list` is being mentioned in the Python documentation and `not item in list` is not.
Which means that it is better to use `item not in list`. |
138,325 | Let $S\_n$ be the permutation group on $n$ elements.
Denote by $K(n)$ the largest $k$ s.t. $S\_n$ has a $k$-transitive subgroup (w.r.t. its action on the $n$-element set on which $S\_n$ acts) different from
$S\_n,A\_n$.
I heard that it has been proved that $K(n)\le 7$ for all $n$ but the proof uses
the classification of finite groups (please correct me if I am wrong on this).
But I am also interested in the exact value of $K(n)$ for small $n$ (or even all $n$ if
there is a simple description).
Also I wonder what can be proved in a more elementary way (even weak bounds like $K(n)<n/3$ are interesting). | 2013/08/01 | [
"https://mathoverflow.net/questions/138325",
"https://mathoverflow.net",
"https://mathoverflow.net/users/9304/"
] | Actually $K(n)\le5$, with equality only for $n=12$ and $n=24$ and subgroup the Mathieu group $M\_n$. If $G\le S\_n$ is at least $2$-transitive, then an old theorem of Burnside shows that either $G$ has a regular elementary abelian normal subgroup, or $G$ has a simple non-abelian normal subgroup.
In the former case, it is an easy exercise to see that $G$ is at most $3$-transitive,
To treat the latter case indeed requires the classification of the finite simple groups. There isn't even any bound $c$ with $K(n)\le c$ available without the classification.
A nice overview is in [Peter Cameron's article](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.122.1628). | Wielandt was able to obtain an upper bound on $K(n)$ which grows logarithmically. He did this in (umlauts suppressed, and I hope I otherwise didn't screw this up)
Wielandt, H.:
Abschatzungen fur den Grad einer Permutationsgruppe yon vorgeschriebenem Transitivitatsgrad. Dissertation, Berlin 1934. Schriften des Math. Seminars und des Instituts fur angew. Math. der Universitat Berlin 2, 151-174 (1934)
If you don't need asymptotic results, but only results which apply to small values of $n$, recall Jordan's theorem which says if $p$ is a prime, a primitive permutation group on $p+3$ or more points containing a $p$-cycle will contain the whole $A\_{n}$. Then supplement that with information on gaps in the primes (for example, from A002386 in the OEIS) and you could be off to a good start.
To the extent you don't mind the analytic number theory needed to obtain effective upper bounds on ratios of consecutive primes, this method can give you bounds better than $K(n) < n/3$ for large enough $n$. |
58,936,088 | Suppose I have an external table like this:
```
CREATE EXTERNAL TABLE my.data (
`id` string,
`timestamp` string,
`profile` struct<
`name`: string,
`score`: int>
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
'serialization.format' = '1',
'ignore.malformed.json' = 'true'
)
LOCATION 's3://my-bucket-of-data'
TBLPROPERTIES ('has_encrypted_data'='false');
```
A few of my documents have an invalid `profile.score` (a string rather than an integer).
This causes queries in Athena to fail:
>
> "Status": {
> "State": "FAILED",
> "StateChangeReason": "HIVE\_BAD\_DATA: Error parsing field value for field 0: For input string: \"4099999.9999999995\"",
>
>
>
How can I configure Athena to skip the documents that do not fit the external table schema?
---
The question [here](https://stackoverflow.com/questions/58919242/how-do-i-identify-problematic-documents-in-s3-when-querying-data-in-athena?noredirect=1#comment104121366_58919242) is about finding the problematic documents; this question is about skipping them. | 2019/11/19 | [
"https://Stackoverflow.com/questions/58936088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256041/"
] | Here is a sample on how to exclude a particular file
```sql
SELECT
*
FROM
"some_database"."some_table"
WHERE(
"$PATH" != 's3://path/to/a/file'
)
```
Just tested this approach with
```sql
SELECT
COUNT(*)
FROM
"some_database"."some_table"
-- Result: 68491573
SELECT
COUNT(*)
FROM
"some_database"."some_table"
WHERE(
"$PATH" != 's3://path/to/a/file'
)
-- Result: 68041452
SELECT
COUNT(*)
FROM
"some_database"."some_table"
WHERE(
"$PATH" = 's3://path/to/a/file'
)
-- Result: 450121
```
Total: 450121 + 68041452 = 68491573 | I have faced same issue. Since I could not found a specific solution, I have used a different approach. It might help you.
The error is related to bad data in profile field. Since you are using “struct” for profile field, Athena is expecting the profile field’s data in structured fashion in source files. If there is any bad data in this field, you will experience this error.
Can you try below queries:
```
CREATE EXTERNAL TABLE my.data (
id string,
timestamp string,
profile string
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
'serialization.format' = '1',
'ignore.malformed.json' = 'true'
)
LOCATION 's3://my-bucket-of-data'
TBLPROPERTIES ('has_encrypted_data'='false');
```
and use below query to get expected result
```
select
id
,timestamp
,socialdata
,json_extract_scalar(profile, '$.name')profile_name
,json_extract_scalar(profile, '$.score')profile_score
from my.data;
```
You can visit this [link](https://www.spheregen.com/hive_bad_data-error-parsing-field-value-for-field-error-in-aws-athena/) for more. |
4,303 | I recently moved away from NYC to the suburbs. In NYC, I always locked up my bike with the New York Lock, which is a super heavy duty U-Lock. With a plethora of signs and parking meters, NYC works amazingly well for a U-Lock. Now however, the security is overkill and also there's very few signs and no parking meters in the suburbs. I find that I spend at least 10 minutes when I get places trying to identify a U-Lock compatible location to lock up.
I'm looking for a bike lock that isn't a U-Lock but is still fairly secure. I might not need such high security still, but you know the old saying... (You can take a man out of the city but you can't take the city out of a man.)
My one requirement is that whatever chain/cable lock I end up with needs to have a mount for the bike. I don't want to be carrying this or draping it on the bicycle.
I've found tons of cheap, really insecure locks with mounts. I can't find anything that's both secure and mountable.
Cost is no obstacle here. A bike theft would cost much, much more. | 2011/06/17 | [
"https://bicycles.stackexchange.com/questions/4303",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1666/"
] | Any specific lock recommendation is going to be out of date in a year, so I'll focus on identifying the best kind of lock:
Any cable locks are going to be insecure by nature, but it's unfortunately the only other kind of lock available just now. (I'm not counting big-ass chains with giant locks; those are more for show than for security.)
One of the heavier Kryptonite cable locks is probably your best bet. To beef up the security, I'd get two of them and lock up different parts of the bike. I'm told that keyed locks are harder to crack than combination locks.
However, have you considered getting a smaller U-lock and a long cable? You'd get the best of both worlds that way. Since places to lock up are scarce, you'd usually end up using it as just a cable lock, but it'd give you flexibility in the event you find a good sign or bike rack.
Bike mounts: These tend to fall apart rather quickly. I recommend focusing on a small pag to carry your locks, rather than use a frame mount. There are triangle frame bags and small trunk bags that do the job nicely. However, cable locks have a great advantage over U-locks--you can coil them up and hang them from your handlebars. Unless you have smaller drop bars, it's amazingly convenient. | I just got this one: [http://www.amazon.com/gp/product/B00165S5FK](http://rads.stackoverflow.com/amzn/click/B00165S5FK). I don't know how secure it is yet, since I haven't used it, but it does come with a frame mount. |
4,303 | I recently moved away from NYC to the suburbs. In NYC, I always locked up my bike with the New York Lock, which is a super heavy duty U-Lock. With a plethora of signs and parking meters, NYC works amazingly well for a U-Lock. Now however, the security is overkill and also there's very few signs and no parking meters in the suburbs. I find that I spend at least 10 minutes when I get places trying to identify a U-Lock compatible location to lock up.
I'm looking for a bike lock that isn't a U-Lock but is still fairly secure. I might not need such high security still, but you know the old saying... (You can take a man out of the city but you can't take the city out of a man.)
My one requirement is that whatever chain/cable lock I end up with needs to have a mount for the bike. I don't want to be carrying this or draping it on the bicycle.
I've found tons of cheap, really insecure locks with mounts. I can't find anything that's both secure and mountable.
Cost is no obstacle here. A bike theft would cost much, much more. | 2011/06/17 | [
"https://bicycles.stackexchange.com/questions/4303",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1666/"
] | A couple of months ago, I purchased an OnGuard link-plate lock which claims to be as tough as some u-locks. It mounts easily to the bicycle and has thus far served me well. It feels pretty durable and will go around more potential anchors than a u-lock.
Mine came with a plastic case that attaches to the downtube using velcro straps. It looked kinda cheesy right out of the package, but I must say that I use it every day and it has been just fine.
Here's the manufactuer's description: <http://www.onguardlock.com/?page_id=329> | I just got this one: [http://www.amazon.com/gp/product/B00165S5FK](http://rads.stackoverflow.com/amzn/click/B00165S5FK). I don't know how secure it is yet, since I haven't used it, but it does come with a frame mount. |
4,303 | I recently moved away from NYC to the suburbs. In NYC, I always locked up my bike with the New York Lock, which is a super heavy duty U-Lock. With a plethora of signs and parking meters, NYC works amazingly well for a U-Lock. Now however, the security is overkill and also there's very few signs and no parking meters in the suburbs. I find that I spend at least 10 minutes when I get places trying to identify a U-Lock compatible location to lock up.
I'm looking for a bike lock that isn't a U-Lock but is still fairly secure. I might not need such high security still, but you know the old saying... (You can take a man out of the city but you can't take the city out of a man.)
My one requirement is that whatever chain/cable lock I end up with needs to have a mount for the bike. I don't want to be carrying this or draping it on the bicycle.
I've found tons of cheap, really insecure locks with mounts. I can't find anything that's both secure and mountable.
Cost is no obstacle here. A bike theft would cost much, much more. | 2011/06/17 | [
"https://bicycles.stackexchange.com/questions/4303",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1666/"
] | You should check out the ABUS extreme editions of their folding bike lock:

See how it packs away:

They also do a twinset version so that you can have two rings of steel around both of your wheels and working off a common key.
I don't own one myself but I know people that do own them. I think that something in the ABUS 'Bordo' range will be perfect for you being able to put your mind at rest when off-bike, yet easy to carry when on-bike. | I just got this one: [http://www.amazon.com/gp/product/B00165S5FK](http://rads.stackoverflow.com/amzn/click/B00165S5FK). I don't know how secure it is yet, since I haven't used it, but it does come with a frame mount. |
1,759,677 | The goal of the assignment that I'm currently working on for my Data Structures class is to create a of Quantum Tic Tac Toe with an AI that plays to win.
Currently, I'm having a bit of trouble finding the most efficient way to represent states.
Overview of current Structure:
**AbstractGame**
* Has and manages AbstractPlayers (game.nextPlayer() returns next player by int ID)
* Has and intializes AbstractBoard at the beginning of the game
* Has a GameTree (Complete if called in initialization, incomplete otherwise)
**AbstractBoard**
* Has a State, a Dimension, and a Parent Game
* Is a mediator between Player and State, (Translates States from collections of rows to a Point representation
* Is a StateConsumer
**AbstractPlayer**
* Is a State Producer
* Has a ConcreteEvaluationStrategy to evaluate the current board
**StateTransveralPool**
* Precomputes possible transversals of "3-states".
* Stores them in a HashMap, where the Set contains nextStates for a given "3-state"
**State**
* Contains 3 Sets -- a Set of X-Moves, O-Moves, and the Board
* Each Integer in the set is a Row. These Integer values can be used to get the next row-state from the StateTransversalPool
**SO, the principle is**
Each row can be represented by the binary numbers 000-111, where 0 implies an open space and 1 implies a closed space.
So, for an incomplete TTT board:
```
From the Set<Integer> board perspective:
X_X R1 might be: 101
OO_ R2 might be: 110
X_X R3 might be: 101, where 1 is an open space, and 0 is a closed space
From the Set<Integer> xMoves perspective:
X_X R1 might be: 101
OO_ R2 might be: 000
X_X R3 might be: 101, where 1 is an X and 0 is not
From the Set<Integer> oMoves perspective:
X_X R1 might be: 000
OO_ R2 might be: 110
X_X R3 might be: 000, where 1 is an O and 0 is not
```
**Then we see that x{R1,R2,R3} & o{R1,R2,R3} => board{R1,R2,R3}**
The problem is quickly generating next states for the GameTree. If I have player Max (x) with board{R1,R2,R3}, then getting the next row-states for R1, R2, and R3 is simple..
```
Set<Integer> R1nextStates = StateTransversalPool.get(R1);
```
The problem is that I have to combine each one of those states with R1 and R2.
Is there a better data structure besides Set that I could use? Is there a more efficient approach in general? I've also found Point<->State mediation cumbersome. Is there another approach that I could try there?
Thanks!
Here is the code for my ConcretePlayer class. It might help explain how players produce new states via moves, using the StateProducer (which might need to become StateFactory or StateBuilder).
```
public class ConcretePlayerGeneric extends AbstractPlayer {
@Override
public BinaryState makeMove() {
// Given a move and the current state, produce a new state
Point playerMove = super.strategy.evaluate(this);
BinaryState currentState = super.getInGame().getBoard().getState();
return StateProducer.getState(this, playerMove, currentState);
}
}
```
EDIT: I'm starting with normal TTT and moving to Quantum TTT. Given the framework, it should be as simple as creating several new Concrete classes and tweaking some things. | 2009/11/18 | [
"https://Stackoverflow.com/questions/1759677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127139/"
] | My suggestion:
* Consider representing individual squares rather than rows, whereby `+1 == O`, `-1 == X` and `0` implies an empty square. **This allows you to detect an end state** by checking whether the sum of a horizontal, vertical or diagonal row equals `+3` or `-3`.
* Secondly "flatten" this 2D 3x3 matrix into a single array whereby elements[0-2] represent the first row, elements[3-5] represent the second row and elements[6-8] represent the third row.
* Use either recursion or an iterative approach to generate subsequent game states given the current state of the board.
**EDIT**
I got bored and so decided to write some "toy code" to implement the game board, including methods to determine if it is in a terminal state and to generate the set of board states after the next move is made. It should generalise to any size board although I haven't tried. Enjoy ...
**Sample Output**
```
$ java Board
Creating board:
---
---
---
Initialising board:
-OX
O--
XO-
Terminal state: false
Generating next move states:
XOX
O--
XO-
-OX
OX-
XO-
-OX
O-X
XO-
-OX
O--
XOX
```
**Code**
```
import java.util.List;
import java.util.LinkedList;
import java.util.Random;
public class Board {
private final int[] squares;
public Board() {
this.squares = new int[9];
}
protected Board(int[] squares) {
this.squares = squares;
}
public void init() {
Random rnd = new Random();
int turn = 1; // 'O' always goes first.
for (int i=0; i<squares.length; ++i) {
double d = rnd.nextDouble();
if (d < 0.75) {
squares[i] = turn;
turn = turn == 1 ? -1 : 1; // Flip to other player's turn.
} else {
squares[i] = 0; // Empty square.
}
if (isTerminalState()) {
break;
}
}
}
public boolean isTerminalState() {
boolean ret = false;
boolean foundEmpty = false;
int hSum = 0;
int[] vSum = new int[3];
for (int i=0; i<squares.length; ++i) {
hSum += squares[i];
if (isWinningRow(hSum)) {
ret = true;
break;
} else if (i == 2 || i == 5) {
hSum = 0;
}
int col = i % 3;
vSum[col] += squares[i];
if (isWinningRow(vSum[col])) {
ret = true;
break;
}
if (squares[i] == 0) {
foundEmpty = true;
}
}
if (!ret) {
if (!foundEmpty) {
ret = true;
} else {
int diag1 = 0;
int diag2 = 0;
int rowSz = (int)Math.sqrt(squares.length);
for (int i=0; i<squares.length; ++i) {
if (i % (rowSz + 1) == 0) {
diag1 += squares[i];
if (isWinningRow(diag1)) {
ret = true;
break;
}
}
if (i > 0 && i % (rowSz - 1) == 0) {
diag2 += squares[i];
if (isWinningRow(diag2)) {
ret = true;
break;
}
}
}
}
}
return ret;
}
private boolean isWinningRow(int rowSum) {
return rowSum == 3 || rowSum == -3;
}
public List<Board> getNextStates() {
List<Board> ret = new LinkedList<Board>();
int tmp = 0;
for (int i=0; i<squares.length; ++i) {
tmp += squares[i];
}
// Next turn is 'O' (i.e. +1) if the board sums to 0.
// Otherwise it's 'X's turn.
int turn = tmp == 0 ? 1 : -1;
if (!isTerminalState()) {
for (int i=0; i<squares.length; ++i) {
if (squares[i] == 0) { // Empty square
int[] squaresA = new int[squares.length];
System.arraycopy(squares, 0, squaresA, 0, squares.length);
squaresA[i] = turn;
ret.add(new Board(squaresA));
}
}
}
return ret;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<squares.length; ++i) {
if (squares[i] == 1) {
sb.append('O');
} else if (squares[i] == -1) {
sb.append('X');
} else {
assert squares[i] == 0;
sb.append('-');
}
if (i == 2 || i == 5) {
sb.append('\n');
}
}
return sb.toString();
}
public static void main(String[] args) {
System.err.println("Creating board:\n");
Board bd = new Board();
System.err.println(bd);
System.err.println("\nInitialising board:\n");
bd.init();
System.err.println(bd);
System.err.println("Terminal state: " + bd.isTerminalState() + '\n');
System.err.println("\nGenerating next move states:\n");
List<Board> nextStates = bd.getNextStates();
for (Board bd1 : nextStates) {
System.err.println(bd1.toString() + '\n');
}
}
}
``` | Shouldn't each square have only three possible states (, X, O)?
Either store a grid of 3-state squares, or store 2 lists of moves. You don't need to store the overall board because it is defined by the moves.
Also, what do you mean by:
>
> generating next states for the
> GameTree
>
>
>
What is a GameTree? and what are some examples of "next states"? |
209,026 | If I open a large .JPG file in Preview I will see a big blank green screen...
[](https://i.stack.imgur.com/XLm8J.jpg)
I tried to delete the user's cache, some files from the preferences, but nothing helped me... | 2015/10/04 | [
"https://apple.stackexchange.com/questions/209026",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/150285/"
] | Go to `Preview > Preferences > Images` and select `Size on screen equals size on printout`.
[](https://i.stack.imgur.com/syO98.jpg)
Found this information at this [link](https://discussions.apple.com/thread/7252316) @ the Apple Discussions site. It seems to have helped other users with the same problem. I've never experienced it myself. Now I know what to do if it does happen! | After set to **Size on screen equals size on printout** I had to scale my resolution to 1440 x 900 or 1680 x 1050 to make it work.
Steps: Go to System Preferences -> Displays -> select Scaled -> select one of 2 More Spaces on the right hand side of Default scale |
209,026 | If I open a large .JPG file in Preview I will see a big blank green screen...
[](https://i.stack.imgur.com/XLm8J.jpg)
I tried to delete the user's cache, some files from the preferences, but nothing helped me... | 2015/10/04 | [
"https://apple.stackexchange.com/questions/209026",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/150285/"
] | Go to `Preview > Preferences > Images` and select `Size on screen equals size on printout`.
[](https://i.stack.imgur.com/syO98.jpg)
Found this information at this [link](https://discussions.apple.com/thread/7252316) @ the Apple Discussions site. It seems to have helped other users with the same problem. I've never experienced it myself. Now I know what to do if it does happen! | Update to OS X El Capitan v10.11.1.
```
Resolves an issue that caused JPEG images to appear as a gray or green box in Preview.
```
<https://support.apple.com/en-hk/HT205360> |
5,730 | No encuentro una regla para justificar la sospecha de que *dense* (del verbo *dar*) lleva acento. De acuerdo con las reglas de la acentuación de palabras graves no lo lleva, pero lo he visto un par de veces con acento. Entonces, ¿cómo se escribe?
>
> Dénse un beso
>
>
>
O bien:
>
> Dense un beso
>
>
>
En diccionarios no lo he visto conjugado como lo necesito (y no tendría por qué aparecer ahí de hecho). | 2014/05/20 | [
"https://spanish.stackexchange.com/questions/5730",
"https://spanish.stackexchange.com",
"https://spanish.stackexchange.com/users/768/"
] | Es *dense*.
No lleva acento gráfico actualmente por ser grave terminada en vocal, y tampoco llevaba con las viejas reglas, ya que *den* no lo lleva. En cambio *deles* antes llevaba acento gráfico y ahora no. La entrada *TILDE* del DPD, en la sección *4.3. Formas verbales con pronombres enclíticos* dice lo siguiente:
>
> A diferencia de lo establecido en normas ortográficas anteriores, a partir de la Ortografía académica de 1999 las formas verbales con enclíticos deben acentuarse gráficamente siguiendo las reglas de acentuación; así, formas como estate, suponlo, deles se escriben ahora sin tilde por ser palabras llanas terminadas en vocal o en -s, mientras que déselo, léela, fíjate llevan tilde por ser esdrújulas, y oídme, salíos, reírte, por contener un hiato de vocal cerrada tónica y vocal abierta átona.
>
>
> | Dense es la respuesta correcta.
Pero...
Si estuvieras diciendo que dar algo a alguien, entonces llevaría un accento `dénselo`
Es porque sin el `lo` en el fin de `dense`, esa palabra obedece la regla que dice que el vocal penúltimo siempre lleva el estrés... si que ya no exista un accento en la palabra. |
16,737,502 | Hi for my application i need to remove null byte on a char array evry X bytes like:
```
char a[] = "\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x00\x00"
```
need to be
```
char a[] = "\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8";
```
and i need a function without std just WINAPI Thanks | 2013/05/24 | [
"https://Stackoverflow.com/questions/16737502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417534/"
] | @Jerry Coffin describes the idiomatic solution to this general type of problem.
You'll want to scan and modify the array in-place, scanning from left to right, preserving or deleting elements as you go, while keeping track of the source (input) index and the target (output) index. Since this scans each element of the array once, it's an O(*n*) algorithm.
For example:
```
// Remove all '\x00' elements from an array
int remove_zeros(char a[], int len)
{
int si; // Source index
int di; // Destination index
// Scan the array from left to right, removing '\x00' elements
di = 0;
for (si = 0; si < len; si++)
{
if (a[si] != '\x00')
a[di++] = a[si]; // Keep/move the element
// Otherwise skip/remove the element
}
return di; // Resulting length of the modified array
}
```
The `di` index is guaranteed to be no greater than `si` as the loop progresses. The `if` condition can be modified to whatever condition you need for preserving elements within the array.
Note: To be completely pedantic, the indices and length should be type `size_t`, so that arrays of any size can be processed. I used `int` just to keep things simple. | One obvious way would be to walk through the array from beginning to end, keeping track of two points: a "input" and an "output". The two will start out the same (the beginning of the array), but every time you encounter a byte you don't want in the result, you'll move the input to the next byte, but leave the output alone. When you encounter a byte you do want to keep, you'll copy from the input point to the output point, then update both of them to point to the next byte. |
44,369,831 | I have a container div ***(that cannot be floated)*** with two children elements. I want child elements to be on opposite sides - first on left, second on right. On 100% browser width children summary width is less than container, but on greater scales it is not, so container should be greater too. How to set container to grow when it's gloat child grow?
[![[1]: https://i.stack.imgur.c](https://i.stack.imgur.com/spPER.png)](https://i.stack.imgur.com/spPER.png)
**UPD:** something like [this](https://jsfiddle.net/st4ooc0b/)
I need all elements to stay one line in any scale.
```
<div id="page">
<div id="container">
<div id="left">
<div>first</div>
<div>second</div>
<div>third</div>
</div>
<div id="right">
right
</div>
</div>
</div>
<style>
#page {
background-color: grey;
width: 100%;
height: 300px;
}
#container {
/*this styles are needed to other parts*/
position: relative;
clear: both;
/*=====================================*/
background-color:red;
height: 50px;
width: 90%;
margin: 0 5%;
}
#left {
float: left;
background-color: blue;
}
#left div {
width: 50px;
display: inline-block;
}
#right{
float: right;
background-color: green;
display: block;
max-width: 200px;
}
</style>
``` | 2017/06/05 | [
"https://Stackoverflow.com/questions/44369831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3913440/"
] | ```
.container {
display: flex;
justify-content: space-between;
}
```
It should do that.
Google up FlexBox Introduction for good explaination. | something like this ?
I've used `display:flex` to let the two divs line up nicely, floats only needed for the inner boxed
<https://jsfiddle.net/070rk2e1/1/> |
6,775,718 | I'm trying to do the union between two MKCoordinateRegion. Does anybody have an idea on how to do this? | 2011/07/21 | [
"https://Stackoverflow.com/questions/6775718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/790645/"
] | There is a `MKMapRectUnion` function which accepts two `MKMapRects` so you could first convert each `MKCoordinateRegion` to an `MKMapRect` and then call that function (and convert the result back to an `MKCoordinateRegion` using the `MKCoordinateRegionForMapRect` function).
The conversion method might look like this:
```
- (MKMapRect)mapRectForCoordinateRegion:(MKCoordinateRegion)coordinateRegion
{
CLLocationCoordinate2D topLeftCoordinate =
CLLocationCoordinate2DMake(coordinateRegion.center.latitude
+ (coordinateRegion.span.latitudeDelta/2.0),
coordinateRegion.center.longitude
- (coordinateRegion.span.longitudeDelta/2.0));
MKMapPoint topLeftMapPoint = MKMapPointForCoordinate(topLeftCoordinate);
CLLocationCoordinate2D bottomRightCoordinate =
CLLocationCoordinate2DMake(coordinateRegion.center.latitude
- (coordinateRegion.span.latitudeDelta/2.0),
coordinateRegion.center.longitude
+ (coordinateRegion.span.longitudeDelta/2.0));
MKMapPoint bottomRightMapPoint = MKMapPointForCoordinate(bottomRightCoordinate);
MKMapRect mapRect = MKMapRectMake(topLeftMapPoint.x,
topLeftMapPoint.y,
fabs(bottomRightMapPoint.x-topLeftMapPoint.x),
fabs(bottomRightMapPoint.y-topLeftMapPoint.y));
return mapRect;
}
```
Then, to actually do the union:
```
MKCoordinateRegion region1 = ...
MKCoordinateRegion region2 = ...
MKMapRect mapRect1 = [self mapRectForCoordinateRegion:region1];
MKMapRect mapRect2 = [self mapRectForCoordinateRegion:region2];
MKMapRect mapRectUnion = MKMapRectUnion(mapRect1, mapRect2);
MKCoordinateRegion regionUnion = MKCoordinateRegionForMapRect(mapRectUnion);
``` | i did a little test on both 4.3 and 5.0 and it seems that the conversion is not correct
```
UIImageView *imageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"heart.png"] imageByScalingProportionallyToSize:CGSizeMake(100, 100)]];
imageView.frame = CGRectMake(0, 0, 100, 100);
imageView.center = [mapView convertCoordinate:mapView.centerCoordinate toPointToView:canvasView];
[canvasView addSubview:imageView];
MKCoordinateRegion region = [mapView convertRect:imageView.frame toRegionFromView:canvasView];
MKMapRect maprect;
for (int i = 0; i < 5; i ++)
{
maprect = [mapView mapRectForCoordinateRegion:region];
NSLog(@"%f, %f, %f, %f", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta);
NSLog(@"%f, %f, %f, %f", maprect.origin.x, maprect.origin.y, maprect.size.width, maprect.size.height);
region = MKCoordinateRegionForMapRect([mapView mapRectForCoordinateRegion:region]);
}
```
14.718256, -40.078125, 63.837150, 70.312500
78118912.000000, 94811514.406252, 52428800.000000, 52428799.999997
17.416993, -40.078125, 63.837150, 70.312500
78118912.000000, 91803983.982924, 52428800.000000, 53344239.567355
20.649080, -40.078125, 63.837150, 70.312500
78118912.000000, 87976363.978412, 52428800.000000, 54699220.734715
24.548345, -40.078125, 63.837150, 70.312500
78118912.000000, 82962597.189840, 52428800.000000, 56765991.576236
29.305644, -40.078125, 63.837150, 70.312500
78118912.000000, 76093086.024249, 52428800.000000, 60073659.997575 |
6,775,718 | I'm trying to do the union between two MKCoordinateRegion. Does anybody have an idea on how to do this? | 2011/07/21 | [
"https://Stackoverflow.com/questions/6775718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/790645/"
] | There is a `MKMapRectUnion` function which accepts two `MKMapRects` so you could first convert each `MKCoordinateRegion` to an `MKMapRect` and then call that function (and convert the result back to an `MKCoordinateRegion` using the `MKCoordinateRegionForMapRect` function).
The conversion method might look like this:
```
- (MKMapRect)mapRectForCoordinateRegion:(MKCoordinateRegion)coordinateRegion
{
CLLocationCoordinate2D topLeftCoordinate =
CLLocationCoordinate2DMake(coordinateRegion.center.latitude
+ (coordinateRegion.span.latitudeDelta/2.0),
coordinateRegion.center.longitude
- (coordinateRegion.span.longitudeDelta/2.0));
MKMapPoint topLeftMapPoint = MKMapPointForCoordinate(topLeftCoordinate);
CLLocationCoordinate2D bottomRightCoordinate =
CLLocationCoordinate2DMake(coordinateRegion.center.latitude
- (coordinateRegion.span.latitudeDelta/2.0),
coordinateRegion.center.longitude
+ (coordinateRegion.span.longitudeDelta/2.0));
MKMapPoint bottomRightMapPoint = MKMapPointForCoordinate(bottomRightCoordinate);
MKMapRect mapRect = MKMapRectMake(topLeftMapPoint.x,
topLeftMapPoint.y,
fabs(bottomRightMapPoint.x-topLeftMapPoint.x),
fabs(bottomRightMapPoint.y-topLeftMapPoint.y));
return mapRect;
}
```
Then, to actually do the union:
```
MKCoordinateRegion region1 = ...
MKCoordinateRegion region2 = ...
MKMapRect mapRect1 = [self mapRectForCoordinateRegion:region1];
MKMapRect mapRect2 = [self mapRectForCoordinateRegion:region2];
MKMapRect mapRectUnion = MKMapRectUnion(mapRect1, mapRect2);
MKCoordinateRegion regionUnion = MKCoordinateRegionForMapRect(mapRectUnion);
``` | If anyone is looking for a swift equivalent using extensions,
```
extension MKCoordinateRegion {
func mapRectForCoordinateRegion() -> MKMapRect {
let dLat = span.latitudeDelta / 2.0
let dLon = span.longitudeDelta / 2.0
let topLeft = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(center.latitude + dLat, center.longitude - dLon))
let botRight = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(center.latitude - dLat, center.longitude + dLon))
return MKMapRectMake(
topLeft.x,
topLeft.y,
fabs(botRight.x - topLeft.x),
fabs(botRight.y - topLeft.y))
}
func unionWith(region: MKCoordinateRegion) -> MKCoordinateRegion {
let union = MKMapRectUnion(
self.mapRectForCoordinateRegion(),
region.mapRectForCoordinateRegion())
return MKCoordinateRegionForMapRect(union)
}
}
```
And can be used like
```
let region1 = ...
let region2 = ...
let regionUnion = region1.unionWith(region2)
``` |
6,775,718 | I'm trying to do the union between two MKCoordinateRegion. Does anybody have an idea on how to do this? | 2011/07/21 | [
"https://Stackoverflow.com/questions/6775718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/790645/"
] | If anyone is looking for a swift equivalent using extensions,
```
extension MKCoordinateRegion {
func mapRectForCoordinateRegion() -> MKMapRect {
let dLat = span.latitudeDelta / 2.0
let dLon = span.longitudeDelta / 2.0
let topLeft = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(center.latitude + dLat, center.longitude - dLon))
let botRight = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(center.latitude - dLat, center.longitude + dLon))
return MKMapRectMake(
topLeft.x,
topLeft.y,
fabs(botRight.x - topLeft.x),
fabs(botRight.y - topLeft.y))
}
func unionWith(region: MKCoordinateRegion) -> MKCoordinateRegion {
let union = MKMapRectUnion(
self.mapRectForCoordinateRegion(),
region.mapRectForCoordinateRegion())
return MKCoordinateRegionForMapRect(union)
}
}
```
And can be used like
```
let region1 = ...
let region2 = ...
let regionUnion = region1.unionWith(region2)
``` | i did a little test on both 4.3 and 5.0 and it seems that the conversion is not correct
```
UIImageView *imageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"heart.png"] imageByScalingProportionallyToSize:CGSizeMake(100, 100)]];
imageView.frame = CGRectMake(0, 0, 100, 100);
imageView.center = [mapView convertCoordinate:mapView.centerCoordinate toPointToView:canvasView];
[canvasView addSubview:imageView];
MKCoordinateRegion region = [mapView convertRect:imageView.frame toRegionFromView:canvasView];
MKMapRect maprect;
for (int i = 0; i < 5; i ++)
{
maprect = [mapView mapRectForCoordinateRegion:region];
NSLog(@"%f, %f, %f, %f", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta);
NSLog(@"%f, %f, %f, %f", maprect.origin.x, maprect.origin.y, maprect.size.width, maprect.size.height);
region = MKCoordinateRegionForMapRect([mapView mapRectForCoordinateRegion:region]);
}
```
14.718256, -40.078125, 63.837150, 70.312500
78118912.000000, 94811514.406252, 52428800.000000, 52428799.999997
17.416993, -40.078125, 63.837150, 70.312500
78118912.000000, 91803983.982924, 52428800.000000, 53344239.567355
20.649080, -40.078125, 63.837150, 70.312500
78118912.000000, 87976363.978412, 52428800.000000, 54699220.734715
24.548345, -40.078125, 63.837150, 70.312500
78118912.000000, 82962597.189840, 52428800.000000, 56765991.576236
29.305644, -40.078125, 63.837150, 70.312500
78118912.000000, 76093086.024249, 52428800.000000, 60073659.997575 |
36,511,745 | What does `this` refer to inside an AngularJS provider?
>
> And the value it is assigned is based exclusively on the object that
> invokes the this Function.
> Source: <http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/>
>
>
>
Based on above I think `this` references the object which invokes the function that `this` is inside.
**So in below example example...**
```
sth.provider('Cat', function CatProvider() {
var resourceName = 'user';
this.resourceName = function(value) {
if (value === undefined) {
return resourceName;
}
resourceName = value;
return this;
};
this.$get = function($q, $http, $rootScope) {
...
}
}
```
**...does `this` refer to `sth` or to `.provider`?**
I'm a little confused. | 2016/04/09 | [
"https://Stackoverflow.com/questions/36511745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909076/"
] | It refers to the `CatProvider` function. If you check the AngularJS Documentation for **[`angular.Module.provider()`](https://docs.angularjs.org/api/auto/service/$provide#provider)**, then you'll see this description:
>
> Register a provider function with the $injector. **Provider functions
> are constructor functions, whose instances** are responsible for
> "providing" a factory for a service.
>
>
>
Since provider functions are **constructors**, then that only suggests that the function itself is instantiated and thus, **`this`**, refers to the instance of the instantiated `CatProvider` function. | In EcmaScript 5, which you are using, this refers to the function it is used within ...
```
function Jim() {
// this is the Jim function
var self = this;
function Fred() {
// this is the Fred function
this.name='fred'; // I have added a name property to the Fred function
// I can access Jim here by referencing self
self.name='jim'; // I have added a name property to the Jim function
}
}
```
this is how we do it in EcmaScript 5.
In EcmaScript 6 it is all changed and the above no longer applies. You will meet EcmaScript 6 in a browser near you very soon :) |
8,713,090 | I'm trying to center the names(#box2) and the topic(#box1) on top of an image.
```
<?php require_once('seminar_config.php'); ?>
<a href="print.certificate.php">Print</a>
<body>
<?php
$participants = $db->get_results("SELECT participant FROM tbl_participants WHERE state=1");
$topics = $db->get_results("SELECT topic FROM tbl_topics");
if(!empty($participants)){
?>
<?php ob_start(); ?>
<div id="container">
<img src="certificate.jpg"/>
<?php foreach($topics as $a=>$b){ ?>
<?php foreach($participants as $k=>$v){ ?>
<img src="certificate.jpg"/>
<div id="box1" class="common"><?php echo $b->topic; ?></div>
<div id="box2" class="common"><?php echo $v->participant; ?></div>
<?php } ?>
<?php } ?>
</div>
<?php $_SESSION['certificates'] = ob_get_contents(); ?>
<?php ob_flush(); ?>
<?php } ?>
</body>
```
And here's the script that creates the pdf:
```
<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML('<style>
#box1{
margin-top: 350px;
}
#box2{
margin-top: 200px;
}
.common{
height: 20px;
left: 630px;
right: 630px;
text-align: center;
position: absolute;
left: 0;
top: 0;
font-size:20px;
}
</style>'.
$_SESSION['certificates']);
$html2pdf->Output('random.pdf');
?>
```
I have no problem with the center positioning of the names and topic if I'm not using html2pdf to generate pdf files.
But if I use html2pdf everything is ruined. Please help me center things in css when using html2pdf. | 2012/01/03 | [
"https://Stackoverflow.com/questions/8713090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225269/"
] | Most common HTML-to-PDF programs either don't understand CSS, or understand CSS poorly. If your HTML is working, but doesn't translate well to PDF using html2pdf, you might give wkhtmltopdf a shot <https://github.com/antialize/wkhtmltopdf> | Try using tables and inline css styles
```
<table align="left" width="100%" style="page-break-after:always; margin-top:25px; margin-left:25px; font-family:tahoma; font-size:20px; ">
<tr><td>Your info</td></tr>
</table>
``` |
8,713,090 | I'm trying to center the names(#box2) and the topic(#box1) on top of an image.
```
<?php require_once('seminar_config.php'); ?>
<a href="print.certificate.php">Print</a>
<body>
<?php
$participants = $db->get_results("SELECT participant FROM tbl_participants WHERE state=1");
$topics = $db->get_results("SELECT topic FROM tbl_topics");
if(!empty($participants)){
?>
<?php ob_start(); ?>
<div id="container">
<img src="certificate.jpg"/>
<?php foreach($topics as $a=>$b){ ?>
<?php foreach($participants as $k=>$v){ ?>
<img src="certificate.jpg"/>
<div id="box1" class="common"><?php echo $b->topic; ?></div>
<div id="box2" class="common"><?php echo $v->participant; ?></div>
<?php } ?>
<?php } ?>
</div>
<?php $_SESSION['certificates'] = ob_get_contents(); ?>
<?php ob_flush(); ?>
<?php } ?>
</body>
```
And here's the script that creates the pdf:
```
<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML('<style>
#box1{
margin-top: 350px;
}
#box2{
margin-top: 200px;
}
.common{
height: 20px;
left: 630px;
right: 630px;
text-align: center;
position: absolute;
left: 0;
top: 0;
font-size:20px;
}
</style>'.
$_SESSION['certificates']);
$html2pdf->Output('random.pdf');
?>
```
I have no problem with the center positioning of the names and topic if I'm not using html2pdf to generate pdf files.
But if I use html2pdf everything is ruined. Please help me center things in css when using html2pdf. | 2012/01/03 | [
"https://Stackoverflow.com/questions/8713090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225269/"
] | If you want to center .common try following:
```
.common{
position: absolute;
left: 50%;
top: 0;
font-size:20px;
width:600px;
margin-left:-300px;
}
``` | Try using tables and inline css styles
```
<table align="left" width="100%" style="page-break-after:always; margin-top:25px; margin-left:25px; font-family:tahoma; font-size:20px; ">
<tr><td>Your info</td></tr>
</table>
``` |
8,713,090 | I'm trying to center the names(#box2) and the topic(#box1) on top of an image.
```
<?php require_once('seminar_config.php'); ?>
<a href="print.certificate.php">Print</a>
<body>
<?php
$participants = $db->get_results("SELECT participant FROM tbl_participants WHERE state=1");
$topics = $db->get_results("SELECT topic FROM tbl_topics");
if(!empty($participants)){
?>
<?php ob_start(); ?>
<div id="container">
<img src="certificate.jpg"/>
<?php foreach($topics as $a=>$b){ ?>
<?php foreach($participants as $k=>$v){ ?>
<img src="certificate.jpg"/>
<div id="box1" class="common"><?php echo $b->topic; ?></div>
<div id="box2" class="common"><?php echo $v->participant; ?></div>
<?php } ?>
<?php } ?>
</div>
<?php $_SESSION['certificates'] = ob_get_contents(); ?>
<?php ob_flush(); ?>
<?php } ?>
</body>
```
And here's the script that creates the pdf:
```
<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML('<style>
#box1{
margin-top: 350px;
}
#box2{
margin-top: 200px;
}
.common{
height: 20px;
left: 630px;
right: 630px;
text-align: center;
position: absolute;
left: 0;
top: 0;
font-size:20px;
}
</style>'.
$_SESSION['certificates']);
$html2pdf->Output('random.pdf');
?>
```
I have no problem with the center positioning of the names and topic if I'm not using html2pdf to generate pdf files.
But if I use html2pdf everything is ruined. Please help me center things in css when using html2pdf. | 2012/01/03 | [
"https://Stackoverflow.com/questions/8713090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225269/"
] | Here is what I use to position divs in center.
Say you want to position div with id=test
CSS
```
#test {
width: 500px;
margin: 0 auto; //auto margin to left and right
}
``` | Try using tables and inline css styles
```
<table align="left" width="100%" style="page-break-after:always; margin-top:25px; margin-left:25px; font-family:tahoma; font-size:20px; ">
<tr><td>Your info</td></tr>
</table>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.