qid
int64 1
74.7M
| question
stringlengths 17
39.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
41.1k
| response_k
stringlengths 2
47.9k
|
---|---|---|---|---|---|
19,364,739 | For some reason I am not able to make my Genymotion player to scale to actual display.
I have look d at the post [can I scale genymotion emulator to “device real size”?](https://stackoverflow.com/questions/18046482/can-i-scale-genymotion-emulator-to-device-real-size?rq=1) and it was not much of a help to me because I am already using the player. All I can do right now is re-size the window, but that does not give me an accurate display size. I am on a windows 7 if it matters.Any other suggestion? | 2013/10/14 | [
"https://Stackoverflow.com/questions/19364739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1878558/"
] | You're almost there, but note you can only reference columns from tables in the `FROM` clause in your `WHERE` clause.
So you'd probably want to do something like this:
```
SELECT *
FROM T2
WHERE T2.id NOT IN
(SELECT T1.t2_id FROM T1)
``` | >
> I want to get all T2 records that aren't linked in T1, how can I do that?
>
>
>
The ones in `T1` are
```
SELECT T1.t2_id FROM T1
```
and the link to `T2` is, of course, done via `T2.id`, so
```
SELECT * FROM T2
WHERE T2.id NOT IN
(SELECT T1.t2_id FROM T1)
```
seems to be what you want.
If you have a close look, SQL is nearly like everyday's language. Nearly. |
19,364,739 | For some reason I am not able to make my Genymotion player to scale to actual display.
I have look d at the post [can I scale genymotion emulator to “device real size”?](https://stackoverflow.com/questions/18046482/can-i-scale-genymotion-emulator-to-device-real-size?rq=1) and it was not much of a help to me because I am already using the player. All I can do right now is re-size the window, but that does not give me an accurate display size. I am on a windows 7 if it matters.Any other suggestion? | 2013/10/14 | [
"https://Stackoverflow.com/questions/19364739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1878558/"
] | You have it backwards:
```
SELECT *
FROM T2
WHERE id NOT IN (SELECT t2_id FROM T1)
```
This can also be written as an outer join, and MySQL tends to perform better this way:
```
SELECT T2.*
FROM T2
LEFT JOIN T1 ON T1.t2_id = T2.id
WHERE T1.id IS NULL
```
Make sure you have an index on T1.t2\_id for this to perform well. | >
> I want to get all T2 records that aren't linked in T1, how can I do that?
>
>
>
The ones in `T1` are
```
SELECT T1.t2_id FROM T1
```
and the link to `T2` is, of course, done via `T2.id`, so
```
SELECT * FROM T2
WHERE T2.id NOT IN
(SELECT T1.t2_id FROM T1)
```
seems to be what you want.
If you have a close look, SQL is nearly like everyday's language. Nearly. |
19,364,739 | For some reason I am not able to make my Genymotion player to scale to actual display.
I have look d at the post [can I scale genymotion emulator to “device real size”?](https://stackoverflow.com/questions/18046482/can-i-scale-genymotion-emulator-to-device-real-size?rq=1) and it was not much of a help to me because I am already using the player. All I can do right now is re-size the window, but that does not give me an accurate display size. I am on a windows 7 if it matters.Any other suggestion? | 2013/10/14 | [
"https://Stackoverflow.com/questions/19364739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1878558/"
] | You have it backwards:
```
SELECT *
FROM T2
WHERE id NOT IN (SELECT t2_id FROM T1)
```
This can also be written as an outer join, and MySQL tends to perform better this way:
```
SELECT T2.*
FROM T2
LEFT JOIN T1 ON T1.t2_id = T2.id
WHERE T1.id IS NULL
```
Make sure you have an index on T1.t2\_id for this to perform well. | You're almost there, but note you can only reference columns from tables in the `FROM` clause in your `WHERE` clause.
So you'd probably want to do something like this:
```
SELECT *
FROM T2
WHERE T2.id NOT IN
(SELECT T1.t2_id FROM T1)
``` |
48,350,288 | Due to lack of knowledge in MYSQL language I cannot create a query to obtain what is required.
I tried several options from stackoverflow and other places but none works.
Elaborating... I need to Select a specific value in a column BUT if that value is not given, I want to select all.
Example (pseudo code)
```
SELECT *
FROM table
WHERE id = 'specificvalue'
IF 'specificvalue' IS NULL, THEN SELECT * FROM table
```
EDIT: dont want to break any rules. I added bellow an image of an example of a table.
I would like to search in FName for 'jack' in specific but if i have no name i want to search all then.
I tried to make a condition with IS NULL but I failed miserably...
I hope someone can help me again!!
[Table example](http://support.sas.com/documentation/cdl/en/sqlproc/63043/HTML/default/images/proc-sql-ex3a.png) | 2018/01/19 | [
"https://Stackoverflow.com/questions/48350288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9123580/"
] | Use a `NOT EXISTS` condition.
```
SELECT *
FROM table
WHERE id = 'specificvalue'
OR NOT EXISTS (
SELECT *
FROM table
WHERE id = 'specificvalue'
)
``` | Assuming ID is unique, ow about using IFNULL:
```
SELECT *
FROM table
WHERE id = IFNULL('specificvalue',id)
```
if your value is null, it looks for all rows where id=id, which is always going to be true, the id will always match itself.
IS NULL should also work:
```
SELECT *
FROM table
WHERE id = 'specificvalue'
OR 'specificvalue' IS NULL
``` |
47,790,563 | I have a rails app that uses postgresql + some extensions, but every time I run `rails db:migrate` it removes the lines that enable the extensions. I have to copy and paste it manually every time.
Lines being removed on db/structure.sql:
```
-- Name: EXTENSION "postgis"; Type: COMMENT; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "postgis" WITH SCHEMA public;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
```
My database.yml:
```
default: &default
adapter: postgis
encoding: unicode
host: <%= ENV.fetch('DB_HOST', 'localhost') %>
username: <%= ENV.fetch('DB_USERNAME') %>
password: <%= ENV.fetch('DB_PASSWORD') %>
schema_search_path: public
test:
<<: *default
database: db_test
development:
<<: *default
database: db_development
production:
<<: *default
database: db_production
```
Any ideas how can I fix it?
I'm using the following versions:
postgresql: 9.6
postgis: 2.3
rails: 5.0
macOS: 10.12
**UPDATE:**
I managed to find a workaround to the problem. As I'm using `schema_search_path` as public, if not defined the default option is public. Just removed this line from database.yml and it works now. Still no clues why it's happening when defining the `schema_search_path` explicitly. | 2017/12/13 | [
"https://Stackoverflow.com/questions/47790563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4621521/"
] | You could generate a migration and use `enable_extension` method:
```
class AddExtensions < ActiveRecord::Migration[5.1]
def change
enable_extension "postgis"
enable_extension "plpgsql"
enable_extension "pg_trgm"
enable_extension "uuid-ossp"
# ...
end
end
``` | You can also move all your extension to another schema like `shared_extension` and controls which database schemas will be dumped by set `config.active_record.dump_schemas = "public"`. |
47,790,563 | I have a rails app that uses postgresql + some extensions, but every time I run `rails db:migrate` it removes the lines that enable the extensions. I have to copy and paste it manually every time.
Lines being removed on db/structure.sql:
```
-- Name: EXTENSION "postgis"; Type: COMMENT; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "postgis" WITH SCHEMA public;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
```
My database.yml:
```
default: &default
adapter: postgis
encoding: unicode
host: <%= ENV.fetch('DB_HOST', 'localhost') %>
username: <%= ENV.fetch('DB_USERNAME') %>
password: <%= ENV.fetch('DB_PASSWORD') %>
schema_search_path: public
test:
<<: *default
database: db_test
development:
<<: *default
database: db_development
production:
<<: *default
database: db_production
```
Any ideas how can I fix it?
I'm using the following versions:
postgresql: 9.6
postgis: 2.3
rails: 5.0
macOS: 10.12
**UPDATE:**
I managed to find a workaround to the problem. As I'm using `schema_search_path` as public, if not defined the default option is public. Just removed this line from database.yml and it works now. Still no clues why it's happening when defining the `schema_search_path` explicitly. | 2017/12/13 | [
"https://Stackoverflow.com/questions/47790563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4621521/"
] | You could generate a migration and use `enable_extension` method:
```
class AddExtensions < ActiveRecord::Migration[5.1]
def change
enable_extension "postgis"
enable_extension "plpgsql"
enable_extension "pg_trgm"
enable_extension "uuid-ossp"
# ...
end
end
``` | After digging thru the code for the schema dumper, I found an option that seems to help.
`ActiveRecord::Base.dump_schemas = :all`
I added this to a config/initializers/schema\_dumper.rb |
47,790,563 | I have a rails app that uses postgresql + some extensions, but every time I run `rails db:migrate` it removes the lines that enable the extensions. I have to copy and paste it manually every time.
Lines being removed on db/structure.sql:
```
-- Name: EXTENSION "postgis"; Type: COMMENT; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "postgis" WITH SCHEMA public;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
```
My database.yml:
```
default: &default
adapter: postgis
encoding: unicode
host: <%= ENV.fetch('DB_HOST', 'localhost') %>
username: <%= ENV.fetch('DB_USERNAME') %>
password: <%= ENV.fetch('DB_PASSWORD') %>
schema_search_path: public
test:
<<: *default
database: db_test
development:
<<: *default
database: db_development
production:
<<: *default
database: db_production
```
Any ideas how can I fix it?
I'm using the following versions:
postgresql: 9.6
postgis: 2.3
rails: 5.0
macOS: 10.12
**UPDATE:**
I managed to find a workaround to the problem. As I'm using `schema_search_path` as public, if not defined the default option is public. Just removed this line from database.yml and it works now. Still no clues why it's happening when defining the `schema_search_path` explicitly. | 2017/12/13 | [
"https://Stackoverflow.com/questions/47790563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4621521/"
] | I experienced a similar issue where the `database.yml` specified multiple schemas for like `schema_search_path: public, third_party`. I found the answer why the `CREATE EXTENSION` statements didn't end up in `structure.sql`.
The reason is explained in <https://github.com/rails/rails/issues/17157> but here is it for reference
>
> If the user has specified a schema\_search\_path and also has
> extensions, the resulting pg\_dump call generated by rake
> db:structure:dump includes the --schema flag which means that no
> CREATE EXTENSION statements will be created in the resulting
> structure.sql. According to the pg\_dump documentation:
>
>
> | You can also move all your extension to another schema like `shared_extension` and controls which database schemas will be dumped by set `config.active_record.dump_schemas = "public"`. |
47,790,563 | I have a rails app that uses postgresql + some extensions, but every time I run `rails db:migrate` it removes the lines that enable the extensions. I have to copy and paste it manually every time.
Lines being removed on db/structure.sql:
```
-- Name: EXTENSION "postgis"; Type: COMMENT; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "postgis" WITH SCHEMA public;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
```
My database.yml:
```
default: &default
adapter: postgis
encoding: unicode
host: <%= ENV.fetch('DB_HOST', 'localhost') %>
username: <%= ENV.fetch('DB_USERNAME') %>
password: <%= ENV.fetch('DB_PASSWORD') %>
schema_search_path: public
test:
<<: *default
database: db_test
development:
<<: *default
database: db_development
production:
<<: *default
database: db_production
```
Any ideas how can I fix it?
I'm using the following versions:
postgresql: 9.6
postgis: 2.3
rails: 5.0
macOS: 10.12
**UPDATE:**
I managed to find a workaround to the problem. As I'm using `schema_search_path` as public, if not defined the default option is public. Just removed this line from database.yml and it works now. Still no clues why it's happening when defining the `schema_search_path` explicitly. | 2017/12/13 | [
"https://Stackoverflow.com/questions/47790563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4621521/"
] | After digging thru the code for the schema dumper, I found an option that seems to help.
`ActiveRecord::Base.dump_schemas = :all`
I added this to a config/initializers/schema\_dumper.rb | You can also move all your extension to another schema like `shared_extension` and controls which database schemas will be dumped by set `config.active_record.dump_schemas = "public"`. |
47,790,563 | I have a rails app that uses postgresql + some extensions, but every time I run `rails db:migrate` it removes the lines that enable the extensions. I have to copy and paste it manually every time.
Lines being removed on db/structure.sql:
```
-- Name: EXTENSION "postgis"; Type: COMMENT; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "postgis" WITH SCHEMA public;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: pg_trgm; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
--
-- Name: EXTENSION pg_trgm; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
```
My database.yml:
```
default: &default
adapter: postgis
encoding: unicode
host: <%= ENV.fetch('DB_HOST', 'localhost') %>
username: <%= ENV.fetch('DB_USERNAME') %>
password: <%= ENV.fetch('DB_PASSWORD') %>
schema_search_path: public
test:
<<: *default
database: db_test
development:
<<: *default
database: db_development
production:
<<: *default
database: db_production
```
Any ideas how can I fix it?
I'm using the following versions:
postgresql: 9.6
postgis: 2.3
rails: 5.0
macOS: 10.12
**UPDATE:**
I managed to find a workaround to the problem. As I'm using `schema_search_path` as public, if not defined the default option is public. Just removed this line from database.yml and it works now. Still no clues why it's happening when defining the `schema_search_path` explicitly. | 2017/12/13 | [
"https://Stackoverflow.com/questions/47790563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4621521/"
] | I experienced a similar issue where the `database.yml` specified multiple schemas for like `schema_search_path: public, third_party`. I found the answer why the `CREATE EXTENSION` statements didn't end up in `structure.sql`.
The reason is explained in <https://github.com/rails/rails/issues/17157> but here is it for reference
>
> If the user has specified a schema\_search\_path and also has
> extensions, the resulting pg\_dump call generated by rake
> db:structure:dump includes the --schema flag which means that no
> CREATE EXTENSION statements will be created in the resulting
> structure.sql. According to the pg\_dump documentation:
>
>
> | After digging thru the code for the schema dumper, I found an option that seems to help.
`ActiveRecord::Base.dump_schemas = :all`
I added this to a config/initializers/schema\_dumper.rb |
4,668,592 | I use a mmap'ed file to share data between processes.
The code is like this:
```
struct Shared
{
int Data;
};
int file = open("file.dat", O_RDWR);
Shared* shared = static_cast<Shared*>(
mmap(0, sizeof(Shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, file, 0));
shared->Data++;
```
The questions are:
1. Should I use volatile qualifier (`volatile int Data`)?
2. Should I use atomic operations on the shared data (`__sync_fetch_and_add(&(shared->Data), 1)`)?
---
For future reference: [Volatile: Almost Useless for Multi-Threaded Programming](http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/). | 2011/01/12 | [
"https://Stackoverflow.com/questions/4668592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23714/"
] | You should not use volatile when changing an integer from more than one thread. Volatile is both not necessary and not sufficient. Atomic operations will do. | There is no guarantee that `volatile` will work correctly across multiple processors, the thing you need to check is whether that intrinsic inserts the appropriate memory barriers during the operation.
Is this some sort of semaphore? if so, you are better off using the platform implementation of such a construct. |
4,668,592 | I use a mmap'ed file to share data between processes.
The code is like this:
```
struct Shared
{
int Data;
};
int file = open("file.dat", O_RDWR);
Shared* shared = static_cast<Shared*>(
mmap(0, sizeof(Shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, file, 0));
shared->Data++;
```
The questions are:
1. Should I use volatile qualifier (`volatile int Data`)?
2. Should I use atomic operations on the shared data (`__sync_fetch_and_add(&(shared->Data), 1)`)?
---
For future reference: [Volatile: Almost Useless for Multi-Threaded Programming](http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/). | 2011/01/12 | [
"https://Stackoverflow.com/questions/4668592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23714/"
] | There is no guarantee that `volatile` will work correctly across multiple processors, the thing you need to check is whether that intrinsic inserts the appropriate memory barriers during the operation.
Is this some sort of semaphore? if so, you are better off using the platform implementation of such a construct. | No need for both volatile and atomic accesses. IPC using mmap works fine without them.
If you need to inform whether something changed, you can use [message queues](http://linux.die.net/man/3/mq_open), but you can also use them instead of mmap (depends how big is the message you want to send. mmap works good is the data is big, but MQ is it is smaller then 200k) |
4,668,592 | I use a mmap'ed file to share data between processes.
The code is like this:
```
struct Shared
{
int Data;
};
int file = open("file.dat", O_RDWR);
Shared* shared = static_cast<Shared*>(
mmap(0, sizeof(Shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, file, 0));
shared->Data++;
```
The questions are:
1. Should I use volatile qualifier (`volatile int Data`)?
2. Should I use atomic operations on the shared data (`__sync_fetch_and_add(&(shared->Data), 1)`)?
---
For future reference: [Volatile: Almost Useless for Multi-Threaded Programming](http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/). | 2011/01/12 | [
"https://Stackoverflow.com/questions/4668592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23714/"
] | You should not use volatile when changing an integer from more than one thread. Volatile is both not necessary and not sufficient. Atomic operations will do. | No need for both volatile and atomic accesses. IPC using mmap works fine without them.
If you need to inform whether something changed, you can use [message queues](http://linux.die.net/man/3/mq_open), but you can also use them instead of mmap (depends how big is the message you want to send. mmap works good is the data is big, but MQ is it is smaller then 200k) |
2,677,730 | I am not so good with regex. I am struggling to find a solution for a small functionality.
I have a ajax response which returns a string like **"Your ticket has been successfully logged. Please follow the link to view details 123432."**
All I have to do is replace that number **123432** with `<a href="blablabla.com?ticket=123432">` using javascript. | 2010/04/20 | [
"https://Stackoverflow.com/questions/2677730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236888/"
] | Try this:
```
fixedString = yourString.replace(/(\d+)/g,
"<a href='blablabla.com?ticket=$1\'>$1</a>");
```
This will give you a new string that looks like this:
>
> `Your ticket has been successfully logged. Please follow the link to view details <a href='blablabla.com?ticket=123432'>123432</a>.`
>
>
> | ```
var str = "Your ticket has been successfully logged. Please follow the link to view details 123432.";
str = str.replace(/\s+(\d+)\.$/g, '<a href="blablabla.com?ticket=$1">$&</a>');
```
this code will output
```
<a href="blablabla.com?ticket=123432">Your ticket has been successfully logged. Please follow the link to view details 123432.</a>
``` |
13,306,640 | I'm looking at a solution that requires us to capture and send the first 12 digits of a customers PAN in order to initiate a transaction that will be finalized by the customer at a later stage with an external payment processor.
A transaction log will be generated with the 12 first digits.
Would this be ok from a PCI-DSS point of view or would it require us to fully comply with PCI-DSS requirements? | 2012/11/09 | [
"https://Stackoverflow.com/questions/13306640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1811823/"
] | In my knowledge PCI-DSS it is pretty clear on two principals:
1. Avoid where ever possible card data at rest (in storage).
2. And if the card number must be displayed at all, as @paulg indicates first 6 and last 4 are acceptable and not more. Which is only 10 digits leaving normally 6 digits unknown. Your 12 leaves only 4 digts unknown. | PCI does allow this in order to allow for customer service computer searches such that the cardholder might be on the phone and ask for the first 8 digits of the credit card number in order to find a given customer or transaction - the PCI people understand that you cannot do an efficient customer/transaction search by decrypting each and every credit card number you have on a system to perform a search for a match. But I think I would regard the fact that you are allowed to store part of the credit card number unencrypted as applying only if you are meeting PCI-DSS requrements in all the other areas covered by PCI-DSS. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | The current, widely accepted model for cosmology is [$\lambda$-CDM](http://en.wikipedia.org/wiki/Lambda-CDM_model). The universe appears (exactly) flat, and for simplicity the universe is infinite. Note that we distinguish between the observable universe (which is the local patch that light could have travelled between since the Big Bang) and the totality — we have constraints that even if the universe is not infinite, its size is many orders of magnitude larger than the observable one.
In the literature (especially the popular science one) the details are very muddled, because the consensus around $\lambda$-CDM model is quite recent — relying heavily on detailed measurements of the cosmological microwave background radiation, largely done by WMAP in the last 8 years or so. In a sense, the lay reader should be exceedingly careful when she reads statements (even from heavy-weight scientists) regarding cosmology — it is (perhaps ironically) a fast moving field. | There is always the problem when answering this question that General Relativity, naively interpreted, allows you to speak about the part of the universe which is not observable from our vantage point, and this makes the question nontrivial.
But in a logical positivist perspective, the one suggest strongly by string-theoretic holography, the universe is exactly the stuff inside the cosmological horizon, and it is finite because the cosmological horizon is of finite area. There is no objective meaning to stuff outside the cosmological horizon, so there is no point in thinking about this--- it is meaningless in the sense of Carnap. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | It's impossible to know whether the universe if finite or infinite because we'll never be able to see it all. Note that genneth says "and for simplicity the universe is infinite", and this is the key point really. It makes Physics simpler if the universe is infinite so we tend to assume it is.
But you need to consider what you mean by "infinite". It doesn't make sense to say the universe has an edge, because you then have to ask what happens if you go up to the edge then take one more step. That means the only alternative to the universe being infinite is that it loops back on itself like a sphere, so you can walk forever without reaching an edge, but eventually you'll be back where you started.
We don't think the universe is like a sphere because for that spacetime would have to have positive curvature, and experiments to date show space is flat (to within experimental error). However spacetime could be positively curved but with such small curvature that we can't detect it. Alternatively spacetime could be flat but have a complex global topology like a torus. The scale of anything like this would have to be larger than the observable univrse otherwise we'd have seen signs of it.
Incidentally, if the universe is infinite now it has always been infinite, even at the Big Bang. This is why you'll often hear it said that the Big Bang wasn't a point, it was something that happened everywhere.
Later:
I've just realised that you also asked the question about [time beginning at the Big Bang](https://physics.stackexchange.com/questions/24018). In the answer to that question I explained how you use the metric to calculate a geodesic, with the result that you can't calculate back in time earlier than the Big Bang. You can also use the metric to calculate a line in space at a fixed value of time (a space-like geodesic). Our universe appears to be well described by the [FLRW](http://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric) metric with $\Omega$ = 1 that I mentioned in the other question, and if you use this metric to calculate your line you find it goes on forever i.e. the universe is infinite.
But then no-one knows for sure if the FLRW metric with $\Omega$ = 1 is the right one to describe our universe. It's certainly the simplest. | The current, widely accepted model for cosmology is [$\lambda$-CDM](http://en.wikipedia.org/wiki/Lambda-CDM_model). The universe appears (exactly) flat, and for simplicity the universe is infinite. Note that we distinguish between the observable universe (which is the local patch that light could have travelled between since the Big Bang) and the totality — we have constraints that even if the universe is not infinite, its size is many orders of magnitude larger than the observable one.
In the literature (especially the popular science one) the details are very muddled, because the consensus around $\lambda$-CDM model is quite recent — relying heavily on detailed measurements of the cosmological microwave background radiation, largely done by WMAP in the last 8 years or so. In a sense, the lay reader should be exceedingly careful when she reads statements (even from heavy-weight scientists) regarding cosmology — it is (perhaps ironically) a fast moving field. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | It's impossible to know whether the universe if finite or infinite because we'll never be able to see it all. Note that genneth says "and for simplicity the universe is infinite", and this is the key point really. It makes Physics simpler if the universe is infinite so we tend to assume it is.
But you need to consider what you mean by "infinite". It doesn't make sense to say the universe has an edge, because you then have to ask what happens if you go up to the edge then take one more step. That means the only alternative to the universe being infinite is that it loops back on itself like a sphere, so you can walk forever without reaching an edge, but eventually you'll be back where you started.
We don't think the universe is like a sphere because for that spacetime would have to have positive curvature, and experiments to date show space is flat (to within experimental error). However spacetime could be positively curved but with such small curvature that we can't detect it. Alternatively spacetime could be flat but have a complex global topology like a torus. The scale of anything like this would have to be larger than the observable univrse otherwise we'd have seen signs of it.
Incidentally, if the universe is infinite now it has always been infinite, even at the Big Bang. This is why you'll often hear it said that the Big Bang wasn't a point, it was something that happened everywhere.
Later:
I've just realised that you also asked the question about [time beginning at the Big Bang](https://physics.stackexchange.com/questions/24018). In the answer to that question I explained how you use the metric to calculate a geodesic, with the result that you can't calculate back in time earlier than the Big Bang. You can also use the metric to calculate a line in space at a fixed value of time (a space-like geodesic). Our universe appears to be well described by the [FLRW](http://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric) metric with $\Omega$ = 1 that I mentioned in the other question, and if you use this metric to calculate your line you find it goes on forever i.e. the universe is infinite.
But then no-one knows for sure if the FLRW metric with $\Omega$ = 1 is the right one to describe our universe. It's certainly the simplest. | The universe cannot be infinite because everything has a limit and infinity is not apllied to stuff which is real |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | The current, widely accepted model for cosmology is [$\lambda$-CDM](http://en.wikipedia.org/wiki/Lambda-CDM_model). The universe appears (exactly) flat, and for simplicity the universe is infinite. Note that we distinguish between the observable universe (which is the local patch that light could have travelled between since the Big Bang) and the totality — we have constraints that even if the universe is not infinite, its size is many orders of magnitude larger than the observable one.
In the literature (especially the popular science one) the details are very muddled, because the consensus around $\lambda$-CDM model is quite recent — relying heavily on detailed measurements of the cosmological microwave background radiation, largely done by WMAP in the last 8 years or so. In a sense, the lay reader should be exceedingly careful when she reads statements (even from heavy-weight scientists) regarding cosmology — it is (perhaps ironically) a fast moving field. | If the universe were spatially of finite and not too large volume then we could, in principle, discover this by observations in the future. For example, there might be evidence of light setting off in opposite directions eventually arriving at the same point after travelling around the universe, or something like that. This can happen even if the average curvature is zero or negative if the topology has the required form.
However if the universe is very large then we will not be able to make observations like that. We will not be able to tell whether it is infinite or just very large.
In fact I think it fair to say that no experiment, even in principle, could establish beyond reasonable doubt that the universe is in fact spatially infinite. Certainly it is not something anyone can claim to know for sure.
What happens is that people working in cosmology find that many of the ideas do not require one to know whether or not the universe is infinite, so if one is studying the average properties one might just say "oh well let's just treat it as if it is infinite". It has become so common to do this that people often forget that this is not a hypothesis that has been tested at all. It is just a working assumption, or a way of avoiding the need for more information. But if you query this assumption then it is not at all clear whether or not it is right. The idea of infinity is reasonably well-defined in mathematics, but it is not clear whether physical stuff can be infinite. Do we really know? No we do not.
So the short answer to your question is "no-one knows". And the longer answer is "very likely no one will ever know." |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | It's impossible to know whether the universe if finite or infinite because we'll never be able to see it all. Note that genneth says "and for simplicity the universe is infinite", and this is the key point really. It makes Physics simpler if the universe is infinite so we tend to assume it is.
But you need to consider what you mean by "infinite". It doesn't make sense to say the universe has an edge, because you then have to ask what happens if you go up to the edge then take one more step. That means the only alternative to the universe being infinite is that it loops back on itself like a sphere, so you can walk forever without reaching an edge, but eventually you'll be back where you started.
We don't think the universe is like a sphere because for that spacetime would have to have positive curvature, and experiments to date show space is flat (to within experimental error). However spacetime could be positively curved but with such small curvature that we can't detect it. Alternatively spacetime could be flat but have a complex global topology like a torus. The scale of anything like this would have to be larger than the observable univrse otherwise we'd have seen signs of it.
Incidentally, if the universe is infinite now it has always been infinite, even at the Big Bang. This is why you'll often hear it said that the Big Bang wasn't a point, it was something that happened everywhere.
Later:
I've just realised that you also asked the question about [time beginning at the Big Bang](https://physics.stackexchange.com/questions/24018). In the answer to that question I explained how you use the metric to calculate a geodesic, with the result that you can't calculate back in time earlier than the Big Bang. You can also use the metric to calculate a line in space at a fixed value of time (a space-like geodesic). Our universe appears to be well described by the [FLRW](http://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric) metric with $\Omega$ = 1 that I mentioned in the other question, and if you use this metric to calculate your line you find it goes on forever i.e. the universe is infinite.
But then no-one knows for sure if the FLRW metric with $\Omega$ = 1 is the right one to describe our universe. It's certainly the simplest. | If the universe were spatially of finite and not too large volume then we could, in principle, discover this by observations in the future. For example, there might be evidence of light setting off in opposite directions eventually arriving at the same point after travelling around the universe, or something like that. This can happen even if the average curvature is zero or negative if the topology has the required form.
However if the universe is very large then we will not be able to make observations like that. We will not be able to tell whether it is infinite or just very large.
In fact I think it fair to say that no experiment, even in principle, could establish beyond reasonable doubt that the universe is in fact spatially infinite. Certainly it is not something anyone can claim to know for sure.
What happens is that people working in cosmology find that many of the ideas do not require one to know whether or not the universe is infinite, so if one is studying the average properties one might just say "oh well let's just treat it as if it is infinite". It has become so common to do this that people often forget that this is not a hypothesis that has been tested at all. It is just a working assumption, or a way of avoiding the need for more information. But if you query this assumption then it is not at all clear whether or not it is right. The idea of infinity is reasonably well-defined in mathematics, but it is not clear whether physical stuff can be infinite. Do we really know? No we do not.
So the short answer to your question is "no-one knows". And the longer answer is "very likely no one will ever know." |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | It's impossible to know whether the universe if finite or infinite because we'll never be able to see it all. Note that genneth says "and for simplicity the universe is infinite", and this is the key point really. It makes Physics simpler if the universe is infinite so we tend to assume it is.
But you need to consider what you mean by "infinite". It doesn't make sense to say the universe has an edge, because you then have to ask what happens if you go up to the edge then take one more step. That means the only alternative to the universe being infinite is that it loops back on itself like a sphere, so you can walk forever without reaching an edge, but eventually you'll be back where you started.
We don't think the universe is like a sphere because for that spacetime would have to have positive curvature, and experiments to date show space is flat (to within experimental error). However spacetime could be positively curved but with such small curvature that we can't detect it. Alternatively spacetime could be flat but have a complex global topology like a torus. The scale of anything like this would have to be larger than the observable univrse otherwise we'd have seen signs of it.
Incidentally, if the universe is infinite now it has always been infinite, even at the Big Bang. This is why you'll often hear it said that the Big Bang wasn't a point, it was something that happened everywhere.
Later:
I've just realised that you also asked the question about [time beginning at the Big Bang](https://physics.stackexchange.com/questions/24018). In the answer to that question I explained how you use the metric to calculate a geodesic, with the result that you can't calculate back in time earlier than the Big Bang. You can also use the metric to calculate a line in space at a fixed value of time (a space-like geodesic). Our universe appears to be well described by the [FLRW](http://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric) metric with $\Omega$ = 1 that I mentioned in the other question, and if you use this metric to calculate your line you find it goes on forever i.e. the universe is infinite.
But then no-one knows for sure if the FLRW metric with $\Omega$ = 1 is the right one to describe our universe. It's certainly the simplest. | There is always the problem when answering this question that General Relativity, naively interpreted, allows you to speak about the part of the universe which is not observable from our vantage point, and this makes the question nontrivial.
But in a logical positivist perspective, the one suggest strongly by string-theoretic holography, the universe is exactly the stuff inside the cosmological horizon, and it is finite because the cosmological horizon is of finite area. There is no objective meaning to stuff outside the cosmological horizon, so there is no point in thinking about this--- it is meaningless in the sense of Carnap. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | It's impossible to know whether the universe if finite or infinite because we'll never be able to see it all. Note that genneth says "and for simplicity the universe is infinite", and this is the key point really. It makes Physics simpler if the universe is infinite so we tend to assume it is.
But you need to consider what you mean by "infinite". It doesn't make sense to say the universe has an edge, because you then have to ask what happens if you go up to the edge then take one more step. That means the only alternative to the universe being infinite is that it loops back on itself like a sphere, so you can walk forever without reaching an edge, but eventually you'll be back where you started.
We don't think the universe is like a sphere because for that spacetime would have to have positive curvature, and experiments to date show space is flat (to within experimental error). However spacetime could be positively curved but with such small curvature that we can't detect it. Alternatively spacetime could be flat but have a complex global topology like a torus. The scale of anything like this would have to be larger than the observable univrse otherwise we'd have seen signs of it.
Incidentally, if the universe is infinite now it has always been infinite, even at the Big Bang. This is why you'll often hear it said that the Big Bang wasn't a point, it was something that happened everywhere.
Later:
I've just realised that you also asked the question about [time beginning at the Big Bang](https://physics.stackexchange.com/questions/24018). In the answer to that question I explained how you use the metric to calculate a geodesic, with the result that you can't calculate back in time earlier than the Big Bang. You can also use the metric to calculate a line in space at a fixed value of time (a space-like geodesic). Our universe appears to be well described by the [FLRW](http://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric) metric with $\Omega$ = 1 that I mentioned in the other question, and if you use this metric to calculate your line you find it goes on forever i.e. the universe is infinite.
But then no-one knows for sure if the FLRW metric with $\Omega$ = 1 is the right one to describe our universe. It's certainly the simplest. | Nobody knows. But most probable theory says it is infinite.
**UPDATE**
The general theoretical description of Universe is given by [Friedmann–Lemaître–Robertson–Walker metric](http://en.wikipedia.org/wiki/FLRW_metric). This metric allows Universe to be both finite (closed) and infinite (opened). This depends on `k` parameter. If `k<=0` then the Universe is infinite. Current observations show that `k` is close to zero, which can mean either infinite or very big (much larger than 14 billions of ly which is observable space size).
I treat this as it is most probably infinite.
**UPDATE 2**
[Lambda-CDM model](http://en.wikipedia.org/wiki/Lambda-CDM_model) cannot itself answer the question if the Universe is finite or not. This is just a summation of observable data about what Universe is consist of. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | There is always the problem when answering this question that General Relativity, naively interpreted, allows you to speak about the part of the universe which is not observable from our vantage point, and this makes the question nontrivial.
But in a logical positivist perspective, the one suggest strongly by string-theoretic holography, the universe is exactly the stuff inside the cosmological horizon, and it is finite because the cosmological horizon is of finite area. There is no objective meaning to stuff outside the cosmological horizon, so there is no point in thinking about this--- it is meaningless in the sense of Carnap. | Nobody knows. But most probable theory says it is infinite.
**UPDATE**
The general theoretical description of Universe is given by [Friedmann–Lemaître–Robertson–Walker metric](http://en.wikipedia.org/wiki/FLRW_metric). This metric allows Universe to be both finite (closed) and infinite (opened). This depends on `k` parameter. If `k<=0` then the Universe is infinite. Current observations show that `k` is close to zero, which can mean either infinite or very big (much larger than 14 billions of ly which is observable space size).
I treat this as it is most probably infinite.
**UPDATE 2**
[Lambda-CDM model](http://en.wikipedia.org/wiki/Lambda-CDM_model) cannot itself answer the question if the Universe is finite or not. This is just a summation of observable data about what Universe is consist of. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | If the universe were spatially of finite and not too large volume then we could, in principle, discover this by observations in the future. For example, there might be evidence of light setting off in opposite directions eventually arriving at the same point after travelling around the universe, or something like that. This can happen even if the average curvature is zero or negative if the topology has the required form.
However if the universe is very large then we will not be able to make observations like that. We will not be able to tell whether it is infinite or just very large.
In fact I think it fair to say that no experiment, even in principle, could establish beyond reasonable doubt that the universe is in fact spatially infinite. Certainly it is not something anyone can claim to know for sure.
What happens is that people working in cosmology find that many of the ideas do not require one to know whether or not the universe is infinite, so if one is studying the average properties one might just say "oh well let's just treat it as if it is infinite". It has become so common to do this that people often forget that this is not a hypothesis that has been tested at all. It is just a working assumption, or a way of avoiding the need for more information. But if you query this assumption then it is not at all clear whether or not it is right. The idea of infinity is reasonably well-defined in mathematics, but it is not clear whether physical stuff can be infinite. Do we really know? No we do not.
So the short answer to your question is "no-one knows". And the longer answer is "very likely no one will ever know." | Nobody knows. But most probable theory says it is infinite.
**UPDATE**
The general theoretical description of Universe is given by [Friedmann–Lemaître–Robertson–Walker metric](http://en.wikipedia.org/wiki/FLRW_metric). This metric allows Universe to be both finite (closed) and infinite (opened). This depends on `k` parameter. If `k<=0` then the Universe is infinite. Current observations show that `k` is close to zero, which can mean either infinite or very big (much larger than 14 billions of ly which is observable space size).
I treat this as it is most probably infinite.
**UPDATE 2**
[Lambda-CDM model](http://en.wikipedia.org/wiki/Lambda-CDM_model) cannot itself answer the question if the Universe is finite or not. This is just a summation of observable data about what Universe is consist of. |
24,017 | I thought the universe was finite, but then I read this:
[How can something finite become infinite?](https://physics.stackexchange.com/questions/9419/how-can-something-finite-become-infinite)
And they seem to assume it is infinite. So which is it? | 2012/04/19 | [
"https://physics.stackexchange.com/questions/24017",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/3935/"
] | If the universe were spatially of finite and not too large volume then we could, in principle, discover this by observations in the future. For example, there might be evidence of light setting off in opposite directions eventually arriving at the same point after travelling around the universe, or something like that. This can happen even if the average curvature is zero or negative if the topology has the required form.
However if the universe is very large then we will not be able to make observations like that. We will not be able to tell whether it is infinite or just very large.
In fact I think it fair to say that no experiment, even in principle, could establish beyond reasonable doubt that the universe is in fact spatially infinite. Certainly it is not something anyone can claim to know for sure.
What happens is that people working in cosmology find that many of the ideas do not require one to know whether or not the universe is infinite, so if one is studying the average properties one might just say "oh well let's just treat it as if it is infinite". It has become so common to do this that people often forget that this is not a hypothesis that has been tested at all. It is just a working assumption, or a way of avoiding the need for more information. But if you query this assumption then it is not at all clear whether or not it is right. The idea of infinity is reasonably well-defined in mathematics, but it is not clear whether physical stuff can be infinite. Do we really know? No we do not.
So the short answer to your question is "no-one knows". And the longer answer is "very likely no one will ever know." | The universe cannot be infinite because everything has a limit and infinity is not apllied to stuff which is real |
18,211,322 | I'd like to have a method in one of my services that should return a generic list.
Then I want to add items to that list from another service.
```
class Fruit;
class Apple extends Fruit;
class FruitService() {
private ArrayList<? extends Fruit> getList() {
return new ArrayList<Apple>();
}
}
class SomeService() {
init() {
fruitService.getList().add(new Apple());
}
}
```
This gives the following error:
```
The method add(capture#3-of ? extends Fruit) in the type ArrayList<capture#3-of ? extends Fruit> is not applicable for the arguments (Apple)
```
Why? How could I add an Apple to that generic list?
My goal is to have that getList() method not to return a specific implementation. | 2013/08/13 | [
"https://Stackoverflow.com/questions/18211322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194415/"
] | You can't.
```
ArrayList<? extends Fruit>
```
could be in fact an
```
ArrayList<Apple>
```
in which you can't insert a `Banana` although `Banana extends Fruit`. And you can't insert a `Fruit` because it has to be at least something that extends `Apple`. And since Java can't see the required type anymore but has to guarantee that it would work it won't even allow you to insert an `Apple` although that would be allowed for the actual list.
-> You can't insert *anything* into `List<? extends Whatever>` besides `null` because you don't know the exact type. `? extends Whatever` results in a read-only list of `Whatever`.
If you want to return a regular & useful `List` don't return one with wildcard types.
Instead you could use generics in `FruitService` e.g.
```
class FruitService<T extends Fruit> {
private ArrayList<T> getList() {
return new ArrayList<T>();
}
public void useList(T fruit) {
getList().add(fruit);
}
}
class User {
void foo() {
FruitService<Apple> appleService = new FruitService<Apple>();
appleService.useList(new Apple());
FruitService<Banana> bananaService = new FruitService<Banana>();
bananaService.useList(new Banana());
}
}
``` | Can you have your `getList()` method return a `List` (or `ArrayList`) of `Fruit` instead? That way, you can insert any subtype of `Fruit` into the `List`.
```
private List<Fruit> getList() {
return new ArrayList<Fruit>();
}
``` |
18,211,322 | I'd like to have a method in one of my services that should return a generic list.
Then I want to add items to that list from another service.
```
class Fruit;
class Apple extends Fruit;
class FruitService() {
private ArrayList<? extends Fruit> getList() {
return new ArrayList<Apple>();
}
}
class SomeService() {
init() {
fruitService.getList().add(new Apple());
}
}
```
This gives the following error:
```
The method add(capture#3-of ? extends Fruit) in the type ArrayList<capture#3-of ? extends Fruit> is not applicable for the arguments (Apple)
```
Why? How could I add an Apple to that generic list?
My goal is to have that getList() method not to return a specific implementation. | 2013/08/13 | [
"https://Stackoverflow.com/questions/18211322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194415/"
] | You can't.
```
ArrayList<? extends Fruit>
```
could be in fact an
```
ArrayList<Apple>
```
in which you can't insert a `Banana` although `Banana extends Fruit`. And you can't insert a `Fruit` because it has to be at least something that extends `Apple`. And since Java can't see the required type anymore but has to guarantee that it would work it won't even allow you to insert an `Apple` although that would be allowed for the actual list.
-> You can't insert *anything* into `List<? extends Whatever>` besides `null` because you don't know the exact type. `? extends Whatever` results in a read-only list of `Whatever`.
If you want to return a regular & useful `List` don't return one with wildcard types.
Instead you could use generics in `FruitService` e.g.
```
class FruitService<T extends Fruit> {
private ArrayList<T> getList() {
return new ArrayList<T>();
}
public void useList(T fruit) {
getList().add(fruit);
}
}
class User {
void foo() {
FruitService<Apple> appleService = new FruitService<Apple>();
appleService.useList(new Apple());
FruitService<Banana> bananaService = new FruitService<Banana>();
bananaService.useList(new Banana());
}
}
``` | You could make the method generic -
```
public <T extends Fruit> List<T> getList() {
//....
```
The type variable `T` can capture the actual type argument, so the compiler can assume type-safety.
Also, you can do `return new ArrayList<T>();` instead of `return new ArrayList<Apple>();`. |
8,689,235 | I am getting the following error when I use my app for a little while. Usually takes between 50 and 100 movements to cause the crash. I am not making sense of it though as I am using storyboards, and it is a NIB error.
```
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:
'Could not load NIB in bundle: 'NSBundle
</Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/GUID/appname.app>
(loaded)' with name 'MainStoryboard_iPhone.storyboardc/q8p-MH-tsT-view-acD-hJ-g0C''
```
I am not 100% sure where to begin looking, but I assume that this means that the storyboard is corrupt?
I looked through all of my source, and I don't have the string "nib" anywhere, so there are no nibWithNibName calls or the like. I also don't have a MainWindow.xib, though I tried creating one. I am not sure if it can be set to the main interface when I am using storyboards though. There is one reference to a .nib in the .xcodeproj/project.pbxproj file, however:
```
/* Begin PBXBuildRule section */
148BDD4C14AE8D5E002C30ED /* PBXBuildRule */ = {
isa = PBXBuildRule;
compilerSpec = com.apple.compilers.proxy.script;
fileType = wrapper.nib;
isEditable = 1;
outputFiles = (
);
script = "$(DEVELOPER_BIN_DIR)/ibtool\n";
};
```
I am using storyboarding in Xcode 4.2. My main storyboard is set to MainStoryboard\_iPhone, and its file is named MainStoryboard\_iPhone.storyboard.
The crash is in the iOS 5 simulator. | 2011/12/31 | [
"https://Stackoverflow.com/questions/8689235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032341/"
] | I got exactly this error, too.
Finally I found the cause was I accessed `self.tableView` in `-(id)initWithCoder:(NSCoder *)aDecoder` before it was initiated.
So, I moved those code into `- (void)viewDidLoad`, everything went well. | This question appears to have been answered in the comments area. Reposting here so question shows as having an answer. -- gs.
Answer copied from comments:
There was a memory leak in a 3rd party component. Once the resources were exhausted, it would crash with the error above. A couple weeks of QA/Beta testing confirmed that it is gone. Thanks. – stubble jumper Jan 24 at 2:29 |
8,689,235 | I am getting the following error when I use my app for a little while. Usually takes between 50 and 100 movements to cause the crash. I am not making sense of it though as I am using storyboards, and it is a NIB error.
```
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:
'Could not load NIB in bundle: 'NSBundle
</Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/GUID/appname.app>
(loaded)' with name 'MainStoryboard_iPhone.storyboardc/q8p-MH-tsT-view-acD-hJ-g0C''
```
I am not 100% sure where to begin looking, but I assume that this means that the storyboard is corrupt?
I looked through all of my source, and I don't have the string "nib" anywhere, so there are no nibWithNibName calls or the like. I also don't have a MainWindow.xib, though I tried creating one. I am not sure if it can be set to the main interface when I am using storyboards though. There is one reference to a .nib in the .xcodeproj/project.pbxproj file, however:
```
/* Begin PBXBuildRule section */
148BDD4C14AE8D5E002C30ED /* PBXBuildRule */ = {
isa = PBXBuildRule;
compilerSpec = com.apple.compilers.proxy.script;
fileType = wrapper.nib;
isEditable = 1;
outputFiles = (
);
script = "$(DEVELOPER_BIN_DIR)/ibtool\n";
};
```
I am using storyboarding in Xcode 4.2. My main storyboard is set to MainStoryboard\_iPhone, and its file is named MainStoryboard\_iPhone.storyboard.
The crash is in the iOS 5 simulator. | 2011/12/31 | [
"https://Stackoverflow.com/questions/8689235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032341/"
] | This question appears to have been answered in the comments area. Reposting here so question shows as having an answer. -- gs.
Answer copied from comments:
There was a memory leak in a 3rd party component. Once the resources were exhausted, it would crash with the error above. A couple weeks of QA/Beta testing confirmed that it is gone. Thanks. – stubble jumper Jan 24 at 2:29 | I've had this problem before. The name of my nib was different than the name of my view controller while using `- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil` as my init. |
8,689,235 | I am getting the following error when I use my app for a little while. Usually takes between 50 and 100 movements to cause the crash. I am not making sense of it though as I am using storyboards, and it is a NIB error.
```
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:
'Could not load NIB in bundle: 'NSBundle
</Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/GUID/appname.app>
(loaded)' with name 'MainStoryboard_iPhone.storyboardc/q8p-MH-tsT-view-acD-hJ-g0C''
```
I am not 100% sure where to begin looking, but I assume that this means that the storyboard is corrupt?
I looked through all of my source, and I don't have the string "nib" anywhere, so there are no nibWithNibName calls or the like. I also don't have a MainWindow.xib, though I tried creating one. I am not sure if it can be set to the main interface when I am using storyboards though. There is one reference to a .nib in the .xcodeproj/project.pbxproj file, however:
```
/* Begin PBXBuildRule section */
148BDD4C14AE8D5E002C30ED /* PBXBuildRule */ = {
isa = PBXBuildRule;
compilerSpec = com.apple.compilers.proxy.script;
fileType = wrapper.nib;
isEditable = 1;
outputFiles = (
);
script = "$(DEVELOPER_BIN_DIR)/ibtool\n";
};
```
I am using storyboarding in Xcode 4.2. My main storyboard is set to MainStoryboard\_iPhone, and its file is named MainStoryboard\_iPhone.storyboard.
The crash is in the iOS 5 simulator. | 2011/12/31 | [
"https://Stackoverflow.com/questions/8689235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032341/"
] | I got exactly this error, too.
Finally I found the cause was I accessed `self.tableView` in `-(id)initWithCoder:(NSCoder *)aDecoder` before it was initiated.
So, I moved those code into `- (void)viewDidLoad`, everything went well. | I've had this problem before. The name of my nib was different than the name of my view controller while using `- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil` as my init. |
1,840 | After a discussion with Monica in the comments of this question:
[Injecting creativity into a cookbook](https://writing.stackexchange.com/questions/42760/injecting-creativity-into-a-cookbook#42760)
We have added a tag for [food-writing](https://writing.stackexchange.com/questions/tagged/food-writing "show questions tagged 'food-writing'")
Wiki:
>
> Use this tag for questions within the genre of food writing.
> Food-related blogs and books, cookbooks, scripts for cooking videos,
> podcasts, or TV, food-related travel writing, restaurant reviews,
> blogs and websites about food, cooking, or eating. Can also be used
> for questions focusing on food research and description within
> fiction.
>
>
>
I looked for other questions to add the tag to and only found one. Which surprises me since this is a huge genre in nonfiction and very popular not just for bloggers but also short video makers, newspaper writers, and magazines.
Question: You all cool with this? Any changes you want to make? | 2019/03/01 | [
"https://writers.meta.stackexchange.com/questions/1840",
"https://writers.meta.stackexchange.com",
"https://writers.meta.stackexchange.com/users/32946/"
] | **We shouldn't be afraid to make changes as the need arises.**
Sometimes, the need for a tag crops up. Often, it's a single question that gets things started, *but* as long as we can see a reasonable number of on-topic questions benefiting from the tag for categorization, there's a good chance it's a good tag. I think [food-writing](https://writing.stackexchange.com/questions/tagged/food-writing "show questions tagged 'food-writing'") meets that criteria.
The same goes for the tag wiki excerpt; provide some guidance for the tag's usage, but if it turns out to be unclear, or too narrow, or too broad, or whatever, nothing says we can't change it.
**Very little on the site is cast in stone.**
Tags, and tag wikis, and tag wiki excerpts, are editable [just like questions and answers](https://writing.stackexchange.com/help/editing), and for good reason. The reputation limits are different, but the basic concept remains the same: collaborative editing ultimately improves the quality of the content. | I'm all for it
For the sake of discussion, is there maybe a larger group here that can be lumped together?
Possibly similar topics:
* Travel
* Lifestyle
(please edit if you know what this group would be called or have more suggestions) |
507,239 | How can I determine the proper value for a pull-up resistor that's being used as an input to a CD4078 when the [datasheet](https://www.ti.com/lit/ds/symlink/cd4078b.pdf?ts=1593018603797) doesn't mention anything about input impedance? I'm trying to minimize power usage since my circuit will be powered by a battery.
The datasheet does say that the input current is +- 10mA, so should a 100K @ 5V suffice since that should provide 50mA? | 2020/06/24 | [
"https://electronics.stackexchange.com/questions/507239",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/256169/"
] | Considering strictly *static* DC operation for these CMOS gates...
Input current at maximum temperature tops-out at one microamp. So a large-value resistor of about 3 MEGohm will ensure a logic high, if no other current paths are present.
So why might you use a smaller-value pullup? A few reasons:
* Noise pulses from nearby traces might momentarily yank a high-resistance pullup low.
* If an open-collector (or open-drain) is to drive this input low, its leakage current would require a smaller-value pullup resistor.
* A large-value pullup resistor pulls up rather slowly in the presence of capacitance. The capacitance of the input alone might be about 7pf. A slow transition time can cause logic gates to go squirrelly, and oscillate as the input slowly transits from low-to-high. A clean logic transition is often required.
The logical solution to these problems is to lower the value of pull-up resistance.
Consider that an input pin that spends most of its time "pulled-up" to logic high causes almost no current drain. You can choose a smaller-value pullup resistor, with almost no down-side.
If the pulled-up input spends most of its time low (pulled down by some other source) then current does flow, and a large-value pull-up resistor value should be chosen to reduce battery drain. | The datasheet states clearly that the maximum input current is 1μA when the input voltage is limited to be not less than 0 and not more than VDD. This is the current value to use when calculating a pullup resistor value.
The 10mA limit applies for any input voltage, and in particular it applies when the input voltage is less than 0 or greater than VDD. In that case the ESD protection diodes at the chip inputs will be forward biased and the current must be limited to prevent damaging those diodes. |
30,583,053 | I have 3 controllers. I am using push and pop method to change the controllers.
```
[self.navigationController pushViewController:product_subcatagory animated:YES];
[self.navigationController popViewControllerAnimated:YES];
```
The issue I am getting while i am continue doing push and pop operation for 8 to 10 minutes as it responding slow animation and at one step is getting crashed. So what could be the reason for slow animation for push-pop controller operation.
Below as Example I have 3 class A,B,C. Then following push view controller and pop view controller operation i am performing.
A->B->C It has three possibilities 1. B->A 2.C->B->A 3.C->B
Thanks in Advance. | 2015/06/01 | [
"https://Stackoverflow.com/questions/30583053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962897/"
] | You can use the `require_geomType` parameter for various GDAL functions to extract the features that you need:
```
library(rgdal)
ogrListLayers("test.geojson")
## [1] "OGRGeoJSON"
## attr(,"driver")
## [1] "GeoJSON"
## attr(,"nlayers")
## [1] 1
# This fails but you can at least see the geoms it whines about
ogrInfo("test.geojson", "OGRGeoJSON")
## Error in ogrInfo("test.geojson", "OGRGeoJSON") :
## Multiple incompatible geometries: wkbPoint: 98; wkbLineString: 660; wkbPolygon: 23
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbPoint")
## NOTE: keeping only 98 wkbPoint of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbPoint with 98 rows
## Feature type: wkbPoint with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbLineString")
## NOTE: keeping only 660 wkbLineString of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbLineString with 660 rows
## Feature type: wkbLineString with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total (same as above)
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbPolygon")
## NOTE: keeping only 23 wkbPolygon of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbPolygon with 23 rows
## Feature type: wkbPolygon with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total (same as above)
points <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbPoint")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbPoint feature type, with 98 rows
## It has 78 fields
## NOTE: keeping only 98 wkbPoint of 781 features
lines <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbLineString")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbLineString feature type, with 660 rows
## It has 78 fields
## NOTE: keeping only 660 wkbLineString of 781 features
polygons <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbPolygon")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbPolygon feature type, with 23 rows
## It has 78 fields
## NOTE: keeping only 23 wkbPolygon of 781 features
# prove they red in things
plot(lines, col="#7f7f7f")
plot(polygons, add=TRUE)
plot(points, add=TRUE, col="red")
```
![enter image description here](https://i.stack.imgur.com/C9mya.png) | You can use ogr2ogr on the command line to split this monstrous chimera into sensible things:
```
ogr2ogr -where "OGR_GEOMETRY='LINESTRING'" \
-f "GeoJSON" lines.geojson test.geojson
```
and similarly for points and polygons.
There was some chatter a few years ago about implementing OGR\_SQL into `readOGR`, at which point you would be able to do this from R, but Roger didn't want to do it and nobody wanted to help :(
Once you've created the split geojson files you can read them into a single `rgeos::SpatialCollections` object:
```
points=readOGR("points.geojson","OGRGeoJSON")
polys=readOGR("polygons.geojson","OGRGeoJSON")
lines=readOGR("lines.geojson","OGRGeoJSON")
require(rgeos)
g = SpatialCollections(points=points, lines=lines, polygons=polys)
plot(g)
```
If you want to try something with the `geojsonio` then you can use `Filter` to select list elements of a given geometry from the Geometry Collection
```
polygon_features = Filter(
function(f){f$geometry$type=="Polygon"},
test$features)
```
but then you still have to build something you can get into separate R entities.... |
30,583,053 | I have 3 controllers. I am using push and pop method to change the controllers.
```
[self.navigationController pushViewController:product_subcatagory animated:YES];
[self.navigationController popViewControllerAnimated:YES];
```
The issue I am getting while i am continue doing push and pop operation for 8 to 10 minutes as it responding slow animation and at one step is getting crashed. So what could be the reason for slow animation for push-pop controller operation.
Below as Example I have 3 class A,B,C. Then following push view controller and pop view controller operation i am performing.
A->B->C It has three possibilities 1. B->A 2.C->B->A 3.C->B
Thanks in Advance. | 2015/06/01 | [
"https://Stackoverflow.com/questions/30583053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962897/"
] | You can use ogr2ogr on the command line to split this monstrous chimera into sensible things:
```
ogr2ogr -where "OGR_GEOMETRY='LINESTRING'" \
-f "GeoJSON" lines.geojson test.geojson
```
and similarly for points and polygons.
There was some chatter a few years ago about implementing OGR\_SQL into `readOGR`, at which point you would be able to do this from R, but Roger didn't want to do it and nobody wanted to help :(
Once you've created the split geojson files you can read them into a single `rgeos::SpatialCollections` object:
```
points=readOGR("points.geojson","OGRGeoJSON")
polys=readOGR("polygons.geojson","OGRGeoJSON")
lines=readOGR("lines.geojson","OGRGeoJSON")
require(rgeos)
g = SpatialCollections(points=points, lines=lines, polygons=polys)
plot(g)
```
If you want to try something with the `geojsonio` then you can use `Filter` to select list elements of a given geometry from the Geometry Collection
```
polygon_features = Filter(
function(f){f$geometry$type=="Polygon"},
test$features)
```
but then you still have to build something you can get into separate R entities.... | A few years later, a couple of alternatives - `library(geojsonsf)` and `library(sf)` will both read the geojson and convert to `sf` objects
```
url <- 'https://github.com/Robinlovelace/Creating-maps-in-R/raw/master/data/test-multifeature.geojson'
## these give the same result
sf <- geojsonsf::geojson_sf( url )
sf <- sf::st_read( url )
```
---
Let's take a look
```
library(mapdeck)
set_token( "MAPBOX_TOKEN" )
mapdeck( style = mapdeck_style("light") ) %>%
add_sf( sf )
```
[![enter image description here](https://i.stack.imgur.com/jF4yt.png)](https://i.stack.imgur.com/jF4yt.png) |
30,583,053 | I have 3 controllers. I am using push and pop method to change the controllers.
```
[self.navigationController pushViewController:product_subcatagory animated:YES];
[self.navigationController popViewControllerAnimated:YES];
```
The issue I am getting while i am continue doing push and pop operation for 8 to 10 minutes as it responding slow animation and at one step is getting crashed. So what could be the reason for slow animation for push-pop controller operation.
Below as Example I have 3 class A,B,C. Then following push view controller and pop view controller operation i am performing.
A->B->C It has three possibilities 1. B->A 2.C->B->A 3.C->B
Thanks in Advance. | 2015/06/01 | [
"https://Stackoverflow.com/questions/30583053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962897/"
] | You can use the `require_geomType` parameter for various GDAL functions to extract the features that you need:
```
library(rgdal)
ogrListLayers("test.geojson")
## [1] "OGRGeoJSON"
## attr(,"driver")
## [1] "GeoJSON"
## attr(,"nlayers")
## [1] 1
# This fails but you can at least see the geoms it whines about
ogrInfo("test.geojson", "OGRGeoJSON")
## Error in ogrInfo("test.geojson", "OGRGeoJSON") :
## Multiple incompatible geometries: wkbPoint: 98; wkbLineString: 660; wkbPolygon: 23
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbPoint")
## NOTE: keeping only 98 wkbPoint of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbPoint with 98 rows
## Feature type: wkbPoint with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbLineString")
## NOTE: keeping only 660 wkbLineString of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbLineString with 660 rows
## Feature type: wkbLineString with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total (same as above)
ogrInfo("test.geojson", "OGRGeoJSON", require_geomType="wkbPolygon")
## NOTE: keeping only 23 wkbPolygon of 781 features
## note that extent applies to all features
## Source: "test.geojson", layer: "OGRGeoJSON"
## Driver: GeoJSON number of rows 781
## selected geometry type: wkbPolygon with 23 rows
## Feature type: wkbPolygon with 2 dimensions
## Extent: (12.48326 41.88355) - (12.5033 41.89629)
## CRS: +proj=longlat +datum=WGS84 +no_defs
## Number of fields: 78
## name type length typeName
## 1 area 4 0 String
## 2 bicycle 4 0 String
## ...
## LONG LIST - 78 total (same as above)
points <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbPoint")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbPoint feature type, with 98 rows
## It has 78 fields
## NOTE: keeping only 98 wkbPoint of 781 features
lines <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbLineString")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbLineString feature type, with 660 rows
## It has 78 fields
## NOTE: keeping only 660 wkbLineString of 781 features
polygons <- readOGR("test.geojson", "OGRGeoJSON", require_geomType="wkbPolygon")
## OGR data source with driver: GeoJSON
## Source: "test.geojson", layer: "OGRGeoJSON"
## with 781 features;
## Selected wkbPolygon feature type, with 23 rows
## It has 78 fields
## NOTE: keeping only 23 wkbPolygon of 781 features
# prove they red in things
plot(lines, col="#7f7f7f")
plot(polygons, add=TRUE)
plot(points, add=TRUE, col="red")
```
![enter image description here](https://i.stack.imgur.com/C9mya.png) | A few years later, a couple of alternatives - `library(geojsonsf)` and `library(sf)` will both read the geojson and convert to `sf` objects
```
url <- 'https://github.com/Robinlovelace/Creating-maps-in-R/raw/master/data/test-multifeature.geojson'
## these give the same result
sf <- geojsonsf::geojson_sf( url )
sf <- sf::st_read( url )
```
---
Let's take a look
```
library(mapdeck)
set_token( "MAPBOX_TOKEN" )
mapdeck( style = mapdeck_style("light") ) %>%
add_sf( sf )
```
[![enter image description here](https://i.stack.imgur.com/jF4yt.png)](https://i.stack.imgur.com/jF4yt.png) |
378,350 | Imagine the following solution:
* Website ABC.com (not Web Application)
* BLL (business logic layer in a seperate assembly)
* DTO (dto objects in their own assembly)
* DAL (data access layer in it's own assembly as well).
1. The BLL has a reference to the DAL.
2. The BLL has a reference to the DTO layer.
3. The Website project references the BLL.
When one compiles the website project, the following DLLs will appear in the BIN directory:
BLL.dll
DTO.dll
DAL.dll
When one goes to preview the site, an error occurs about not having the necessary assembly references... Now if one right clicks on the website project, Add Reference, and explicitly add the reference to the missing assemblies, it will work fine.
It seems to me like ASP.NET pulls the referenced assemblies of the referenced assembly being added/referenced in the website.
Why does one need to add explicit references to the references of the references... ? Sorry if I'm not wording this correctly or if it confusing. | 2008/12/18 | [
"https://Stackoverflow.com/questions/378350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47460/"
] | You could use a [MatchEvaluator](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx) to manipulate the replacement string? It gets handed the matched string so you could look at the case of that and assemble a replacement. Seemsa bit overkill, though | or use this online tool: <http://gskinner.com/RegExr/> |
73,697,854 | I got stuck at this mongoose code. I tried billions of time for this. but in my node app.js output is : MongooseError: document must have an \_id before saving
at D:\node\_modules\mongoose\lib\model.js:297:18
at processTicksAndRejections (node:internal/process/task\_queues:78:11)
**and also data didn't save on mongoose shell. on some my research on internet i found one answer that if you dont provide '\_id' then mongoose will do it automatically. On my code I didn't provide any \_id. Now this didnt work also. If i tried with provide \_id this also didnt work. What should I do now? Please, save my life!!!**
Here is my code:
```
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/newDB", {useNewUrlParser: true});
const peopleSchema = new mongoose.Schema({
name: String,
age: Number,
address: String
});
const People= mongoose.model("People", peopleSchema);
const person = new People(
{
name: "john",
age: 25,
address: "New York, USA"
},
{
name: "Don",
age: 30,
address: "Chicago, USA"
},
{
name: "Kahn",
age: 34,
address: "Dhaka, Bangladesh"
}
);
person.save();
``` | 2022/09/13 | [
"https://Stackoverflow.com/questions/73697854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19982365/"
] | Let me explain the problem in the above code by adding comments:
```
const addItemVoucher = () => {
const totalItem = valueItem.quantity * valueItem.price;
// this will tell React to chain an update event on the "valueItem"
// but this will happen on the next re-render of your component
setValueItem((state) => ({ ...state, total: totalItem }));
// so this will still log the current valueItem with the old "total"
console.log(valueItem);
// now you are creating here an outdated item copy
const itemTemp = Object.assign({}, valueItem);
// you add this outdated copy to your list, but for next re-render
setItemVouchers((itemVouchers) => [...itemVouchers, itemTemp]);
// you update the "valueItem" again, but again for next re-render
// since React@18 this means you only see this update and NOT the
// previous update you did before
setValueItem({
id: "",
article: "",
price: 0.0,
quantity: 0.0,
total: 0.0
});
};
```
To fix this, you might want to do this instead:
```
const addItemVoucher = () => {
const totalItem = valueItem.quantity * valueItem.price;
setItemVouchers((itemVouchers) => [...itemVouchers, { ...valueItem, total: totalItem }]);
setValueItem({
id: "",
article: "",
price: 0.0,
quantity: 0.0,
total: 0.0
});
};
``` | Try this way
```
const addItemVoucher = () => {
const totalItem = valueItem.quantity * valueItem.price;
const tempValueItem = {...valueItem}
tempValueItem['total'] = totalItem
const itemTemp = Object.assign({}, valueItem);
setItemVouchers((itemVouchers) => [...itemVouchers, itemTemp]);
tempValueItem['id'] = ''
tempValueItem['article'] = ''
tempValueItem['price'] = 0.0
tempValueItem['id'] = 0.0
tempValueItem['total'] = 0.0
setValueItem(tempValueItem);
};
``` |
48,642,296 | I'm trying to do something that should be very basic but impossible to bypass that issue.
I have 2 tables. The first one is a table that stocks the page architecture and the second one stocks some contents. Occasionally, I'd like to call some contents from my first table. I've tried to create a Foreign Key but that only displays the id of the content.
Here is the structure of my table 1 (page models)
1 idPrimaire int(11) Non Aucun(e) AUTO\_INCREMENT
2 client varchar(100) utf8\_general\_ci Non Aucun(e)
3 nom\_document varchar(100) utf8\_general\_ci Non Aucun(e)
4 type\_page varchar(100) utf8\_general\_ci Non Aucun(e)
5 nom\_page varchar(100) utf8\_general\_ci Non Aucun(e)
6 valeur\_contenu int(11) Non Aucun(e)
7 ordre int(11) Non Aucun(e)
Here is the structure of my table 2 (general contents)
1 idPrimaire int(11) Non Aucun(e) AUTO\_INCREMENT
2 nom\_liste varchar(100) utf8\_general\_ci Non Aucun(e)
3 nom\_contenu varchar(255) utf8\_general\_ci Non Aucun(e)
4 valeur\_contenu text utf8\_general\_ci Non Aucun(e)
5 type\_contenu varchar(100) utf8\_general\_ci Non Aucun(e)
So what I am looking for is to connect table 1 & 2 in order to be able to call some content from table1 | 2018/02/06 | [
"https://Stackoverflow.com/questions/48642296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You need to have a foreign key on your second table so you can `JOIN` them together.
For example
**Table 1**
```
1 idPrimaire int(11) Non Aucun(e) AUTO_INCREMENT
2 client varchar(100) utf8_general_ci Non Aucun(e)
3 nom_document varchar(100) utf8_general_ci Non Aucun(e)
4 type_page varchar(100) utf8_general_ci Non Aucun(e)
5 nom_page varchar(100) utf8_general_ci Non Aucun(e)
6 valeur_contenu int(11) Non Aucun(e)
7 ordre int(11) Non Aucun(e)
```
**Table 2**
```
1 idPrimaire int(11) Non Aucun(e) AUTO_INCREMENT
2 client varchar(100) utf8_general_ci Non Aucun(e)
3 nom_document varchar(100) utf8_general_ci Non Aucun(e)
4 type_page varchar(100) utf8_general_ci Non Aucun(e)
5 nom_page varchar(100) utf8_general_ci Non Aucun(e)
6 valeur_contenu int(11) Non Aucun(e)
7 ordre int(11) Non Aucun(e)
8 table_1_id int(11)
```
Then in SQL you would write
```
SELECT * FROM table_1 LEFT JOIN table_2 ON table_1.idPrimaire = table_2.table_1_id
```
The join doesn't have to be left, it can be whatever join you need. Once these 2 tables are together, you can fetch them in php using an associative array then get the columns you need.
For example
```
$query = SELECT * FROM table_1 LEFT JOIN table_2 ON table_1.idPrimaire = table_2.table_1_id;
$result = ($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo $row['nom_page'];
}
``` | You could try "natural join" if u want them combined based on related column, otherwise "full outer join" which returns all records when there is a match in either table1 or table2.
"inner join" will give you values matching on both the table.
Go through this they have explained everything here:
<https://www.w3schools.com/sql/sql_join_inner.asp> |
17,386,423 | I want to mimic the "Want" iPhone app background, there are 3 colors that I want a view to cycle through, let us say red, blue, and green.
I want there to be a gradient with red to blue to green, each 1/3 of the screen, faded into each other (gradient), then, I want the red to go off screen on the top and come back on the bottom. (See photos below...)
The animation should move up, I want the gradient to go up and reform at the bottom of the screen and go up.
I tried using CAGradientLayer and animating the "colors" property, but that just looks like everything fades into each other, not necessarily moving off screen.
Contemplating using OpenGL, but don't want to go that low for something that seems pretty simple. Any help/code samples would be much appreciated. I basically need help animating a gradient using CoreAnimation/CoreGraphics.
Thanks in advance!
![enter image description here](https://i.stack.imgur.com/1xRr0.png)
![enter image description here](https://i.stack.imgur.com/Ot7qX.png)
![enter image description here](https://i.stack.imgur.com/6D5Io.png) | 2013/06/30 | [
"https://Stackoverflow.com/questions/17386423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/929156/"
] | Animating the `colors` property of a CAGradientLayer will just cause a fade, as you've discovered. However I think a gradient layer is the way to go. You should look at the following options:
* animating the `positions` property as well as / instead of the `colors`.
* creating a larger gradient layer that contains your full animation cycle and animating its position
The second option will probably give the best performance as the gradient will not need to be recalculated. | You should subclass UIView to create a GradientView class. Add an array to hold the colors you are moving through. The choice is important and I [wrote an article](http://blog.karmadust.com/animating-a-gradient-in-a-uiview/) explaining why. Override the *drawRect(rect: CGRect)* method and interpolate between the components of the colors:
```
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
let c1 = colors[index == 0 ? (colors.count - 1) : index - 1] // previous
let c2 = colors[index] // current
let c3 = colors[index == (colors.count - 1) ? 0 : index + 1] // next
var c1Comp = CGColorGetComponents(c1.CGColor)
var c2Comp = CGColorGetComponents(c2.CGColor)
var c3Comp = CGColorGetComponents(c3.CGColor)
var colorComponents = [
c1Comp[0] * (1 - factor) + c2Comp[0] * factor, // color 1 and 2
c1Comp[1] * (1 - factor) + c2Comp[1] * factor,
c1Comp[2] * (1 - factor) + c2Comp[2] * factor,
c1Comp[3] * (1 - factor) + c2Comp[3] * factor,
c2Comp[0] * (1 - factor) + c3Comp[0] * factor, // color 2 and 3
c2Comp[1] * (1 - factor) + c3Comp[1] * factor,
c2Comp[2] * (1 - factor) + c3Comp[2] * factor,
c2Comp[3] * (1 - factor) + c3Comp[3] * factor
]
let gradient = CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), &colorComponents, [0.0, 1.0], 2)
let startPoint = CGPoint(x: 0.0, y: 0.0)
let endPoint = CGPoint(x: rect.size.width, y: rect.size.height)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsAfterEndLocation)
CGContextRestoreGState(context);
}
```
The index variable starts from 0 and wraps around the colors array while the factor is between 0.0 and 1.0 and animates through a timer:
```
var index: Int = 0
var factor: CGFloat = 1.0
var timer: NSTimer?
func animateToNextGradient() {
index = (index + 1) % colors.count
self.setNeedsDisplay()
self.factor = 0.0
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0/60.0, target: self, selector: "animate:", userInfo: nil, repeats: true)
}
func animate(timer: NSTimer) {
self.factor += 0.02
if(self.factor > 1.0) {
self.timer?.invalidate()
}
self.setNeedsDisplay()
}
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | Give like this
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
```
or you can also write as
```
button span{
padding-left: 10px;
transition: .2s;
}
button span:hover{
padding-left: 20px;
}
``` | **You need to add separate rule for each span,**
example:
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | Give like this
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
```
or you can also write as
```
button span{
padding-left: 10px;
transition: .2s;
}
button span:hover{
padding-left: 20px;
}
``` | I think you need this, the issue was you `.hold.roll span` or `.hold,.roll span` is not acceptable, is should be `.hold span,.roll span`
```css
.hold span , .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover , .hold span:hover{
padding-left: 20px;
}
```
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | Give like this
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
```
or you can also write as
```
button span{
padding-left: 10px;
transition: .2s;
}
button span:hover{
padding-left: 20px;
}
``` | You can also add more than one class for a object, lets say you have two classes in your css file:
```
.default-padding {padding:6px}
.button {background:#c00;}
<input type="button" class="default-padding button"></button>
<label class="default-padding">Label</label>
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | Give like this
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
```
or you can also write as
```
button span{
padding-left: 10px;
transition: .2s;
}
button span:hover{
padding-left: 20px;
}
``` | You can combine as many selectors as you wnat, but all of them must be completely defined. Here's a nice article about this issue: [Grouping Multiple CSS Selectors](https://www.thoughtco.com/grouping-multiple-css-selectors-3467065).
This is what you are looking for:
```
.hold span, .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover, .hold span:hover{
padding-left: 20px;
}
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | **You need to add separate rule for each span,**
example:
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
``` | You can also add more than one class for a object, lets say you have two classes in your css file:
```
.default-padding {padding:6px}
.button {background:#c00;}
<input type="button" class="default-padding button"></button>
<label class="default-padding">Label</label>
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | **You need to add separate rule for each span,**
example:
```
.hold span,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold span:hover,.roll span:hover{
padding-left: 20px;
}
``` | You can combine as many selectors as you wnat, but all of them must be completely defined. Here's a nice article about this issue: [Grouping Multiple CSS Selectors](https://www.thoughtco.com/grouping-multiple-css-selectors-3467065).
This is what you are looking for:
```
.hold span, .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover, .hold span:hover{
padding-left: 20px;
}
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | I think you need this, the issue was you `.hold.roll span` or `.hold,.roll span` is not acceptable, is should be `.hold span,.roll span`
```css
.hold span , .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover , .hold span:hover{
padding-left: 20px;
}
```
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
``` | You can also add more than one class for a object, lets say you have two classes in your css file:
```
.default-padding {padding:6px}
.button {background:#c00;}
<input type="button" class="default-padding button"></button>
<label class="default-padding">Label</label>
``` |
46,642,987 | I am a newbie in web development, I have an HTML document with some classes, however, while designing I came across these This is my HTML doc snippet:
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
```
and i have written css like this:
```css
.hold span{
padding-left: 10px;
transition: .2s;
}
.roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover{
padding-left: 20px;
}
.hold span:hover{
padding-left: 20px;
}
```
However, i tried to make it shorter like this, it was not working properly:
```css
.hold.roll span{
padding-left: 10px;
transition: .2s;
}
.hold.roll span:hover{
padding-left: 20px;
}
```
and also like this:
```css
.hold,.roll span{
padding-left: 10px;
transition: .2s;
}
.hold,.roll span:hover{
padding-left: 20px;
}
```
Is there something which I am missing about CSS ? Thanks, why my other 2 code is not working. ? | 2017/10/09 | [
"https://Stackoverflow.com/questions/46642987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6787187/"
] | I think you need this, the issue was you `.hold.roll span` or `.hold,.roll span` is not acceptable, is should be `.hold span,.roll span`
```css
.hold span , .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover , .hold span:hover{
padding-left: 20px;
}
```
```html
<button class="roll"><i class="ion-ios-loop"></i><span>Roll dice</span></button>
<button class="hold"><i class="ion-ios-download-outline"></i><span>Hold</span></button>
``` | You can combine as many selectors as you wnat, but all of them must be completely defined. Here's a nice article about this issue: [Grouping Multiple CSS Selectors](https://www.thoughtco.com/grouping-multiple-css-selectors-3467065).
This is what you are looking for:
```
.hold span, .roll span{
padding-left: 10px;
transition: .2s;
}
.roll span:hover, .hold span:hover{
padding-left: 20px;
}
``` |
35,678,671 | How would I make this code show the current time, accurately to the second?
```
using System;
namespace TestCode
{
class DisplayTime
{
static void Main()
{
DateTime now = DateTime.Now;
Console.WriteLine(" Blah Blah Blah ");
Console.WriteLine(now);
Console.ReadLine();
}
}
```
} | 2016/02/28 | [
"https://Stackoverflow.com/questions/35678671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5992313/"
] | By default, `ToString()` has already done it for you.
```
Console.WriteLine("Don't swear."); //change this too
Console.WriteLine(now.ToString());
```
You can also make it print in specific format as you want to:
```
Console.WriteLine("Don't swear."); //change this too
Console.WriteLine(now.ToString(yyyy-MM-dd HH:mm:ss.fff)); //up to milliseconds
```
Check [this](https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx) and [this](https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx) for more choices. | ```
DateTime time = DateTime.Now;
string Time = time.ToString("mm");
Console.WriteLine($"{time}");
Console.ReadLine();
```
It will not show the milliseconds like the above person said, but perhaps it will do. |
11,132,410 | How I can Read the RGB-Pixel by Pixel values from CGImagea also after how to assign it to UIImage | 2012/06/21 | [
"https://Stackoverflow.com/questions/11132410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You would - **need an FM Transmitter** - that is, the *appropriate hardware* for generating frequencies in the desired range.
It is a good thing [portable FM Transmitters](https://www.google.com/?q=portable+FM+transmitter) can be bought from many electronic retailers. They usually plug into the 2.5mm jack and have a battery for several hours of transmission; there are Android/Phone-specific models as well.
The Nokia C7 *already has* the appropriate hardware built in. The standard "Android" does not.
Good luck :) | Somebody over at XDA mentioned a similar thing
<http://forum.xda-developers.com/showthread.php?t=1092719>
It sounds really complicated, and potentially only available to certain roms, meaning it's probably not something easily achievable on android at the moment.
Anyway good luck, I'd love to see this happening. |
46,496,554 | Data set looks like
```
id statusid statusdate
100 22 04/12/2016
100 22 04/14/2016
100 25 04/16/2016
100 25 04/17/2016
100 25 04/19/2016
100 22 04/22/2016
100 22 05/14/2016
100 27 05/19/2016
100 27 06/14/2016
100 25 06/18/2016
100 22 07/14/2016
100 22 07/18/2016
```
Task is to select the First time each status was logged. Number of unique times each status were logged.
Example :
For Status 22
* First time status date: 04/12/2016
* Last time Status first date: 07/14/2016
* Number of Unique times it went to that status: 3 | 2017/09/29 | [
"https://Stackoverflow.com/questions/46496554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5559574/"
] | Since it is not specified, there is no guarantee. You should not depend on this behavior.
Certainly you could find out what will happen with the current implementation simply by reading it:
```
(defn max-key
"Returns the x for which (k x), a number, is greatest."
{:added "1.0"
:static true}
([k x] x)
([k x y] (if (> (k x) (k y)) x y))
([k x y & more]
(reduce1 #(max-key k %1 %2) (max-key k x y) more)))
```
It is clearly right-biased, so as implemented now you will get the rightmost element among all those that qualify. But again, because there is no guarantee, and any future version of Clojure may change this behavior. | ClojureDocs has [a link to the source code](https://github.com/clojure/clojure/blob/clojure-1.9.0-alpha14/src/clj/clojure/core.clj#L4915) (top right corner) so you can see the details and predict what will happen in any specific case. However, when more than one answer is available it is generally unspecified which item will be returned. Also, it can change with future versions of Clojure (which has happened before).
So, if you need a specific outcome (first, last, or something else) you may need to write a wrapper function to enforce the desired behavior in the event of ambiguous inputs. |
54,216,516 | I have this in `src/vue.config.js`
```
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
},
},
},
};
```
and I'm calling the api with
```
axios.get('/api/parts')
.then(result => commit('updateParts', result.data))
.catch(console.error);
```
But I just keep getting
>
> Error: "Request failed with status code 404"
>
>
>
And I can see the request is being made to port 8080 instead of 8081
I can access the api in the browser with no problems
How can I debug this? | 2019/01/16 | [
"https://Stackoverflow.com/questions/54216516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671754/"
] | Your `vue.config.js` is not supposed to be in the src folder. It must be in the root of your project. Simply move the file.
The configuration reference for the server can be found here: <https://cli.vuejs.org/config/#devserver-proxy> but it seems you're actually doing it right. The file is just at the wrong folder. | I had the same issue after trying a couple of combinations finally I figured it out.
I am using `Axios` and my application is running at port `8080`
**main.js:**
`axios.defaults.baseURL = 'http://localhost:8080/api/'`
**vue.config.js**
```
module.exports = {
devServer: {
proxy: 'https://reqres.in'
}
}
```
**My Vue Component**
```
this.axios.get("users")
.then(response => {
this.items = response.data.data;
this.isLoading = false;
})
```
**Browser's Network tab:**
[![enter image description here](https://i.stack.imgur.com/J8yhm.png)](https://i.stack.imgur.com/J8yhm.png) |
54,216,516 | I have this in `src/vue.config.js`
```
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
},
},
},
};
```
and I'm calling the api with
```
axios.get('/api/parts')
.then(result => commit('updateParts', result.data))
.catch(console.error);
```
But I just keep getting
>
> Error: "Request failed with status code 404"
>
>
>
And I can see the request is being made to port 8080 instead of 8081
I can access the api in the browser with no problems
How can I debug this? | 2019/01/16 | [
"https://Stackoverflow.com/questions/54216516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671754/"
] | Your `vue.config.js` is not supposed to be in the src folder. It must be in the root of your project. Simply move the file.
The configuration reference for the server can be found here: <https://cli.vuejs.org/config/#devserver-proxy> but it seems you're actually doing it right. The file is just at the wrong folder. | it is not right, if you use proxy, your remote address must be same as request url and port, so your vue.config.js should be edited like below:
```
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
```
or you can use rewrite attribute like this :
```
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: { '^/api': '/'}
}
}
```
the difference is the real request, top will be <http://localhost:8080/api/>..., rewrite will be <http://localhost:8080/>... |
54,216,516 | I have this in `src/vue.config.js`
```
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
},
},
},
};
```
and I'm calling the api with
```
axios.get('/api/parts')
.then(result => commit('updateParts', result.data))
.catch(console.error);
```
But I just keep getting
>
> Error: "Request failed with status code 404"
>
>
>
And I can see the request is being made to port 8080 instead of 8081
I can access the api in the browser with no problems
How can I debug this? | 2019/01/16 | [
"https://Stackoverflow.com/questions/54216516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671754/"
] | it is not right, if you use proxy, your remote address must be same as request url and port, so your vue.config.js should be edited like below:
```
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
```
or you can use rewrite attribute like this :
```
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: { '^/api': '/'}
}
}
```
the difference is the real request, top will be <http://localhost:8080/api/>..., rewrite will be <http://localhost:8080/>... | I had the same issue after trying a couple of combinations finally I figured it out.
I am using `Axios` and my application is running at port `8080`
**main.js:**
`axios.defaults.baseURL = 'http://localhost:8080/api/'`
**vue.config.js**
```
module.exports = {
devServer: {
proxy: 'https://reqres.in'
}
}
```
**My Vue Component**
```
this.axios.get("users")
.then(response => {
this.items = response.data.data;
this.isLoading = false;
})
```
**Browser's Network tab:**
[![enter image description here](https://i.stack.imgur.com/J8yhm.png)](https://i.stack.imgur.com/J8yhm.png) |
240,476 | I would like to be able to write the output of Portage commands, along with other commands, that I perform in tty (that is, the screen-wide terminals started with `Ctrl`+`Alt`+`F*n*` where n represents an integer between 1 and 6. These terminals are started using the `getty` command, to my knowledge) where there is no clipboard, to a text file. Now I read on the [Ubuntu forums](http://ubuntuforums.org/showthread.php?t=1379903) that maybe the Unix command `cat` might be able to do this, if properly used. Unfortunately, following the command suggested there does not seem to add the complete output of the `emerge` command to a text file. See I ran:
```
emerge dev-qt/qtwayland > cat >> /home/fusion809/output.txt
```
where fusion809 is my username, and it only wrote four lines of output to output.txt, namely:
```
Calculating dependencies ....... .. ....... done!
[ebuild R ] media-libs/mesa-11.0.4 USE="-wayland*" ABI_X86="32*"
[ebuild R ] dev-qt/qtgui-5.5.1 USE="-egl* -evdev* -ibus*"
[ebuild R ] dev-qt/qtwayland-5.5.1 USE="-egl*"
```
I also tried:
```
emerge dev-qt/qtwayland > /home/fusion809/output.txt
```
and:
```
emerge dev-qt/qtwayland >> /home/fusion809/output.txt
```
both of which wrote the same output to output.txt. | 2015/11/03 | [
"https://unix.stackexchange.com/questions/240476",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/27613/"
] | You're on the right track. In Unix/Linux there's also an error stream. Every command gets standard input, standard output, and standard error.
You've been working with standard output. To also capture the standard error stream from the command use `2>`. For example:
```
emerge dev-qt/qtwayland > emerge.out 2> emerge.err
```
Now if you want the standard output *and* error to go into the *same* file, use `2>&1` to tell the shell to send the standard error output to the same place as the standard output:
```
emerge dev-qt/qtwayland > emerge.out 2>&1
```
Also, if you need to reference and learn more, you can always look this up in the shell man page `man sh`.
Thanks for the informative and well-thought question! | 1. you don't need the `> cat` there. in fact, that just creates another file called `cat` in the current dir. and if you meant to type `| cat`, that's superfluous, you can redirect the output without piping it through cat.
2. `emerge dev-qt/qtwayland > /home/fusion809/output.txt` will save **ALL** of the stdout output from your `emerge` command to `/home/fusion809/output.txt`. ALL of it. if there's only 4 lines in the file, that's because `emerge` only printed 4 lines to stdout.
3. emerge may have printed more stuff to `stderr`. if you want to capture that too, try `emerge dev-qt/qtwayland >& /home/fusion809/output.txt`. That redirects both stdout and stderr to the same file.
4. the difference between `>` and `>>` is that `>` erases the file if it exists before creating it, and `>>` appends to the file if it already exists or creates it if it doesn't (depending on shell options).
5. if you want to capture the output to a file **AND** see it on screen at the same time, use `tee`. For example:
`emerge dev-qt/qtwayland |& tee -a /home/fusion809/output.txt`
`tee`'s `-a` option tells it to append rather than erase and overwrite. |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | Take a line one unit long. You can divide it into n parts each of length 1/n. As n increases the parts get smaller, but at the same time to total length is always 1 unit.
The length is given by n.(1/n) and the modern mathematical concept is that the *Limit* as n *tends to infinity* of the function n.(1/n) is 1.
There's a notation for this: $\lim\_{n \to \infty} n.(1/n) = 1$
Google and read up on *limits of functions and sequences*. | It states
>
> ...then the line would **seem** to be infinitely long.
>
>
>
It is infinitely long for a very very small person who walk exactly one real number with each step. For example if she/he is on the point 0.5, then she/he must find the next real point right after (or before) 0.5. Can she/he?
But for us, who use centimeter as a measuring unit, that line would not be infinitely long. So it basically depends on the unit of length that we consider. |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | The paradox has to do with the additivity with measure; in particular, naively switching from finite additivity to infinite additivity.
We're familiar with the fact that, if we split something up into two parts, the measure of the whole is the sum of the measure of the two parts.
If we repeat this with one of the individual parts, we've now split the original whole into three parts. The measure of the whole is the sum of the individual measures of the three parts.
And so forth; *binary* additivity of measure does extend to arbitrary, but *finite* additivity of measure.
Generally speaking, things have to change when you switch from finite to infinite. We can no longer justify additivity of measure when you have infinitely many parts, because you can never get to infinitely many parts by repeatedly splitting the whole into finitely many parts finitely many times.
A priori, there might not even be a reasonable notion of additivity of measure when you have infinitely many parts! However, experience has shown there is a useful extension of additivity to *countably* many parts, at least when studying a continuum.
i.e. if you split a whole into *countably* many parts (and in a *measurable* way), you can expect the measure of the whole to be the sum of the measures of the individual parts.
Note that "sum" must be meant in the sense of an infinite sum from calculus; e.g. as a limit of partial sums. Trying to literally interpret an infinite sum as repeated addition runs into all of the same problems we're trying to work around.
When you split the whole into more than countably many parts -- e.g. you split the number line into its individual points -- you now have too many parts for countable additivity of measure. | Take a line one unit long. You can divide it into n parts each of length 1/n. As n increases the parts get smaller, but at the same time to total length is always 1 unit.
The length is given by n.(1/n) and the modern mathematical concept is that the *Limit* as n *tends to infinity* of the function n.(1/n) is 1.
There's a notation for this: $\lim\_{n \to \infty} n.(1/n) = 1$
Google and read up on *limits of functions and sequences*. |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | Take a line one unit long. You can divide it into n parts each of length 1/n. As n increases the parts get smaller, but at the same time to total length is always 1 unit.
The length is given by n.(1/n) and the modern mathematical concept is that the *Limit* as n *tends to infinity* of the function n.(1/n) is 1.
There's a notation for this: $\lim\_{n \to \infty} n.(1/n) = 1$
Google and read up on *limits of functions and sequences*. | If you divide the unit interval $[0,1]$ into $N$ equal parts where $N$ is an infinite number, each of the intervals of the subdivision will be of infinitesimal length. Thus infinitely many subintervals can indeed add to a finite length, but those subintervals can't have appreciable length: they must be infinitesimal. See related discussion at [Are infinitesimals dangerous?](https://math.stackexchange.com/questions/661999/are-infinitesimals-dangerous)
To respond the title question, "What is the answer to the paradox of the infinitesimal?", such an answer is given by a construction of a proper extension of the real number field which remains an ordered field (that's the easy part) and moreover is an elementary extension in the sense that "all" (in a suitable sense) properties of the real number field still hold for the proper extension (this requires more work). |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | Take a line one unit long. You can divide it into n parts each of length 1/n. As n increases the parts get smaller, but at the same time to total length is always 1 unit.
The length is given by n.(1/n) and the modern mathematical concept is that the *Limit* as n *tends to infinity* of the function n.(1/n) is 1.
There's a notation for this: $\lim\_{n \to \infty} n.(1/n) = 1$
Google and read up on *limits of functions and sequences*. | Its an idea that relates to how we can indefinitely count in "both directions". In other words we can count in whole steps forever, we can also do the same for the space between the steps.
Consider a ruler, we can count the 12 inches that are clearly marked out and we can count out all the lines in between the inch markings. We can keep dividing and we can imagine the idea of doing this indefinitely. Of course physical limitations will only allow us to divide things so far down.
There really are no paradoxes. These infinitesimal brain teasers rely on how the terms are defined. In other words how the sets of the mathematical system are described. Real Numbers represent the set of all numbers including fractions, decimals, and even whole numbers. This 'set' includes all the other 'sets'. A natural number is the basic 1,2,3,4 etc (or 0,1,2,3 etc). A real number would include pi or 3.3333333 or 1/5 or 1/3 etc.
The idea is that there are more real numbers than natural numbers even though both are 'infinite'. The thing is infinite means boundless. What counting means is we can count forever. The supposed paradox here has to do with confusing numerical symbols and concepts with the quantities they are supposed to represent. These quantities can be real or imagined. These quantities are things like the dimensions of a physical object or its weight, the amount of gas in your car or the amount of debt ( represented by a negative number) you owe.
The sleight of hand of this supposed paradox is the confusing of the numerical symbols and concepts with the quantities they represent. Math simply involves counting of one kind or another and the whole numbers work with the rest of the sets of numbers of the system just fine. The whole system is one numerical system and any divisions are very arbitrary in terms of making metaphysical claims of cosmic mystery paradoxes. (cosmic means order)
We can also simply convert 3.33333 to 333,333 like the metric system allows and we will have only whole numbers and no fractions. We just scale down or up. We can go to nanometers or smaller and we can go to kilometers or bigger. We do not have to resort to fractions. We can extend pi out as far as we like, 3.14159 etc can become 314 or 3142 (rounded) or 314,159 etc. We have to round pi off at some point and all this shows is the limits of math as a human tool. We only need to know what resolution we need and that is our limit. In the real world we can only measure sup to a certain 'resolution' anyway so we are physically limited from truly dividing something down indefinitely.
We can also convert whole numbers to decimal placed numbers by adding as many zero placeholders as we like: 1 becomes 1.000000000 etc.
"Cantor established the importance of one-to-one correspondence between the members of two sets, defined infinite and well-ordered sets, and proved that the real numbers are more numerous than the natural numbers. In fact, Cantor's method of proof of this theorem implies the existence of an "infinity of infinities". He defined the cardinal and ordinal numbers and their arithmetic. Cantor's work is of great philosophical interest, a fact of which he was well aware."
<https://en.wikipedia.org/wiki/Georg_Cantor> |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | The paradox has to do with the additivity with measure; in particular, naively switching from finite additivity to infinite additivity.
We're familiar with the fact that, if we split something up into two parts, the measure of the whole is the sum of the measure of the two parts.
If we repeat this with one of the individual parts, we've now split the original whole into three parts. The measure of the whole is the sum of the individual measures of the three parts.
And so forth; *binary* additivity of measure does extend to arbitrary, but *finite* additivity of measure.
Generally speaking, things have to change when you switch from finite to infinite. We can no longer justify additivity of measure when you have infinitely many parts, because you can never get to infinitely many parts by repeatedly splitting the whole into finitely many parts finitely many times.
A priori, there might not even be a reasonable notion of additivity of measure when you have infinitely many parts! However, experience has shown there is a useful extension of additivity to *countably* many parts, at least when studying a continuum.
i.e. if you split a whole into *countably* many parts (and in a *measurable* way), you can expect the measure of the whole to be the sum of the measures of the individual parts.
Note that "sum" must be meant in the sense of an infinite sum from calculus; e.g. as a limit of partial sums. Trying to literally interpret an infinite sum as repeated addition runs into all of the same problems we're trying to work around.
When you split the whole into more than countably many parts -- e.g. you split the number line into its individual points -- you now have too many parts for countable additivity of measure. | It states
>
> ...then the line would **seem** to be infinitely long.
>
>
>
It is infinitely long for a very very small person who walk exactly one real number with each step. For example if she/he is on the point 0.5, then she/he must find the next real point right after (or before) 0.5. Can she/he?
But for us, who use centimeter as a measuring unit, that line would not be infinitely long. So it basically depends on the unit of length that we consider. |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | If you divide the unit interval $[0,1]$ into $N$ equal parts where $N$ is an infinite number, each of the intervals of the subdivision will be of infinitesimal length. Thus infinitely many subintervals can indeed add to a finite length, but those subintervals can't have appreciable length: they must be infinitesimal. See related discussion at [Are infinitesimals dangerous?](https://math.stackexchange.com/questions/661999/are-infinitesimals-dangerous)
To respond the title question, "What is the answer to the paradox of the infinitesimal?", such an answer is given by a construction of a proper extension of the real number field which remains an ordered field (that's the easy part) and moreover is an elementary extension in the sense that "all" (in a suitable sense) properties of the real number field still hold for the proper extension (this requires more work). | It states
>
> ...then the line would **seem** to be infinitely long.
>
>
>
It is infinitely long for a very very small person who walk exactly one real number with each step. For example if she/he is on the point 0.5, then she/he must find the next real point right after (or before) 0.5. Can she/he?
But for us, who use centimeter as a measuring unit, that line would not be infinitely long. So it basically depends on the unit of length that we consider. |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | The paradox has to do with the additivity with measure; in particular, naively switching from finite additivity to infinite additivity.
We're familiar with the fact that, if we split something up into two parts, the measure of the whole is the sum of the measure of the two parts.
If we repeat this with one of the individual parts, we've now split the original whole into three parts. The measure of the whole is the sum of the individual measures of the three parts.
And so forth; *binary* additivity of measure does extend to arbitrary, but *finite* additivity of measure.
Generally speaking, things have to change when you switch from finite to infinite. We can no longer justify additivity of measure when you have infinitely many parts, because you can never get to infinitely many parts by repeatedly splitting the whole into finitely many parts finitely many times.
A priori, there might not even be a reasonable notion of additivity of measure when you have infinitely many parts! However, experience has shown there is a useful extension of additivity to *countably* many parts, at least when studying a continuum.
i.e. if you split a whole into *countably* many parts (and in a *measurable* way), you can expect the measure of the whole to be the sum of the measures of the individual parts.
Note that "sum" must be meant in the sense of an infinite sum from calculus; e.g. as a limit of partial sums. Trying to literally interpret an infinite sum as repeated addition runs into all of the same problems we're trying to work around.
When you split the whole into more than countably many parts -- e.g. you split the number line into its individual points -- you now have too many parts for countable additivity of measure. | If you divide the unit interval $[0,1]$ into $N$ equal parts where $N$ is an infinite number, each of the intervals of the subdivision will be of infinitesimal length. Thus infinitely many subintervals can indeed add to a finite length, but those subintervals can't have appreciable length: they must be infinitesimal. See related discussion at [Are infinitesimals dangerous?](https://math.stackexchange.com/questions/661999/are-infinitesimals-dangerous)
To respond the title question, "What is the answer to the paradox of the infinitesimal?", such an answer is given by a construction of a proper extension of the real number field which remains an ordered field (that's the easy part) and moreover is an elementary extension in the sense that "all" (in a suitable sense) properties of the real number field still hold for the proper extension (this requires more work). |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | The paradox has to do with the additivity with measure; in particular, naively switching from finite additivity to infinite additivity.
We're familiar with the fact that, if we split something up into two parts, the measure of the whole is the sum of the measure of the two parts.
If we repeat this with one of the individual parts, we've now split the original whole into three parts. The measure of the whole is the sum of the individual measures of the three parts.
And so forth; *binary* additivity of measure does extend to arbitrary, but *finite* additivity of measure.
Generally speaking, things have to change when you switch from finite to infinite. We can no longer justify additivity of measure when you have infinitely many parts, because you can never get to infinitely many parts by repeatedly splitting the whole into finitely many parts finitely many times.
A priori, there might not even be a reasonable notion of additivity of measure when you have infinitely many parts! However, experience has shown there is a useful extension of additivity to *countably* many parts, at least when studying a continuum.
i.e. if you split a whole into *countably* many parts (and in a *measurable* way), you can expect the measure of the whole to be the sum of the measures of the individual parts.
Note that "sum" must be meant in the sense of an infinite sum from calculus; e.g. as a limit of partial sums. Trying to literally interpret an infinite sum as repeated addition runs into all of the same problems we're trying to work around.
When you split the whole into more than countably many parts -- e.g. you split the number line into its individual points -- you now have too many parts for countable additivity of measure. | Its an idea that relates to how we can indefinitely count in "both directions". In other words we can count in whole steps forever, we can also do the same for the space between the steps.
Consider a ruler, we can count the 12 inches that are clearly marked out and we can count out all the lines in between the inch markings. We can keep dividing and we can imagine the idea of doing this indefinitely. Of course physical limitations will only allow us to divide things so far down.
There really are no paradoxes. These infinitesimal brain teasers rely on how the terms are defined. In other words how the sets of the mathematical system are described. Real Numbers represent the set of all numbers including fractions, decimals, and even whole numbers. This 'set' includes all the other 'sets'. A natural number is the basic 1,2,3,4 etc (or 0,1,2,3 etc). A real number would include pi or 3.3333333 or 1/5 or 1/3 etc.
The idea is that there are more real numbers than natural numbers even though both are 'infinite'. The thing is infinite means boundless. What counting means is we can count forever. The supposed paradox here has to do with confusing numerical symbols and concepts with the quantities they are supposed to represent. These quantities can be real or imagined. These quantities are things like the dimensions of a physical object or its weight, the amount of gas in your car or the amount of debt ( represented by a negative number) you owe.
The sleight of hand of this supposed paradox is the confusing of the numerical symbols and concepts with the quantities they represent. Math simply involves counting of one kind or another and the whole numbers work with the rest of the sets of numbers of the system just fine. The whole system is one numerical system and any divisions are very arbitrary in terms of making metaphysical claims of cosmic mystery paradoxes. (cosmic means order)
We can also simply convert 3.33333 to 333,333 like the metric system allows and we will have only whole numbers and no fractions. We just scale down or up. We can go to nanometers or smaller and we can go to kilometers or bigger. We do not have to resort to fractions. We can extend pi out as far as we like, 3.14159 etc can become 314 or 3142 (rounded) or 314,159 etc. We have to round pi off at some point and all this shows is the limits of math as a human tool. We only need to know what resolution we need and that is our limit. In the real world we can only measure sup to a certain 'resolution' anyway so we are physically limited from truly dividing something down indefinitely.
We can also convert whole numbers to decimal placed numbers by adding as many zero placeholders as we like: 1 becomes 1.000000000 etc.
"Cantor established the importance of one-to-one correspondence between the members of two sets, defined infinite and well-ordered sets, and proved that the real numbers are more numerous than the natural numbers. In fact, Cantor's method of proof of this theorem implies the existence of an "infinity of infinities". He defined the cardinal and ordinal numbers and their arithmetic. Cantor's work is of great philosophical interest, a fact of which he was well aware."
<https://en.wikipedia.org/wiki/Georg_Cantor> |
771,952 | I just read [this article](http://www.npr.org/2014/04/20/303716795/far-from-infinitesimal-a-mathematical-paradoxs-role-in-history) on npr, which mentioned the following question:
>
> You can keep on dividing forever, so every line has an infinite amount
> of parts. But how long are those parts? If they're anything greater
> than zero, then the line would seem to be infinitely long. And if
> they're zero, well, then no matter how many parts there are, the
> length of the line would still be zero.
>
>
>
It further mentions that
>
> Today, mathematicians have found ways to answer that question so that
> modern calculus is rigorous and reliable.
>
>
>
Can anyone elaborate on the modern answers to this question? | 2014/04/27 | [
"https://math.stackexchange.com/questions/771952",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21006/"
] | If you divide the unit interval $[0,1]$ into $N$ equal parts where $N$ is an infinite number, each of the intervals of the subdivision will be of infinitesimal length. Thus infinitely many subintervals can indeed add to a finite length, but those subintervals can't have appreciable length: they must be infinitesimal. See related discussion at [Are infinitesimals dangerous?](https://math.stackexchange.com/questions/661999/are-infinitesimals-dangerous)
To respond the title question, "What is the answer to the paradox of the infinitesimal?", such an answer is given by a construction of a proper extension of the real number field which remains an ordered field (that's the easy part) and moreover is an elementary extension in the sense that "all" (in a suitable sense) properties of the real number field still hold for the proper extension (this requires more work). | Its an idea that relates to how we can indefinitely count in "both directions". In other words we can count in whole steps forever, we can also do the same for the space between the steps.
Consider a ruler, we can count the 12 inches that are clearly marked out and we can count out all the lines in between the inch markings. We can keep dividing and we can imagine the idea of doing this indefinitely. Of course physical limitations will only allow us to divide things so far down.
There really are no paradoxes. These infinitesimal brain teasers rely on how the terms are defined. In other words how the sets of the mathematical system are described. Real Numbers represent the set of all numbers including fractions, decimals, and even whole numbers. This 'set' includes all the other 'sets'. A natural number is the basic 1,2,3,4 etc (or 0,1,2,3 etc). A real number would include pi or 3.3333333 or 1/5 or 1/3 etc.
The idea is that there are more real numbers than natural numbers even though both are 'infinite'. The thing is infinite means boundless. What counting means is we can count forever. The supposed paradox here has to do with confusing numerical symbols and concepts with the quantities they are supposed to represent. These quantities can be real or imagined. These quantities are things like the dimensions of a physical object or its weight, the amount of gas in your car or the amount of debt ( represented by a negative number) you owe.
The sleight of hand of this supposed paradox is the confusing of the numerical symbols and concepts with the quantities they represent. Math simply involves counting of one kind or another and the whole numbers work with the rest of the sets of numbers of the system just fine. The whole system is one numerical system and any divisions are very arbitrary in terms of making metaphysical claims of cosmic mystery paradoxes. (cosmic means order)
We can also simply convert 3.33333 to 333,333 like the metric system allows and we will have only whole numbers and no fractions. We just scale down or up. We can go to nanometers or smaller and we can go to kilometers or bigger. We do not have to resort to fractions. We can extend pi out as far as we like, 3.14159 etc can become 314 or 3142 (rounded) or 314,159 etc. We have to round pi off at some point and all this shows is the limits of math as a human tool. We only need to know what resolution we need and that is our limit. In the real world we can only measure sup to a certain 'resolution' anyway so we are physically limited from truly dividing something down indefinitely.
We can also convert whole numbers to decimal placed numbers by adding as many zero placeholders as we like: 1 becomes 1.000000000 etc.
"Cantor established the importance of one-to-one correspondence between the members of two sets, defined infinite and well-ordered sets, and proved that the real numbers are more numerous than the natural numbers. In fact, Cantor's method of proof of this theorem implies the existence of an "infinity of infinities". He defined the cardinal and ordinal numbers and their arithmetic. Cantor's work is of great philosophical interest, a fact of which he was well aware."
<https://en.wikipedia.org/wiki/Georg_Cantor> |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | It appears someone else had the same problem. It was solved using the function `execSQL` instead of `rawQuery` to update the field.
You can read about it here: [Increase the value of a record in android/sqlite database](https://stackoverflow.com/questions/3427516/increase-the-value-of-a-record-in-android-sqlite-database/3432777#3432777) | chnge your UPDATE query as:
```
int newcount=SMS_SENT+1;
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+
SMS_SENT + " = " + newcount + "", null);
^^^^^
```
and make sure `SMS_SENT` is String column name not an number |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | Following good database design it is almost always a good idea to have a field **`ID`** with an integer data type and have that value auto increment in an effort to create unique records. For your particular problem it can be easily solved by just adding an **`ID`** column and set it to an **`INTEGER`** data type and not **`INT`** as you would do with high-performance databases like (Postgresql, MySQL, etc...). Try changing your schema to something like this and it should do the trick:
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY, " +
PHONE_NUMBER + " TEXT, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);"
);
```
All you have to do now is just pass in the values for `PHONE_NUMBER`, `SMS_SENT`, `SMS_RECEIVED` and your counter (the `ID` field) should start to increment accordingly. For more information you can check out this [post](http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example). | chnge your UPDATE query as:
```
int newcount=SMS_SENT+1;
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+
SMS_SENT + " = " + newcount + "", null);
^^^^^
```
and make sure `SMS_SENT` is String column name not an number |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | I solved it in the following way:
```
ContentValues args = new ContentValues();
args.put(SMS_SENT, sent+1);
db.update(TABLE_NAME, args, ID, new String[] {"id_value"});
``` | It appears someone else had the same problem. It was solved using the function `execSQL` instead of `rawQuery` to update the field.
You can read about it here: [Increase the value of a record in android/sqlite database](https://stackoverflow.com/questions/3427516/increase-the-value-of-a-record-in-android-sqlite-database/3432777#3432777) |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | The update sql statement is missing a where clause so would update all rows. Try this:
```
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT
+ " = " + SMS_SENT + "+1 WHERE " + PHONE_NUMBER
+ " = '" + phoneNumber +"'", null);
``` | Try this,
While creating table use `INTEGER` instead of `INT`. It should work.
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);");
``` |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | Following good database design it is almost always a good idea to have a field **`ID`** with an integer data type and have that value auto increment in an effort to create unique records. For your particular problem it can be easily solved by just adding an **`ID`** column and set it to an **`INTEGER`** data type and not **`INT`** as you would do with high-performance databases like (Postgresql, MySQL, etc...). Try changing your schema to something like this and it should do the trick:
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY, " +
PHONE_NUMBER + " TEXT, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);"
);
```
All you have to do now is just pass in the values for `PHONE_NUMBER`, `SMS_SENT`, `SMS_RECEIVED` and your counter (the `ID` field) should start to increment accordingly. For more information you can check out this [post](http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example). | Try this,
While creating table use `INTEGER` instead of `INT`. It should work.
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);");
``` |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | The update sql statement is missing a where clause so would update all rows. Try this:
```
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT
+ " = " + SMS_SENT + "+1 WHERE " + PHONE_NUMBER
+ " = '" + phoneNumber +"'", null);
``` | chnge your UPDATE query as:
```
int newcount=SMS_SENT+1;
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+
SMS_SENT + " = " + newcount + "", null);
^^^^^
```
and make sure `SMS_SENT` is String column name not an number |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | Try this,
While creating table use `INTEGER` instead of `INT`. It should work.
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);");
``` | chnge your UPDATE query as:
```
int newcount=SMS_SENT+1;
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+
SMS_SENT + " = " + newcount + "", null);
^^^^^
```
and make sure `SMS_SENT` is String column name not an number |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | I solved it in the following way:
```
ContentValues args = new ContentValues();
args.put(SMS_SENT, sent+1);
db.update(TABLE_NAME, args, ID, new String[] {"id_value"});
``` | chnge your UPDATE query as:
```
int newcount=SMS_SENT+1;
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+
SMS_SENT + " = " + newcount + "", null);
^^^^^
```
and make sure `SMS_SENT` is String column name not an number |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | I solved it in the following way:
```
ContentValues args = new ContentValues();
args.put(SMS_SENT, sent+1);
db.update(TABLE_NAME, args, ID, new String[] {"id_value"});
``` | Try this,
While creating table use `INTEGER` instead of `INT`. It should work.
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);");
``` |
14,219,072 | I have a database in which I am storing the number of sent messages. However, when I send a message, the counter is not incremented.
This is the database class (usersdata):
```
import static android.provider.BaseColumns._ID;
import static com.app.Constants.TABLE_NAME;
import static com.app.Constants.PHONE_NUMBER;
import static com.app.Constants.SMS_SENT;
import static com.app.Constants.SMS_RECEIVED;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UsersData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rpgsms.db";
private static final int DATABASE_VERSION = 1;
public UsersData (Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
PHONE_NUMBER + " TEXT PRIMARY KEY, " +
SMS_SENT + " INT, " +
SMS_RECEIVED + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
In another class I want to update the `SMS_SENT` field, and I'm doing it like this:
```
usersData = new UsersData(this);
SQLiteDatabase db = usersData.getWritableDatabase();
db.rawQuery("UPDATE "+ TABLE_NAME + " SET "+ SMS_SENT + " = " + SMS_SENT + "+1", null);
```
However, this does not update the corresponding field. What am I doing wrong? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14219072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301428/"
] | I solved it in the following way:
```
ContentValues args = new ContentValues();
args.put(SMS_SENT, sent+1);
db.update(TABLE_NAME, args, ID, new String[] {"id_value"});
``` | Following good database design it is almost always a good idea to have a field **`ID`** with an integer data type and have that value auto increment in an effort to create unique records. For your particular problem it can be easily solved by just adding an **`ID`** column and set it to an **`INTEGER`** data type and not **`INT`** as you would do with high-performance databases like (Postgresql, MySQL, etc...). Try changing your schema to something like this and it should do the trick:
```
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY, " +
PHONE_NUMBER + " TEXT, " +
SMS_SENT + " INTEGER, " +
SMS_RECEIVED + " INTEGER);"
);
```
All you have to do now is just pass in the values for `PHONE_NUMBER`, `SMS_SENT`, `SMS_RECEIVED` and your counter (the `ID` field) should start to increment accordingly. For more information you can check out this [post](http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example). |
20,202,469 | Using this code/method, I have finally got JQuery Mobile collapsible styling to be applied to data pulled from an XML file - but I can't get ALL Jquery styling to work, such as the icon, which doesn't work. I want data-collapsed-icon to be set to arrow-u, for example. This works in static code, but not when I'm working dynamically with an XML/JSON file. Any ideas how I get the icon styling to work?
```
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "jargon.xml",
dataType: "xml",
success: function(xml) {
var container = document.getElementById("catalogue");
container.setAttribute('data-role', 'collapsible-set');
container.setAttribute('data-collapsed', 'true');
$(xml).find('release').each(function(){
var release = document.createElement("div");
release.setAttribute('data-role', 'collapsible');
release.setAttribute('data-collapsed', 'true');
var cat = $(this).find('cat').text();
var title = $(this).find('title:first').text();
var artist = $(this).find('artist').text();
var tracks = "";
$(this).find('track').each(function(){
tracks = tracks + $(this).find('title').text() + "<br>";
});
release.innerHTML = "<h3>" + cat + "<br></h3><p>" + artist + "</p>";
container.appendChild(release);
});
var catDiv = $('#catalogue');
catDiv.find('div[data-role=collapsible]').collapsible({theme:'b',refresh:true});
}
});
});
</script>
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872353/"
] | It looks like you can use [regular expressions](http://docs.oracle.com/cd/B28359_01/appdev.111/b28424/adfns_regexp.htm#i1007663) in your query, like so:
```
SELECT ID FROM table WHERE REGEXP_LIKE(zeroes, '^0+$')
``` | Assuming that the column only has numbers, then you might want to try and `CAST` it to an `INT`:
```
SELECT *
FROM YourTable
WHERE CAST(YourColumn AS INT) = 0
``` |
20,202,469 | Using this code/method, I have finally got JQuery Mobile collapsible styling to be applied to data pulled from an XML file - but I can't get ALL Jquery styling to work, such as the icon, which doesn't work. I want data-collapsed-icon to be set to arrow-u, for example. This works in static code, but not when I'm working dynamically with an XML/JSON file. Any ideas how I get the icon styling to work?
```
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "jargon.xml",
dataType: "xml",
success: function(xml) {
var container = document.getElementById("catalogue");
container.setAttribute('data-role', 'collapsible-set');
container.setAttribute('data-collapsed', 'true');
$(xml).find('release').each(function(){
var release = document.createElement("div");
release.setAttribute('data-role', 'collapsible');
release.setAttribute('data-collapsed', 'true');
var cat = $(this).find('cat').text();
var title = $(this).find('title:first').text();
var artist = $(this).find('artist').text();
var tracks = "";
$(this).find('track').each(function(){
tracks = tracks + $(this).find('title').text() + "<br>";
});
release.innerHTML = "<h3>" + cat + "<br></h3><p>" + artist + "</p>";
container.appendChild(release);
});
var catDiv = $('#catalogue');
catDiv.find('div[data-role=collapsible]').collapsible({theme:'b',refresh:true});
}
});
});
</script>
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872353/"
] | It looks like you can use [regular expressions](http://docs.oracle.com/cd/B28359_01/appdev.111/b28424/adfns_regexp.htm#i1007663) in your query, like so:
```
SELECT ID FROM table WHERE REGEXP_LIKE(zeroes, '^0+$')
``` | Check that the string contains any character, and after removing all zeroes contains no characters:
```
where length(field) > 0 and length(replace(field, '0', '')) = 0
```
If the value can never be an empty string, you can skip the first test:
```
where length(replace(field, '0', '')) = 0
``` |
20,202,469 | Using this code/method, I have finally got JQuery Mobile collapsible styling to be applied to data pulled from an XML file - but I can't get ALL Jquery styling to work, such as the icon, which doesn't work. I want data-collapsed-icon to be set to arrow-u, for example. This works in static code, but not when I'm working dynamically with an XML/JSON file. Any ideas how I get the icon styling to work?
```
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "jargon.xml",
dataType: "xml",
success: function(xml) {
var container = document.getElementById("catalogue");
container.setAttribute('data-role', 'collapsible-set');
container.setAttribute('data-collapsed', 'true');
$(xml).find('release').each(function(){
var release = document.createElement("div");
release.setAttribute('data-role', 'collapsible');
release.setAttribute('data-collapsed', 'true');
var cat = $(this).find('cat').text();
var title = $(this).find('title:first').text();
var artist = $(this).find('artist').text();
var tracks = "";
$(this).find('track').each(function(){
tracks = tracks + $(this).find('title').text() + "<br>";
});
release.innerHTML = "<h3>" + cat + "<br></h3><p>" + artist + "</p>";
container.appendChild(release);
});
var catDiv = $('#catalogue');
catDiv.find('div[data-role=collapsible]').collapsible({theme:'b',refresh:true});
}
});
});
</script>
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872353/"
] | It looks like you can use [regular expressions](http://docs.oracle.com/cd/B28359_01/appdev.111/b28424/adfns_regexp.htm#i1007663) in your query, like so:
```
SELECT ID FROM table WHERE REGEXP_LIKE(zeroes, '^0+$')
``` | Checking that a field only contains characters from a limited subset can be done using the 'translate' function.
Example:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0', 'x')), 0) = 0
```
The translate in this case replaces 'x' by 'x' (does nothing with the 'x') and removes all other characters listed, in this case '0'. The result may be null, so a coalesce (ANSI variant of nvl) is needed.
This example can be extended to wider use, for example to list all fields that have non-numeric characters:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0123456789', 'x')), 0) != 0
``` |
20,202,469 | Using this code/method, I have finally got JQuery Mobile collapsible styling to be applied to data pulled from an XML file - but I can't get ALL Jquery styling to work, such as the icon, which doesn't work. I want data-collapsed-icon to be set to arrow-u, for example. This works in static code, but not when I'm working dynamically with an XML/JSON file. Any ideas how I get the icon styling to work?
```
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "jargon.xml",
dataType: "xml",
success: function(xml) {
var container = document.getElementById("catalogue");
container.setAttribute('data-role', 'collapsible-set');
container.setAttribute('data-collapsed', 'true');
$(xml).find('release').each(function(){
var release = document.createElement("div");
release.setAttribute('data-role', 'collapsible');
release.setAttribute('data-collapsed', 'true');
var cat = $(this).find('cat').text();
var title = $(this).find('title:first').text();
var artist = $(this).find('artist').text();
var tracks = "";
$(this).find('track').each(function(){
tracks = tracks + $(this).find('title').text() + "<br>";
});
release.innerHTML = "<h3>" + cat + "<br></h3><p>" + artist + "</p>";
container.appendChild(release);
});
var catDiv = $('#catalogue');
catDiv.find('div[data-role=collapsible]').collapsible({theme:'b',refresh:true});
}
});
});
</script>
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872353/"
] | Assuming that the column only has numbers, then you might want to try and `CAST` it to an `INT`:
```
SELECT *
FROM YourTable
WHERE CAST(YourColumn AS INT) = 0
``` | Checking that a field only contains characters from a limited subset can be done using the 'translate' function.
Example:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0', 'x')), 0) = 0
```
The translate in this case replaces 'x' by 'x' (does nothing with the 'x') and removes all other characters listed, in this case '0'. The result may be null, so a coalesce (ANSI variant of nvl) is needed.
This example can be extended to wider use, for example to list all fields that have non-numeric characters:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0123456789', 'x')), 0) != 0
``` |
20,202,469 | Using this code/method, I have finally got JQuery Mobile collapsible styling to be applied to data pulled from an XML file - but I can't get ALL Jquery styling to work, such as the icon, which doesn't work. I want data-collapsed-icon to be set to arrow-u, for example. This works in static code, but not when I'm working dynamically with an XML/JSON file. Any ideas how I get the icon styling to work?
```
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "jargon.xml",
dataType: "xml",
success: function(xml) {
var container = document.getElementById("catalogue");
container.setAttribute('data-role', 'collapsible-set');
container.setAttribute('data-collapsed', 'true');
$(xml).find('release').each(function(){
var release = document.createElement("div");
release.setAttribute('data-role', 'collapsible');
release.setAttribute('data-collapsed', 'true');
var cat = $(this).find('cat').text();
var title = $(this).find('title:first').text();
var artist = $(this).find('artist').text();
var tracks = "";
$(this).find('track').each(function(){
tracks = tracks + $(this).find('title').text() + "<br>";
});
release.innerHTML = "<h3>" + cat + "<br></h3><p>" + artist + "</p>";
container.appendChild(release);
});
var catDiv = $('#catalogue');
catDiv.find('div[data-role=collapsible]').collapsible({theme:'b',refresh:true});
}
});
});
</script>
``` | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872353/"
] | Check that the string contains any character, and after removing all zeroes contains no characters:
```
where length(field) > 0 and length(replace(field, '0', '')) = 0
```
If the value can never be an empty string, you can skip the first test:
```
where length(replace(field, '0', '')) = 0
``` | Checking that a field only contains characters from a limited subset can be done using the 'translate' function.
Example:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0', 'x')), 0) = 0
```
The translate in this case replaces 'x' by 'x' (does nothing with the 'x') and removes all other characters listed, in this case '0'. The result may be null, so a coalesce (ANSI variant of nvl) is needed.
This example can be extended to wider use, for example to list all fields that have non-numeric characters:
```
select t.FIELD
from TABLE t
where coalesce(length(translate(t.FIELD, 'x0123456789', 'x')), 0) != 0
``` |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | Here's a version of steenslag's that works when the arrays aren't the same size:
```
size = h.values.max_by { |a| a.length }.length
m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
```
`nil` seems like a reasonable placeholder for missing values but you can, of course, use whatever makes sense.
For example:
```
>> h = {:a => [1, 2, 3], :b => [4, 5, 6, 7, 8], :c => [9]}
>> size = h.values.max_by { |a| a.length }.length
>> m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
=> [[:a, :b, :c], [1, 4, 9], [2, 5, nil], [3, 6, nil], [nil, 7, nil], [nil, 8, nil]]
>> m.each { |r| puts r.map { |x| x.nil?? '' : x }.inspect }
[:a, :b, :c]
[ 1, 4, 9]
[ 2, 5, ""]
[ 3, 6, ""]
["", 7, ""]
["", 8, ""]
``` | ```
h = {:a => [1, 2, 3], :b => [4, 5, 6], :c => [7, 8, 9]}
p h.values.transpose.insert(0, h.keys)
# [[:a, :b, :c], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
``` |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | ```
h = {:a => [1, 2, 3], :b => [4, 5, 6], :c => [7, 8, 9]}
p h.values.transpose.insert(0, h.keys)
# [[:a, :b, :c], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
``` | No, there's no built-in function. Here's a code that would format it as you want it:
```
data = { :keyA => [123, 125, 4456], :keyB => [234000], :keyC => [345, 347] }
length = data.values.max_by{ |v| v.length }.length
widths = {}
data.keys.each do |key|
widths[key] = 5 # minimum column width
# longest string len of values
val_len = data[key].max_by{ |v| v.to_s.length }.to_s.length
widths[key] = (val_len > widths[key]) ? val_len : widths[key]
# length of key
widths[key] = (key.to_s.length > widths[key]) ? key.to_s.length : widths[key]
end
result = ""
data.keys.each {|key| result += key.to_s.ljust(widths[key]) + " " }
result += "\n"
for i in 0.upto(length)
data.keys.each { |key| result += data[key][i].to_s.ljust(widths[key]) + " " }
result += "\n"
end
# TODO write result to file...
```
Any comments and edits to refine the answer are very welcome. |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | Try this gem I wrote (prints hashes, ruby objects, ActiveRecord objects in tables): <http://github.com/arches/table_print> | ```
h = {:a => [1, 2, 3], :b => [4, 5, 6], :c => [7, 8, 9]}
p h.values.transpose.insert(0, h.keys)
# [[:a, :b, :c], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
``` |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | Here's a version of steenslag's that works when the arrays aren't the same size:
```
size = h.values.max_by { |a| a.length }.length
m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
```
`nil` seems like a reasonable placeholder for missing values but you can, of course, use whatever makes sense.
For example:
```
>> h = {:a => [1, 2, 3], :b => [4, 5, 6, 7, 8], :c => [9]}
>> size = h.values.max_by { |a| a.length }.length
>> m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
=> [[:a, :b, :c], [1, 4, 9], [2, 5, nil], [3, 6, nil], [nil, 7, nil], [nil, 8, nil]]
>> m.each { |r| puts r.map { |x| x.nil?? '' : x }.inspect }
[:a, :b, :c]
[ 1, 4, 9]
[ 2, 5, ""]
[ 3, 6, ""]
["", 7, ""]
["", 8, ""]
``` | No, there's no built-in function. Here's a code that would format it as you want it:
```
data = { :keyA => [123, 125, 4456], :keyB => [234000], :keyC => [345, 347] }
length = data.values.max_by{ |v| v.length }.length
widths = {}
data.keys.each do |key|
widths[key] = 5 # minimum column width
# longest string len of values
val_len = data[key].max_by{ |v| v.to_s.length }.to_s.length
widths[key] = (val_len > widths[key]) ? val_len : widths[key]
# length of key
widths[key] = (key.to_s.length > widths[key]) ? key.to_s.length : widths[key]
end
result = ""
data.keys.each {|key| result += key.to_s.ljust(widths[key]) + " " }
result += "\n"
for i in 0.upto(length)
data.keys.each { |key| result += data[key][i].to_s.ljust(widths[key]) + " " }
result += "\n"
end
# TODO write result to file...
```
Any comments and edits to refine the answer are very welcome. |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | Here's a version of steenslag's that works when the arrays aren't the same size:
```
size = h.values.max_by { |a| a.length }.length
m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
```
`nil` seems like a reasonable placeholder for missing values but you can, of course, use whatever makes sense.
For example:
```
>> h = {:a => [1, 2, 3], :b => [4, 5, 6, 7, 8], :c => [9]}
>> size = h.values.max_by { |a| a.length }.length
>> m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
=> [[:a, :b, :c], [1, 4, 9], [2, 5, nil], [3, 6, nil], [nil, 7, nil], [nil, 8, nil]]
>> m.each { |r| puts r.map { |x| x.nil?? '' : x }.inspect }
[:a, :b, :c]
[ 1, 4, 9]
[ 2, 5, ""]
[ 3, 6, ""]
["", 7, ""]
["", 8, ""]
``` | Try this gem I wrote (prints hashes, ruby objects, ActiveRecord objects in tables): <http://github.com/arches/table_print> |
7,904,275 | Is there a way to quickly print a ruby hash in a table format into a file?
Such as:
```
keyA keyB keyC ...
123 234 345
125 347
4456
...
```
where the values of the hash are arrays of different sizes. Or is using a double loop the only way?
Thanks | 2011/10/26 | [
"https://Stackoverflow.com/questions/7904275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677712/"
] | Try this gem I wrote (prints hashes, ruby objects, ActiveRecord objects in tables): <http://github.com/arches/table_print> | No, there's no built-in function. Here's a code that would format it as you want it:
```
data = { :keyA => [123, 125, 4456], :keyB => [234000], :keyC => [345, 347] }
length = data.values.max_by{ |v| v.length }.length
widths = {}
data.keys.each do |key|
widths[key] = 5 # minimum column width
# longest string len of values
val_len = data[key].max_by{ |v| v.to_s.length }.to_s.length
widths[key] = (val_len > widths[key]) ? val_len : widths[key]
# length of key
widths[key] = (key.to_s.length > widths[key]) ? key.to_s.length : widths[key]
end
result = ""
data.keys.each {|key| result += key.to_s.ljust(widths[key]) + " " }
result += "\n"
for i in 0.upto(length)
data.keys.each { |key| result += data[key][i].to_s.ljust(widths[key]) + " " }
result += "\n"
end
# TODO write result to file...
```
Any comments and edits to refine the answer are very welcome. |
8,472,234 | I am creating an app for android using openGL ES. I am trying to draw, in 2D, lots of moving sprites which bounce around the screen.
Let's consider I have a ball at coordinates 100,100. The ball graphic is 10px wide, therefore I can create the vertices `boundingBox = {100,110,0, 110,110,0, 100,100,0, 110,100,0}` and perform the following on each loop of `onDrawFrame()` with the ball texture loaded.
```
//for each ball object
FloatBuffer ballVertexBuffer = byteBuffer.asFloatBuffer();
ballVertexBuffer.put(ball.boundingBox);
ballVertexBuffer.position(0);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, ballVertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0,4);
```
I would then update the `boundingBox` array to move the balls around the screen.
Alternatively, I could not alter the `bounding box` at all and instead `translatef()` the ball before drawing the verticies
```
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, ballVertexBuffer);
gl.glPushMatrix();
gl.glTranslatef(ball.posX, ball.posY, 0);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0,4);
gl.glPopMatrix();
```
What would be the best thing to do in the case in terms of efficient and best practices. | 2011/12/12 | [
"https://Stackoverflow.com/questions/8472234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093404/"
] | OpenGL ES (as of 2.0) does **not** support instancing, unluckily. If it did, I would recommend drawing a 2-triangle sprite instanced *N* times, reading the x/y offsets of the center point, and possibly a scale value if you need differently sized sprites, from a vertex texture (which ES supports just fine). This would limit the amount of data you must push per frame to a minimum.
Assuming you can't do the simulation directly on the GPU (thus avoiding uploading the vertex data each frame) ... this basically leaves you only with only one efficient option:
Generate 2 VBOs, map one and fill it, while the other is used as the source of the draw call. You can also do this *seemingly* with a single buffer if you `glBufferData(... 0)` in between, which tells OpenGL to generate a new buffer and throw the old one away as soon as it's done reading from it.
Streaming vertices in every frame may not be super fast, but this does not matter as long as the latency can be well-hidden (e.g. by drawing from one buffer while filling another). Few draw calls, few state changes, and ideally no stalls should still make this fast. | Drawing calls are much more expensive than altering the data. Also glTranslate is not nearly as efficient as just adding a few numbers, after all it has to go through a full 4×4 matrix multiplication, which is 64 scalar multiplies and 16 scalar additions.
Of course the best method is using some form of instancing. |
82,995 | I have small dot matrix printing device that I'm trying to control (i.e. print to) with a Parallax Propeller board. (See images below.) It's the printer from this: <http://shop.usa.canon.com/shop/en/catalog/calculators/palm-printing-calculators/p23-dhv>
Is anyone familiar with how one of these things works? I don't see any chips or other electronics on it, so I assume it's just stepping motor control. It seems like I can get specs on the large silver motor from here: <http://www.standardmotor.net/sc_webcat/ecat/product_browse_list.php?lang=1&cat=205> but don't know on the rest.
It would be great if there were some sort of "driver" for this for use from Propeller Spin code, but I realize that most likely doesn't exist. If I could at least find some specifications that would describe what I need to send to it, I'd be happy. (Trying to guess what I need to send to each individual motor to get the right output sounds like a rather difficult way of approaching the problem, was hoping there was some sort of documentation or standardized "protocol" that might exist for the overall unit. Definitely have googled a lot to no avail.)
Just looking for some help to point me in the right direction here. I am familiar with the Propeller chip, software development (my main gig), and basic electronics concepts. Never tried to do motor control before.
![top view](https://i.stack.imgur.com/P3e5I.jpg)
![bottom view](https://i.stack.imgur.com/S7bW7.jpg)
![side panel](https://i.stack.imgur.com/GufTv.jpg) | 2013/09/21 | [
"https://electronics.stackexchange.com/questions/82995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27688/"
] | I haven't used anything similar but these are my observations based on the photo:
* It appears to be a standard DC motor not a stepper motor. So to get it to move left and right you'd need to reverse power to the motor.
* On the first photo I'm guessing the wires going to the left are to indicate the end of travel on that end, although the mechanism isn't clear from the photo.
* The right hand side appears to be for the print head. It's hard to make out when assembled what contacts would touch each other on the last photo, but I guess the two inner pins make continual contact with the inner PCB trace, and the right-most make continual contact with the outer trace so that would be power for the print head.
* The left-most pin appears in the same area appears to be for position feedback by making contact with the 'spokes' on the PCB as it turns around.
You'd need to determine the voltage everything requires, for the motor you could just turn up the voltage until it appeared to be moving at a reasonable rate. For the print head you could do the same until it appeared to be leaving a solid line as the motor moves.
I'm not sure how much effort you're prepared to put into it but the other steps I can think of you'd need to perform are:
* Design an H bridge to allow the motor to be moved in each direction.
* Use a FET to drive the print head.
* Connect the two position feedback lines to inputs.
* Write software to keep track of where everything is and get the timing right.
* Find or make font tables to be able to print text using the device.
* Make a suitable paper feeder as this doesn't appear to have one. | Here's my suggested course of action
1. Check the number and type of battery in the calculator. Work out it's max operating voltage. e.g. 4 x AA = 6V.
2. In the top photo assume connections are
* 1&2 shorted when rotor at 0-5 degrees position
* 3&4 shorted when rotor at 360/14 degree positions (next line print position?)
* 5&6 motor drive +/- <=6V
* 7&8 shorted when print head hits left end.
I'd use a multimeter to test these assumptions. |
82,995 | I have small dot matrix printing device that I'm trying to control (i.e. print to) with a Parallax Propeller board. (See images below.) It's the printer from this: <http://shop.usa.canon.com/shop/en/catalog/calculators/palm-printing-calculators/p23-dhv>
Is anyone familiar with how one of these things works? I don't see any chips or other electronics on it, so I assume it's just stepping motor control. It seems like I can get specs on the large silver motor from here: <http://www.standardmotor.net/sc_webcat/ecat/product_browse_list.php?lang=1&cat=205> but don't know on the rest.
It would be great if there were some sort of "driver" for this for use from Propeller Spin code, but I realize that most likely doesn't exist. If I could at least find some specifications that would describe what I need to send to it, I'd be happy. (Trying to guess what I need to send to each individual motor to get the right output sounds like a rather difficult way of approaching the problem, was hoping there was some sort of documentation or standardized "protocol" that might exist for the overall unit. Definitely have googled a lot to no avail.)
Just looking for some help to point me in the right direction here. I am familiar with the Propeller chip, software development (my main gig), and basic electronics concepts. Never tried to do motor control before.
![top view](https://i.stack.imgur.com/P3e5I.jpg)
![bottom view](https://i.stack.imgur.com/S7bW7.jpg)
![side panel](https://i.stack.imgur.com/GufTv.jpg) | 2013/09/21 | [
"https://electronics.stackexchange.com/questions/82995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27688/"
] | I haven't used anything similar but these are my observations based on the photo:
* It appears to be a standard DC motor not a stepper motor. So to get it to move left and right you'd need to reverse power to the motor.
* On the first photo I'm guessing the wires going to the left are to indicate the end of travel on that end, although the mechanism isn't clear from the photo.
* The right hand side appears to be for the print head. It's hard to make out when assembled what contacts would touch each other on the last photo, but I guess the two inner pins make continual contact with the inner PCB trace, and the right-most make continual contact with the outer trace so that would be power for the print head.
* The left-most pin appears in the same area appears to be for position feedback by making contact with the 'spokes' on the PCB as it turns around.
You'd need to determine the voltage everything requires, for the motor you could just turn up the voltage until it appeared to be moving at a reasonable rate. For the print head you could do the same until it appeared to be leaving a solid line as the motor moves.
I'm not sure how much effort you're prepared to put into it but the other steps I can think of you'd need to perform are:
* Design an H bridge to allow the motor to be moved in each direction.
* Use a FET to drive the print head.
* Connect the two position feedback lines to inputs.
* Write software to keep track of where everything is and get the timing right.
* Find or make font tables to be able to print text using the device.
* Make a suitable paper feeder as this doesn't appear to have one. | here is what you're looking for
<http://www.elektronik-kompendium.de/public/arnerossius/bastel/m31a.htm> |
82,995 | I have small dot matrix printing device that I'm trying to control (i.e. print to) with a Parallax Propeller board. (See images below.) It's the printer from this: <http://shop.usa.canon.com/shop/en/catalog/calculators/palm-printing-calculators/p23-dhv>
Is anyone familiar with how one of these things works? I don't see any chips or other electronics on it, so I assume it's just stepping motor control. It seems like I can get specs on the large silver motor from here: <http://www.standardmotor.net/sc_webcat/ecat/product_browse_list.php?lang=1&cat=205> but don't know on the rest.
It would be great if there were some sort of "driver" for this for use from Propeller Spin code, but I realize that most likely doesn't exist. If I could at least find some specifications that would describe what I need to send to it, I'd be happy. (Trying to guess what I need to send to each individual motor to get the right output sounds like a rather difficult way of approaching the problem, was hoping there was some sort of documentation or standardized "protocol" that might exist for the overall unit. Definitely have googled a lot to no avail.)
Just looking for some help to point me in the right direction here. I am familiar with the Propeller chip, software development (my main gig), and basic electronics concepts. Never tried to do motor control before.
![top view](https://i.stack.imgur.com/P3e5I.jpg)
![bottom view](https://i.stack.imgur.com/S7bW7.jpg)
![side panel](https://i.stack.imgur.com/GufTv.jpg) | 2013/09/21 | [
"https://electronics.stackexchange.com/questions/82995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27688/"
] | I haven't used anything similar but these are my observations based on the photo:
* It appears to be a standard DC motor not a stepper motor. So to get it to move left and right you'd need to reverse power to the motor.
* On the first photo I'm guessing the wires going to the left are to indicate the end of travel on that end, although the mechanism isn't clear from the photo.
* The right hand side appears to be for the print head. It's hard to make out when assembled what contacts would touch each other on the last photo, but I guess the two inner pins make continual contact with the inner PCB trace, and the right-most make continual contact with the outer trace so that would be power for the print head.
* The left-most pin appears in the same area appears to be for position feedback by making contact with the 'spokes' on the PCB as it turns around.
You'd need to determine the voltage everything requires, for the motor you could just turn up the voltage until it appeared to be moving at a reasonable rate. For the print head you could do the same until it appeared to be leaving a solid line as the motor moves.
I'm not sure how much effort you're prepared to put into it but the other steps I can think of you'd need to perform are:
* Design an H bridge to allow the motor to be moved in each direction.
* Use a FET to drive the print head.
* Connect the two position feedback lines to inputs.
* Write software to keep track of where everything is and get the timing right.
* Find or make font tables to be able to print text using the device.
* Make a suitable paper feeder as this doesn't appear to have one. | So, I started playing around with one of these. It is *not* a dot matrix printer and it only has 14 glyphs because it comes from a calculator (0-9, some other characters).
Controlling it is fairly straightforward: there's a clutch and a motor. If you watch the output from the index wheel, you can see when to activate the clutch to stamp the characters to the page
Another answer here links to a German page, but it contains everything you'll need to control the printer including circuit diagrams and AVR assembly program so you can send the text to print over serial.
Throw this into a translator and it will give you everything:
<http://elektronik-kompendium.de/public/arnerossius/bastel/m31a.htm> |
82,995 | I have small dot matrix printing device that I'm trying to control (i.e. print to) with a Parallax Propeller board. (See images below.) It's the printer from this: <http://shop.usa.canon.com/shop/en/catalog/calculators/palm-printing-calculators/p23-dhv>
Is anyone familiar with how one of these things works? I don't see any chips or other electronics on it, so I assume it's just stepping motor control. It seems like I can get specs on the large silver motor from here: <http://www.standardmotor.net/sc_webcat/ecat/product_browse_list.php?lang=1&cat=205> but don't know on the rest.
It would be great if there were some sort of "driver" for this for use from Propeller Spin code, but I realize that most likely doesn't exist. If I could at least find some specifications that would describe what I need to send to it, I'd be happy. (Trying to guess what I need to send to each individual motor to get the right output sounds like a rather difficult way of approaching the problem, was hoping there was some sort of documentation or standardized "protocol" that might exist for the overall unit. Definitely have googled a lot to no avail.)
Just looking for some help to point me in the right direction here. I am familiar with the Propeller chip, software development (my main gig), and basic electronics concepts. Never tried to do motor control before.
![top view](https://i.stack.imgur.com/P3e5I.jpg)
![bottom view](https://i.stack.imgur.com/S7bW7.jpg)
![side panel](https://i.stack.imgur.com/GufTv.jpg) | 2013/09/21 | [
"https://electronics.stackexchange.com/questions/82995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27688/"
] | Here's my suggested course of action
1. Check the number and type of battery in the calculator. Work out it's max operating voltage. e.g. 4 x AA = 6V.
2. In the top photo assume connections are
* 1&2 shorted when rotor at 0-5 degrees position
* 3&4 shorted when rotor at 360/14 degree positions (next line print position?)
* 5&6 motor drive +/- <=6V
* 7&8 shorted when print head hits left end.
I'd use a multimeter to test these assumptions. | here is what you're looking for
<http://www.elektronik-kompendium.de/public/arnerossius/bastel/m31a.htm> |
82,995 | I have small dot matrix printing device that I'm trying to control (i.e. print to) with a Parallax Propeller board. (See images below.) It's the printer from this: <http://shop.usa.canon.com/shop/en/catalog/calculators/palm-printing-calculators/p23-dhv>
Is anyone familiar with how one of these things works? I don't see any chips or other electronics on it, so I assume it's just stepping motor control. It seems like I can get specs on the large silver motor from here: <http://www.standardmotor.net/sc_webcat/ecat/product_browse_list.php?lang=1&cat=205> but don't know on the rest.
It would be great if there were some sort of "driver" for this for use from Propeller Spin code, but I realize that most likely doesn't exist. If I could at least find some specifications that would describe what I need to send to it, I'd be happy. (Trying to guess what I need to send to each individual motor to get the right output sounds like a rather difficult way of approaching the problem, was hoping there was some sort of documentation or standardized "protocol" that might exist for the overall unit. Definitely have googled a lot to no avail.)
Just looking for some help to point me in the right direction here. I am familiar with the Propeller chip, software development (my main gig), and basic electronics concepts. Never tried to do motor control before.
![top view](https://i.stack.imgur.com/P3e5I.jpg)
![bottom view](https://i.stack.imgur.com/S7bW7.jpg)
![side panel](https://i.stack.imgur.com/GufTv.jpg) | 2013/09/21 | [
"https://electronics.stackexchange.com/questions/82995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27688/"
] | So, I started playing around with one of these. It is *not* a dot matrix printer and it only has 14 glyphs because it comes from a calculator (0-9, some other characters).
Controlling it is fairly straightforward: there's a clutch and a motor. If you watch the output from the index wheel, you can see when to activate the clutch to stamp the characters to the page
Another answer here links to a German page, but it contains everything you'll need to control the printer including circuit diagrams and AVR assembly program so you can send the text to print over serial.
Throw this into a translator and it will give you everything:
<http://elektronik-kompendium.de/public/arnerossius/bastel/m31a.htm> | here is what you're looking for
<http://www.elektronik-kompendium.de/public/arnerossius/bastel/m31a.htm> |
3,535,923 | I have a dropdown list of items a user can select from (the view is JSF). I would like for an image to appear on the same JSF page after a user selects an item from the dropdown list (i.e. A user select the word "Cat" from the dropdown list, and group of different cat images appear)
How would I code this in JSF?
Note\* I'm using JSF 2.0 with facelets, not JSPs. | 2010/08/21 | [
"https://Stackoverflow.com/questions/3535923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376434/"
] | Provide a list with image URL's in the dropdown and use `h:graphicImage` to display an image on the selected URL. Then, use `f:ajax` to re-render the image on change the dropdown.
Here's a kickoff example:
```
<h:form>
<h:selectOneMenu value="#{bean.imageURL}">
<f:selectItems value="#{bean.imageURLs}" />
<f:ajax event="change" render="image" />
</h:selectOneMenu>
<h:graphicImage id="image" value="#{bean.imageURL}" />
</h:form>
```
Bean:
```
private List<String> imageURLs; // +getter
private String imageURL; // +getter +setter
``` | BalusC's answer is (as always :) correct, but as you noticed there will be a list of URLs in the selectOneMenu. That is exactly why I asked you how do you store your images. The way I usually do it: (and from what I know that's the standard way of doing it, hopefully someone will correcty me if I'm wrong) you store the image somewhere on the server and in your DB you store its location. That's why I would suggest to make a MyImage class (which will be mapped to a DB table) where you would store the name of the image and a way to get its location on the server (for example you can do it using namespaces like cats will have a `String namespace = "cats"` and a `String imageName` and a method that will return the url like `String getImageLocation() {return "<http://something.com/images/>"+namespace+"/"+imageName;}` remember that it's important to make it look like a getter so the JSF can use it). Then all you have to do is to get the list of MyImages for a given namespace from your DB and render the images in a dataTable, something like this:
```
<h:dataTable value="#{myBeanWithAListOfImages.images}" var="img">
<h:column>
<h:graphicImage value="img.imageLocation"/>
</h:column>
</h:dataTable>
```
Where images is a `List<MyImage>`. This should work and print the images in a single column. |
23,899,409 | I'm using Mongodb.
Consider my next document:
```
{ uid: 1, created: ISODate("2014-05-02..."), another_col : "x" },
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 1, created: ISODate("2014-05-01..."), another_col : "f" },
{ uid: 2, created: ISODate("2014-05-22..."), another_col : "a" }
```
What I'm trying to do is a simple groupby on the uid and sorting the created by descending order so i could get the first row for each uid.
An example for an expected output
```
{ uid: 1, created: ISODate("2014-05-05..."), another_col: "y" },
{ uid: 2, created: ISODate("2014-05-22..."), another_col: "a" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col: "w" }
```
The best I could get is:
```
db.mycollection.aggregate( {$group: {_id: "$uid", rows: {$push: { "created" : "$created" }}}}, sort { // doesnt work well } )
```
Anyone can guide me for the right combination of group by and sorting?
It just doesn't work as I was expecting.
(note: I have checked many threads, but I'm unable to find the correct answer for my case) | 2014/05/27 | [
"https://Stackoverflow.com/questions/23899409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1024246/"
] | There are a few catches here to understand.
When you use [**`$group`**](http://docs.mongodb.org/manual/reference/operator/aggregation/group/) the boundaries will be sorted in the order that they were discovered without either an initial or ending stage [**`$sort`**](http://docs.mongodb.org/manual/reference/operator/aggregation/sort/) operation. So if your documents were originally in an order like this:
```js
{ uid: 1, created: ISODate("2014-05-02..."), another_col : "x" },
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
```
Then just using [**`$group`**](http://docs.mongodb.org/manual/reference/operator/aggregation/group/) without a [**`$sort`**](http://docs.mongodb.org/manual/reference/operator/aggregation/sort/) on the end on the pipeline would return you results like this:
```js
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
```
That is one concept, but it actually seems like what you are expecting in results requires returning the "last other fields" by a sorted order of the `uid` is what you are looking for. In that case the way to get your result is actually to **`$sort`** first and then make use of the [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) operator:
```js
db.mycollection.aggregate([
// Sorts everything first by _id and created
{ "$sort": { "_id": 1, "created": 1 } },
// Group with the $last results from each boundary
{ "$group": {
"_id": "$uid",
"created": { "$last": "$created" },
"another_col": { "$last": "$created" }
}}
])
```
Or essentially apply the sort to what you want.
The difference between [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) and [**`$max`**](http://docs.mongodb.org/manual/reference/operator/aggregation/max/) is that the latter will choose the "highest" value for the given field within the grouping `_id`, regardless of the current sorted on un-sorted order. On the other hand, [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) will choose the value that occurs in the same "row" as the "last" grouping `_id` value.
---
If you were actually looking to sort the values of an array then the approach is similar. Keeping the array members in "created" order you would also sort first:
```js
db.mycollection.aggregate([
// Sorts everything first by _id and created
{ "$sort": { "_id": 1, "created": 1 } },
// Group with the $last results from each boundary
{ "$group": {
"_id": "$uid",
"row": {
"$push": {
"created": "$created",
"another_col": "$another_col"
}
}
}}
])
```
And the documents with those fields will be added to the array with the order they were already sorted by. | If all you're looking for is the first row that means you're looking for the max. Just use the built-in `$max` accumulator.
```
db.mycollection.aggregate([{$group: {_id: "$uid", rows: {$max:"$created"}}}])
```
You would use the `$push` accumulator if you needed to process all the creation dates. For more information on the accumulators see: <http://docs.mongodb.org/manual/reference/operator/aggregation/group/>
From your comments if you want the full documents returned, and want to be able to iterate over all the documents then you really don't need to aggregate the results. Something like this should get you what you want.
```
db.mycollection.find({$query:{}, $orderby:{uid:1,created:-1}})
``` |
23,899,409 | I'm using Mongodb.
Consider my next document:
```
{ uid: 1, created: ISODate("2014-05-02..."), another_col : "x" },
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 1, created: ISODate("2014-05-01..."), another_col : "f" },
{ uid: 2, created: ISODate("2014-05-22..."), another_col : "a" }
```
What I'm trying to do is a simple groupby on the uid and sorting the created by descending order so i could get the first row for each uid.
An example for an expected output
```
{ uid: 1, created: ISODate("2014-05-05..."), another_col: "y" },
{ uid: 2, created: ISODate("2014-05-22..."), another_col: "a" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col: "w" }
```
The best I could get is:
```
db.mycollection.aggregate( {$group: {_id: "$uid", rows: {$push: { "created" : "$created" }}}}, sort { // doesnt work well } )
```
Anyone can guide me for the right combination of group by and sorting?
It just doesn't work as I was expecting.
(note: I have checked many threads, but I'm unable to find the correct answer for my case) | 2014/05/27 | [
"https://Stackoverflow.com/questions/23899409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1024246/"
] | There are a few catches here to understand.
When you use [**`$group`**](http://docs.mongodb.org/manual/reference/operator/aggregation/group/) the boundaries will be sorted in the order that they were discovered without either an initial or ending stage [**`$sort`**](http://docs.mongodb.org/manual/reference/operator/aggregation/sort/) operation. So if your documents were originally in an order like this:
```js
{ uid: 1, created: ISODate("2014-05-02..."), another_col : "x" },
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
```
Then just using [**`$group`**](http://docs.mongodb.org/manual/reference/operator/aggregation/group/) without a [**`$sort`**](http://docs.mongodb.org/manual/reference/operator/aggregation/sort/) on the end on the pipeline would return you results like this:
```js
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" },
{ uid: 3, created: ISODate("2014-05-05..."), another_col : "w" },
{ uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
```
That is one concept, but it actually seems like what you are expecting in results requires returning the "last other fields" by a sorted order of the `uid` is what you are looking for. In that case the way to get your result is actually to **`$sort`** first and then make use of the [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) operator:
```js
db.mycollection.aggregate([
// Sorts everything first by _id and created
{ "$sort": { "_id": 1, "created": 1 } },
// Group with the $last results from each boundary
{ "$group": {
"_id": "$uid",
"created": { "$last": "$created" },
"another_col": { "$last": "$created" }
}}
])
```
Or essentially apply the sort to what you want.
The difference between [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) and [**`$max`**](http://docs.mongodb.org/manual/reference/operator/aggregation/max/) is that the latter will choose the "highest" value for the given field within the grouping `_id`, regardless of the current sorted on un-sorted order. On the other hand, [**`$last`**](http://docs.mongodb.org/manual/reference/operator/aggregation/last/) will choose the value that occurs in the same "row" as the "last" grouping `_id` value.
---
If you were actually looking to sort the values of an array then the approach is similar. Keeping the array members in "created" order you would also sort first:
```js
db.mycollection.aggregate([
// Sorts everything first by _id and created
{ "$sort": { "_id": 1, "created": 1 } },
// Group with the $last results from each boundary
{ "$group": {
"_id": "$uid",
"row": {
"$push": {
"created": "$created",
"another_col": "$another_col"
}
}
}}
])
```
And the documents with those fields will be added to the array with the order they were already sorted by. | using $project along with this
```
db.mycollection.aggregate([{$group: {_id: "$uid", rows: {$max:"$created"}}}])
```
should help you, refer to these links
<http://docs.mongodb.org/manual/reference/operator/aggregation/project/>
[Mongodb group and project operators](https://stackoverflow.com/questions/15753317/mongodb-group-and-project-operators)
[mongodb aggregation framework group + project](https://stackoverflow.com/questions/15285795/mongodb-aggregation-framework-group-project) |
43,164,998 | I got one github project to scann QR code using Zxing Library, but somehow I am not able to get Scanned Image and QR code also. here is my code. In gradle I am using:
* Gradle Compile Statment
**build.gradle**
```
compile 'me.dm7.barcodescanner:core:1.9'
compile 'com.google.zxing:core:3.2.1'
```
You can see my activity and xml code below.
**ScanQR\_Code\_Activity.java**
```
package com.rishi.myaadhaar.activities;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.Result;
import com.myadhaar.R;
import java.util.ArrayList;
public class ScanQR_Code_Activity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final String FLASH_STATE = "FLASH_STATE";
// UI Elements
private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
private static final String CAMERA_ID = "CAMERA_ID";
String uid, name, gender, yearOfBirth, careOf, villageTehsil, postOffice, house, street, loc, district, state, postCode, lm;
ViewGroup contentFrame;
private ZXingScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
private ArrayList<Integer> mSelectedIndices;
private int mCameraId = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
if (savedInstanceState != null) {
mFlash = savedInstanceState.getBoolean(FLASH_STATE, false);
mAutoFocus = savedInstanceState.getBoolean(AUTO_FOCUS_STATE, true);
mSelectedIndices = savedInstanceState.getIntegerArrayList(SELECTED_FORMATS);
mCameraId = savedInstanceState.getInt(CAMERA_ID, -1);
} else {
mFlash = false;
mAutoFocus = true;
mSelectedIndices = null;
mCameraId = -1;
}
contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
@Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
@Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
@Override
public void handleResult(Result rawResult) {
Toast.makeText(this, "Contents = " + rawResult.getText() +
", Format = " + rawResult.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
if (rawResult != null && !rawResult.getText().toString().isEmpty()) {
//processScannedData(rawResult.getText());
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Scan Cancelled", Toast.LENGTH_SHORT);
toast.show();
}
// Note:
// * Wait 2 seconds to resume the preview.
// * On older devices continuously stopping and resuming camera preview can result in freezing the app.
// * I don't know why this is the case but I don't have the time to figure out.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mScannerView.resumeCameraPreview(ScanQR_Code_Activity.this);
}
}, 2000);
}
}
```
**activity\_scan\_qr\_code.xml**
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_scan_qr_code"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rishi.myaadhaar.activities.ScanQR_Code_Activity">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
```
**extends class**
```
public class ZXingScannerView extends BarcodeScannerView {
private static final String TAG = "ZXingScannerView";
public interface ResultHandler {
public void handleResult(Result rawResult);
}
private MultiFormatReader mMultiFormatReader;
public static final List<BarcodeFormat> ALL_FORMATS = new ArrayList<BarcodeFormat>();
private List<BarcodeFormat> mFormats;
private ResultHandler mResultHandler;
static {
ALL_FORMATS.add(BarcodeFormat.UPC_A);
ALL_FORMATS.add(BarcodeFormat.UPC_E);
ALL_FORMATS.add(BarcodeFormat.EAN_13);
ALL_FORMATS.add(BarcodeFormat.EAN_8);
ALL_FORMATS.add(BarcodeFormat.RSS_14);
ALL_FORMATS.add(BarcodeFormat.CODE_39);
ALL_FORMATS.add(BarcodeFormat.CODE_93);
ALL_FORMATS.add(BarcodeFormat.CODE_128);
ALL_FORMATS.add(BarcodeFormat.ITF);
ALL_FORMATS.add(BarcodeFormat.CODABAR);
ALL_FORMATS.add(BarcodeFormat.QR_CODE);
ALL_FORMATS.add(BarcodeFormat.DATA_MATRIX);
ALL_FORMATS.add(BarcodeFormat.PDF_417);
}
public ZXingScannerView(Context context) {
super(context);
initMultiFormatReader();
}
public ZXingScannerView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
initMultiFormatReader();
}
public void setFormats(List<BarcodeFormat> formats) {
mFormats = formats;
initMultiFormatReader();
}
public void setResultHandler(ResultHandler resultHandler) {
mResultHandler = resultHandler;
}
public Collection<BarcodeFormat> getFormats() {
if(mFormats == null) {
return ALL_FORMATS;
}
return mFormats;
}
private void initMultiFormatReader() {
Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
hints.put(DecodeHintType.POSSIBLE_FORMATS, getFormats());
mMultiFormatReader = new MultiFormatReader();
mMultiFormatReader.setHints(hints);
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(mResultHandler == null) {
return;
}
try {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
int width = size.width;
int height = size.height;
if (DisplayUtils.getScreenOrientation(getContext()) == Configuration.ORIENTATION_PORTRAIT) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width;
width = height;
height = tmp;
data = rotatedData;
}
Result rawResult = null;
PlanarYUVLuminanceSource source = buildLuminanceSource(data, width, height);
if (source != null)
{
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = mMultiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} catch (NullPointerException npe) {
// This is terrible
} catch (ArrayIndexOutOfBoundsException aoe) {
} finally
{
mMultiFormatReader.reset();
}
}
final Result finalRawResult = rawResult;
if (finalRawResult != null) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// Stopping the preview can take a little long.
// So we want to set result handler to null to discard subsequent calls to
// onPreviewFrame.
ResultHandler tmpResultHandler = mResultHandler;
mResultHandler = null;
stopCameraPreview();
if (tmpResultHandler != null) {
tmpResultHandler.handleResult(finalRawResult);
}
}
});
} else {
camera.setOneShotPreviewCallback(this);
}
} catch(RuntimeException e) {
// TODO: Terrible hack. It is possible that this method is invoked after camera is released.
Log.e(TAG, e.toString(), e);
}
}
public void resumeCameraPreview(ResultHandler resultHandler) {
mResultHandler = resultHandler;
super.resumeCameraPreview();
}
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview(width, height);
if (rect == null)
{
return null;
}
// Go ahead and assume it's YUV rather than die.
PlanarYUVLuminanceSource source = null;
try
{
source = new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false);
}
catch(Exception e)
{
}
return source;
}
}
``` | 2017/04/02 | [
"https://Stackoverflow.com/questions/43164998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5383724/"
] | call generateQRCode() method from handleResult() method like this
```
@Override
public void handleResult(Result rawResult) {
generateQRCode(rawResult.getResultMetadata().toString());
}
public void generateQRCode(String data){
com.google.zxing.Writer wr = new MultiFormatWriter();
try {
int width = 350;
int height = 350;
BitMatrix bm = wr.encode(data, BarcodeFormat.QR_CODE, width, height);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
mBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
} catch (WriterException e) {
e.printStackTrace();
}
if (mBitmap != null) {
img.setImageBitmap(mBitmap);
}
}
``` | ZXing won't return it to you. I would recommend grabbing the frame from the viewfinder at scan time. It won't be the exact image but it will be a frame right before or after the one that triggered the scan. |
33,535,147 | While working with some uncommitted files, I need to pull new code. There's a conflict, so git refuses to pull:
```
error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
```
Question 1: How can I pull and merge with my uncommitted changes? I need to keep on working, I'm not ready to commit, but I want the external code?
Question 2: I ended up doing a `stash` followed by a `pull`. How do I now merge in my changes to the new pull? How do I apply my stash without clobbering the new changes of the pull? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33535147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785494/"
] | Using `stash`, then `pull`, last `stash pop`.
```
git stash
git pull
git stash pop
``` | Git provides excellent documentation on their functions. For this case you would need stach, you can look it up with several examples at:
<https://git-scm.com/book/en/v1/Git-Tools-Stashing> |
33,535,147 | While working with some uncommitted files, I need to pull new code. There's a conflict, so git refuses to pull:
```
error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
```
Question 1: How can I pull and merge with my uncommitted changes? I need to keep on working, I'm not ready to commit, but I want the external code?
Question 2: I ended up doing a `stash` followed by a `pull`. How do I now merge in my changes to the new pull? How do I apply my stash without clobbering the new changes of the pull? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33535147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785494/"
] | Using `stash`, then `pull`, last `stash pop`.
```
git stash
git pull
git stash pop
``` | Before going deeper into merges I need to pay your attention that there are two similar solutions for the task "get latest changes from remote".
For more information please refer to [git pull VS git fetch git rebase](https://stackoverflow.com/questions/3357122/git-pull-vs-git-fetch-git-rebase).
I prefer the rebase since it doesn't produce redundant merge commits.
Do not be afraid to make a commit. You can easily do anything you like with it (modify it with [`git commit --amend`](https://git-scm.com/docs/git-commit), discard it and pop all changes into worktree with [`git reset HEAD~1`](https://git-scm.com/docs/git-reset)) until you push it anywhere.
Answer 1
--------
```
git add . # stage all changes for commit
git commit -m 'Tmp' # make temporary commit
git fetch $RemoteName # fetch new changes from remote
git rebase $RemoteName/$BranchName # rebase my current working branch
# (with temporary commit) on top of fethed changes
git reset HEAD~1 # discard last commit
# and pop all changes from it into worktree
```
Answer 2
--------
```
git stash pop # this retrieves your changes
# from last stash and put them as changes in worktree
```
This command doesn't affect commits that you get using any command from `fetch` *family* (`fetch`, `pull`, ...). |
33,535,147 | While working with some uncommitted files, I need to pull new code. There's a conflict, so git refuses to pull:
```
error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
```
Question 1: How can I pull and merge with my uncommitted changes? I need to keep on working, I'm not ready to commit, but I want the external code?
Question 2: I ended up doing a `stash` followed by a `pull`. How do I now merge in my changes to the new pull? How do I apply my stash without clobbering the new changes of the pull? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33535147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785494/"
] | Before going deeper into merges I need to pay your attention that there are two similar solutions for the task "get latest changes from remote".
For more information please refer to [git pull VS git fetch git rebase](https://stackoverflow.com/questions/3357122/git-pull-vs-git-fetch-git-rebase).
I prefer the rebase since it doesn't produce redundant merge commits.
Do not be afraid to make a commit. You can easily do anything you like with it (modify it with [`git commit --amend`](https://git-scm.com/docs/git-commit), discard it and pop all changes into worktree with [`git reset HEAD~1`](https://git-scm.com/docs/git-reset)) until you push it anywhere.
Answer 1
--------
```
git add . # stage all changes for commit
git commit -m 'Tmp' # make temporary commit
git fetch $RemoteName # fetch new changes from remote
git rebase $RemoteName/$BranchName # rebase my current working branch
# (with temporary commit) on top of fethed changes
git reset HEAD~1 # discard last commit
# and pop all changes from it into worktree
```
Answer 2
--------
```
git stash pop # this retrieves your changes
# from last stash and put them as changes in worktree
```
This command doesn't affect commits that you get using any command from `fetch` *family* (`fetch`, `pull`, ...). | Git provides excellent documentation on their functions. For this case you would need stach, you can look it up with several examples at:
<https://git-scm.com/book/en/v1/Git-Tools-Stashing> |
57,650,739 | I don't know how to make the user leave the voice channel.
I'm trying to make a verify thing, I have it all setup except for the leave voice channel part.
```
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
var channel = bot.channels.get('614299678300831744');
if(oldUserChannel === undefined && newUserChannel !== 615306755420717143) {
channel.send(newMember + ' has been verified.');
let role = newMember.guild.roles.find(role => role.name === "Verified");
newMember.addRole(role);
let verifyEmbed = new Discord.RichEmbed()
.setAuthor("Verificaiton")
.setDescription("You have been verified")
.setFooter(newMember.guild.name)
.setColor("#98AFC7")
newMember.sendMessage(verifyEmbed);
newMember.disconnect();
}
});
```
I don't get any error, but it should disconnect me from the voice channel but can't? | 2019/08/26 | [
"https://Stackoverflow.com/questions/57650739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464450/"
] | Instead of `newMember.disconnect();` use `newMember.setVoiceChannel(null);`
Here is the related [documentation](https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=setVoiceChannel)
I use this on my bot and it works fine. | The problem is that `.disconnect()` is not a method of the `GuildMember` class. All of the methods that can be used on a `GuildMember` can be found [here](https://discord.js.org/#/docs/main/stable/class/GuildMember).
`.disconnect()` is only a method that exists on a `voiceChannel`, and is used to "Disconnect the voice connection, causing a disconnect and closing event to be emitted." [1](https://discord.js.org/#/docs/main/stable/class/VoiceConnection?scrollTo=disconnect)
From what i can tell, there is no possible way to forcibly remove a user from a voice channel. |
57,650,739 | I don't know how to make the user leave the voice channel.
I'm trying to make a verify thing, I have it all setup except for the leave voice channel part.
```
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
var channel = bot.channels.get('614299678300831744');
if(oldUserChannel === undefined && newUserChannel !== 615306755420717143) {
channel.send(newMember + ' has been verified.');
let role = newMember.guild.roles.find(role => role.name === "Verified");
newMember.addRole(role);
let verifyEmbed = new Discord.RichEmbed()
.setAuthor("Verificaiton")
.setDescription("You have been verified")
.setFooter(newMember.guild.name)
.setColor("#98AFC7")
newMember.sendMessage(verifyEmbed);
newMember.disconnect();
}
});
```
I don't get any error, but it should disconnect me from the voice channel but can't? | 2019/08/26 | [
"https://Stackoverflow.com/questions/57650739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464450/"
] | Not sure if this is still relevant but since the update you can now do the following.
```
newMember.member.voice.disconnect();
```
Refer to the [VoiceState](https://discord.js.org/#/docs/main/stable/class/VoiceState) class method `disconnect`. | The problem is that `.disconnect()` is not a method of the `GuildMember` class. All of the methods that can be used on a `GuildMember` can be found [here](https://discord.js.org/#/docs/main/stable/class/GuildMember).
`.disconnect()` is only a method that exists on a `voiceChannel`, and is used to "Disconnect the voice connection, causing a disconnect and closing event to be emitted." [1](https://discord.js.org/#/docs/main/stable/class/VoiceConnection?scrollTo=disconnect)
From what i can tell, there is no possible way to forcibly remove a user from a voice channel. |
57,650,739 | I don't know how to make the user leave the voice channel.
I'm trying to make a verify thing, I have it all setup except for the leave voice channel part.
```
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
var channel = bot.channels.get('614299678300831744');
if(oldUserChannel === undefined && newUserChannel !== 615306755420717143) {
channel.send(newMember + ' has been verified.');
let role = newMember.guild.roles.find(role => role.name === "Verified");
newMember.addRole(role);
let verifyEmbed = new Discord.RichEmbed()
.setAuthor("Verificaiton")
.setDescription("You have been verified")
.setFooter(newMember.guild.name)
.setColor("#98AFC7")
newMember.sendMessage(verifyEmbed);
newMember.disconnect();
}
});
```
I don't get any error, but it should disconnect me from the voice channel but can't? | 2019/08/26 | [
"https://Stackoverflow.com/questions/57650739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464450/"
] | Instead of `newMember.disconnect();` use `newMember.setVoiceChannel(null);`
Here is the related [documentation](https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=setVoiceChannel)
I use this on my bot and it works fine. | You can make the bot create a new voice channel, move the user to the newly created voice channel, delete that channel and thus the user being disconnected
```
let randomnumber = Math.floor(Math.random() * 9000 + 1000)
await receivedMessage.guild.createChannel(`voice-kick-${randomnumber}`, "voice")
await vcUser.setVoiceChannel(receivedMessage.guild.channels.find(r => r.name === `voice-kick-${randomnumber}`))
receivedMessage.guild.channels.find(r => r.name === `voice-${randomnumber}`).delete()
```
Were adding the randomnumber command to make a random number in the VC so that there aren't any VC's that have the same name! |
57,650,739 | I don't know how to make the user leave the voice channel.
I'm trying to make a verify thing, I have it all setup except for the leave voice channel part.
```
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
var channel = bot.channels.get('614299678300831744');
if(oldUserChannel === undefined && newUserChannel !== 615306755420717143) {
channel.send(newMember + ' has been verified.');
let role = newMember.guild.roles.find(role => role.name === "Verified");
newMember.addRole(role);
let verifyEmbed = new Discord.RichEmbed()
.setAuthor("Verificaiton")
.setDescription("You have been verified")
.setFooter(newMember.guild.name)
.setColor("#98AFC7")
newMember.sendMessage(verifyEmbed);
newMember.disconnect();
}
});
```
I don't get any error, but it should disconnect me from the voice channel but can't? | 2019/08/26 | [
"https://Stackoverflow.com/questions/57650739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464450/"
] | Not sure if this is still relevant but since the update you can now do the following.
```
newMember.member.voice.disconnect();
```
Refer to the [VoiceState](https://discord.js.org/#/docs/main/stable/class/VoiceState) class method `disconnect`. | Instead of `newMember.disconnect();` use `newMember.setVoiceChannel(null);`
Here is the related [documentation](https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=setVoiceChannel)
I use this on my bot and it works fine. |