Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 16
65.1k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
117k
| response_k
stringlengths 3
61.5k
|
---|---|---|---|---|---|
34,856 | is it possible to search a whole database tables ( row and column) to find out a particular string.
I am having a Database named A with about 35 tables,i need to search for the string named "hello" and i dont know on which table this string is saved.Is it possible?
Using MySQL
i am a linux admin and i am not familiar with databases,it would be really helpful if u can explain the query also. | 2013/02/16 | [
"https://dba.stackexchange.com/questions/34856",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20242/"
] | If you can use a bash - here is a script:
It needs a user dbread with pass dbread on the database.
```
#!/bin/bash
IFS='
'
DBUSER=dbread
DBPASS=dbread
echo -n "Which database do you want to search in (press 0 to see all databases): "
read DB
echo -n "Which string do you want to search: "
read SEARCHSTRING
for i in `mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | head -1\``
do
for k in `mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | head -1\` | grep -v int | awk '{print $1}'`
do
if [ `mysql $DB -u$DBUSER -p$DBPASS -e "Select * from $i where $k='$SEARCHSTRING'" | wc -l` -gt 1 ]
then
echo " Your searchstring was found in table $i, column $k"
fi
done
done
```
If anyone wants an explanation: <http://infofreund.de/?p=1670> | Do you have access to phpMyAdmin? It has a search feature for each database.
or use scripting of your choice on the result of (change dbname):
```
$string = 'mysqldump --compact --skip-extended-insert -u ' . $db_user . ' -p' . $db_password . ' dbname 2>&1 | grep "particular string" 2>&1';
$result = shell_exec ( $string );
``` |
34,856 | is it possible to search a whole database tables ( row and column) to find out a particular string.
I am having a Database named A with about 35 tables,i need to search for the string named "hello" and i dont know on which table this string is saved.Is it possible?
Using MySQL
i am a linux admin and i am not familiar with databases,it would be really helpful if u can explain the query also. | 2013/02/16 | [
"https://dba.stackexchange.com/questions/34856",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20242/"
] | You can return all columns from all tables that match any values you're looking for all at once by building off of [RolandoMySQLDBA's answer](https://dba.stackexchange.com/a/37041/6786) and using [`PREPARE` and `EXECUTE` to run the query](https://stackoverflow.com/a/10122864/526741).
```
-- Your values
SET @table_schema = 'your_table_name';
SET @condition = "LIKE '%your string to search%'";
SET @column_types_regexp = '^((var)?char|(var)?binary|blob|text|enum|set)\\(';
-- Reset @sql_query in case it was used previously
SET @sql_query = '';
-- Build query for each table and merge with previous queries with UNION
SELECT
-- Use `DISTINCT IF(QUERYBUILDING, NULL, NULL)`
-- to only select a single null value
-- instead of selecting the query over and over again as it's built
DISTINCT IF(@sql_query := CONCAT(
IF(LENGTH(@sql_query), CONCAT(@sql_query, " UNION "), ""),
'SELECT ',
QUOTE(CONCAT('`', `table_name`, '`.`', `column_name`, '`')), ' AS `column`, ',
'COUNT(*) AS `occurrences` ',
'FROM `', `table_schema`, '`.`', `table_name`, '` ',
'WHERE `', `column_name`, '` ', @condition
), NULL, NULL) `query`
FROM (
SELECT
`table_schema`,
`table_name`,
`column_name`
FROM `information_schema`.`columns`
WHERE `table_schema` = @table_schema
AND `column_type` REGEXP @column_types_regexp
) `results`;
select @sql_query;
-- Only return results with at least one occurrence
SET @sql_query = CONCAT("SELECT * FROM (", @sql_query, ") `results` WHERE `occurrences` > 0");
-- Run built query
PREPARE statement FROM @sql_query;
EXECUTE statement;
DEALLOCATE PREPARE statement;
``` | I focus on a simple template solution for your question implemented in **plsql for Oracle** database, I hope customizing it on MySql, being simple throw googleing.
all you need is to investigate information schema on MySql and replaceing some table name and columns.
In the script:
`ALL_TAB_COLUMNS` is an information schema table containing All Table Columns
**'VARCHAR2','NVARCHAR2','NCHAR','CHAR'** refers to string column types in Oracle, you have to replace them with equvalents type names of MySql
%hello% is search keyword replace it with any string.
The result will be some or many sql scripts (based on your tables column types) and running them will result your answer
Also performance and time consumption will be another matters.
i hope this will be useful
```
SELECT
'SELECT ' || ALL_TAB_COLUMNS.COLUMN_NAME || ' AS RESULT_FOUND, '
|| '''' || ALL_TAB_COLUMNS.TABLE_NAME ||''''|| ' AS TABLE_NAME, '
|| '''' || ALL_TAB_COLUMNS.COLUMN_NAME ||''''|| ' AS COLUMN_NAME '
|| 'FROM ' || ALL_TAB_COLUMNS.OWNER ||'.'||ALL_TAB_COLUMNS.TABLE_NAME
|| ' WHERE ' || ALL_TAB_COLUMNS.COLUMN_NAME || ' LIKE ''%hello%''' || ';'
FROM ALL_TAB_COLUMNS
WHERE
ALL_TAB_COLUMNS.OWNER = 'SCOTT'
AND
ALL_TAB_COLUMNS.DATA_TYPE IN ('VARCHAR2','NVARCHAR2','NCHAR','CHAR')
``` |
34,856 | is it possible to search a whole database tables ( row and column) to find out a particular string.
I am having a Database named A with about 35 tables,i need to search for the string named "hello" and i dont know on which table this string is saved.Is it possible?
Using MySQL
i am a linux admin and i am not familiar with databases,it would be really helpful if u can explain the query also. | 2013/02/16 | [
"https://dba.stackexchange.com/questions/34856",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20242/"
] | Taking another approach that doesn't require building SQL queries, I developed [CRGREP](https://sourceforge.net/projects/crgrep/) as a free opensource command line tool that will grep databases (including MySQL) and supports both simple "fred customer.name" type searches for "fred" in the "name" column of the "customer" table to more complex pattern matching such as "fr?d \*.author" for pattern matching against all "author" columns across all tables. | If you can use a bash - here is a script:
It needs a user dbread with pass dbread on the database.
```
#!/bin/bash
IFS='
'
DBUSER=dbread
DBPASS=dbread
echo -n "Which database do you want to search in (press 0 to see all databases): "
read DB
echo -n "Which string do you want to search: "
read SEARCHSTRING
for i in `mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | head -1\``
do
for k in `mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | head -1\` | grep -v int | awk '{print $1}'`
do
if [ `mysql $DB -u$DBUSER -p$DBPASS -e "Select * from $i where $k='$SEARCHSTRING'" | wc -l` -gt 1 ]
then
echo " Your searchstring was found in table $i, column $k"
fi
done
done
```
If anyone wants an explanation: <http://infofreund.de/?p=1670> |
46,332,669 | I want to insert a space before a number in a string if my string has a capital letter, one or more lower case letters, and then a number right after it. That is, if I have
```
Bdefg23
```
I want to insert a space between the "g" and the "23" making the above string
```
Bdefg 23
```
So this string would not get changed
```
BabcdD55
```
because there is a capital letter before "55". I tried this below
```
str.split(/([A-Z][a-z]+)/).delete_if(&:empty?).join(' ')
```
but it works too well. That is, if my string is
```
Ptannex..
```
it will turn it into
```
Ptannex ..
```
How can I adjust what I have to make it work for only the condition I outlined? Btw, I'm using Ruby 2.4. | 2017/09/20 | [
"https://Stackoverflow.com/questions/46332669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can always do it roughly this way:
```
%w[
Bdefg23
Ptannex95
BigX901
littleX902
CS101
xx900
].each do |example|
puts '%s -> %s' % [
example,
example.sub(/\A([A-Z][a-z]+)(\d+)\z/, '\1 \2')
]
end
```
Which gives you output like:
```
Bdefg23 -> Bdefg 23
Ptannex95 -> Ptannex 95
BigX901 -> BigX901
littleX902 -> littleX902
CS101 -> CS101
xx900 -> xx900
``` | You may use
```
s.sub(/\A(\p{Lu}\p{L}*\p{Ll})(\d+)\z/, '\1 \2')
```
See the [Ruby demo](https://ideone.com/JLyfnB).
**Details**
* `\A` - start of string
* `(\p{Lu}\p{L}*\p{Ll})` - Group 1:
+ `\p{Lu}` - any Unicode uppercase letter
+ `\p{L}*` - any 0+ Unicode letters
+ `\p{Ll}` - any lowercase Unicode letter
* `(\d+)` - Group 2: one or more digits
* `\z` - end of string.
The `\1 \2` replacement pattern replaces the whole match with the contents of Group 1, then a space, and then the contents of Group 2. |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Firebug had a similar function
```
console.dir(obj)
```
Or you can do one yourself
```
var dir = '';
for (var i in obj) dir += 'obj[' + i + '] = ' + obj[i];
alert(dir);
``` | ```
for ( var prop in obj ) {
console.log( prop + ' is ' + obj[prop] );
}
``` |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | ```
for ( var prop in obj ) {
console.log( prop + ' is ' + obj[prop] );
}
``` | Try using Chrome's console. If you log any sort of variable to it using `console.log()`, it lets you explore all of its methods and properties, including the prototype chain. This looks sort of like this:
![alt text](https://i.stack.imgur.com/Iju8o.png) |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | ```
for ( var prop in obj ) {
console.log( prop + ' is ' + obj[prop] );
}
``` | JavaScript has the `for .. in` loop construct to help with this:
```
for (var name in some_object) {
// some_object[name] is the value of the property
}
```
However, there are some pitfalls with this approach:
1. An object property can be of *any* type. If you need to filter the list you retrieve, you will need to use `typeof`.
2. `for .. in` will iterate over properties pulled out from the target object's prototype chain. If you want to process only properties defined on the target object itself, you should additionally test for `some_object.hasOwnProperty(name)`. |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Firebug had a similar function
```
console.dir(obj)
```
Or you can do one yourself
```
var dir = '';
for (var i in obj) dir += 'obj[' + i + '] = ' + obj[i];
alert(dir);
``` | Yes. You can use a `for..in` loop (section 12.6.4 of [the spec](http://www.ecma-international.org/publications/standards/Ecma-262.htm)), which loops through the enumerable properties of both the object and its prototype (if it has one), like so:
```
var name;
for (name in obj) {
// `name` is each of the property names, as a string; get the value
// from obj[name]
alert(name + "=" + obj[name]);
}
```
If you want to differentiate whether it's the object itself or its prototype that has the property, you can use [`obj.hasOwnProperty`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty):
```
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
// `name` is the name of a property this object has for itself
}
else {
// `name` is the name of a property the object inherits
// from its prototype
}
}
```
If you're using an implementation that supports some of the new [ECMAScript 5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) stuff, you can use `Object.keys` to get an array of all of its enumerable property names, but really that's just an array version of what `for..in` gives you (and `for..in` is supported by every implementation of JavaScript I've ever seen or you're likely to).
When I say an "enumerable" property: Most of the built-in properties of objects defined by the specification (like `length` on `Array` instances, or `getTime` on `Date` instances) are *non-enumerable* and don't show up in the list. Until the 5th edition of the spec, there was no standard way to define your *own* non-enumerable property, but as of the latest you can do that via `Object.defineProperty` / `Object.defineProperties` (sections 15.2.3.6 and 12.2.3.7 of the spec). That's not widely-supported yet. |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Firebug had a similar function
```
console.dir(obj)
```
Or you can do one yourself
```
var dir = '';
for (var i in obj) dir += 'obj[' + i + '] = ' + obj[i];
alert(dir);
``` | Try using Chrome's console. If you log any sort of variable to it using `console.log()`, it lets you explore all of its methods and properties, including the prototype chain. This looks sort of like this:
![alt text](https://i.stack.imgur.com/Iju8o.png) |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Firebug had a similar function
```
console.dir(obj)
```
Or you can do one yourself
```
var dir = '';
for (var i in obj) dir += 'obj[' + i + '] = ' + obj[i];
alert(dir);
``` | JavaScript has the `for .. in` loop construct to help with this:
```
for (var name in some_object) {
// some_object[name] is the value of the property
}
```
However, there are some pitfalls with this approach:
1. An object property can be of *any* type. If you need to filter the list you retrieve, you will need to use `typeof`.
2. `for .. in` will iterate over properties pulled out from the target object's prototype chain. If you want to process only properties defined on the target object itself, you should additionally test for `some_object.hasOwnProperty(name)`. |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Yes. You can use a `for..in` loop (section 12.6.4 of [the spec](http://www.ecma-international.org/publications/standards/Ecma-262.htm)), which loops through the enumerable properties of both the object and its prototype (if it has one), like so:
```
var name;
for (name in obj) {
// `name` is each of the property names, as a string; get the value
// from obj[name]
alert(name + "=" + obj[name]);
}
```
If you want to differentiate whether it's the object itself or its prototype that has the property, you can use [`obj.hasOwnProperty`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty):
```
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
// `name` is the name of a property this object has for itself
}
else {
// `name` is the name of a property the object inherits
// from its prototype
}
}
```
If you're using an implementation that supports some of the new [ECMAScript 5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) stuff, you can use `Object.keys` to get an array of all of its enumerable property names, but really that's just an array version of what `for..in` gives you (and `for..in` is supported by every implementation of JavaScript I've ever seen or you're likely to).
When I say an "enumerable" property: Most of the built-in properties of objects defined by the specification (like `length` on `Array` instances, or `getTime` on `Date` instances) are *non-enumerable* and don't show up in the list. Until the 5th edition of the spec, there was no standard way to define your *own* non-enumerable property, but as of the latest you can do that via `Object.defineProperty` / `Object.defineProperties` (sections 15.2.3.6 and 12.2.3.7 of the spec). That's not widely-supported yet. | Try using Chrome's console. If you log any sort of variable to it using `console.log()`, it lets you explore all of its methods and properties, including the prototype chain. This looks sort of like this:
![alt text](https://i.stack.imgur.com/Iju8o.png) |
4,652,559 | In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
```
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
``` | 2011/01/10 | [
"https://Stackoverflow.com/questions/4652559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290150/"
] | Yes. You can use a `for..in` loop (section 12.6.4 of [the spec](http://www.ecma-international.org/publications/standards/Ecma-262.htm)), which loops through the enumerable properties of both the object and its prototype (if it has one), like so:
```
var name;
for (name in obj) {
// `name` is each of the property names, as a string; get the value
// from obj[name]
alert(name + "=" + obj[name]);
}
```
If you want to differentiate whether it's the object itself or its prototype that has the property, you can use [`obj.hasOwnProperty`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty):
```
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
// `name` is the name of a property this object has for itself
}
else {
// `name` is the name of a property the object inherits
// from its prototype
}
}
```
If you're using an implementation that supports some of the new [ECMAScript 5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) stuff, you can use `Object.keys` to get an array of all of its enumerable property names, but really that's just an array version of what `for..in` gives you (and `for..in` is supported by every implementation of JavaScript I've ever seen or you're likely to).
When I say an "enumerable" property: Most of the built-in properties of objects defined by the specification (like `length` on `Array` instances, or `getTime` on `Date` instances) are *non-enumerable* and don't show up in the list. Until the 5th edition of the spec, there was no standard way to define your *own* non-enumerable property, but as of the latest you can do that via `Object.defineProperty` / `Object.defineProperties` (sections 15.2.3.6 and 12.2.3.7 of the spec). That's not widely-supported yet. | JavaScript has the `for .. in` loop construct to help with this:
```
for (var name in some_object) {
// some_object[name] is the value of the property
}
```
However, there are some pitfalls with this approach:
1. An object property can be of *any* type. If you need to filter the list you retrieve, you will need to use `typeof`.
2. `for .. in` will iterate over properties pulled out from the target object's prototype chain. If you want to process only properties defined on the target object itself, you should additionally test for `some_object.hasOwnProperty(name)`. |
4,974,727 | This .PHPT test completes: [(from PHPT docs)](http://qa.php.net/write-test.php)
File: `strtr.phpt`
```
--TEST--
strtr() function - basic test for strstr()
--FILE--
<?php
/* Do not change this test it is a README.TESTING example. */
$trans = array("hello"=>"hi", "hi"=>"hello", "a"=>"A", "world"=>"planet");
var_dump(strtr("# hi all, I said hello world! #", $trans));
?>
--EXPECT--
string(32) "# hello All, I sAid hi planet! #"
```
`$ pear run-tests --cgi strtr.phpt`
Output:
```
Running 1 tests
PASS strtr() function - basic test for strstr()[uploadTest.phpt]
TOTAL TIME: 00:00
1 PASSED TESTS
0 SKIPPED TESTS
```
However, when I try running another example test, like [`sample006.phpt`](http://qa.php.net/sample_tests/sample006.php), and any other test that uses `--GET--`, `--POST--`, `--POST_RAW--`, etc., sections, the tests always fail.
My Big Picture Goal is to test file uploads in PHPUnit by way of PHPT as described in [Testing file uploads with PHP](http://qafoo.com/blog/013_testing_file_uploads_with_php.html). The `--POST_RAW--` example used in that article fails for me as well, whereas the other examples pass successfully.
It would appear I have a local config problem, but I have no idea where I would track this down. Not much in Google, unfortunately.
One thing I've noticed between these `--POST--` tests failing, and other regular tests failing, is that the regular test failures always populate the `*.out` file with the failed output of the script. The `--POST--` tests that fail do not have anything in the `*.out` file, even when I am explicitly outputting text.
Do those example PHPT tests using `--POST_RAW--` work for anyone else?
Here are my system specs: (php 5.2, os x 10.6)
```
$ pear -V
PEAR Version: 1.9.1
PHP Version: 5.2.13
Zend Engine Version: 2.2.0
Running on: Darwin mbp.local 10.6.0 Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386 i386
``` | 2011/02/11 | [
"https://Stackoverflow.com/questions/4974727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39539/"
] | You should be able override [theme\_image\_formatter()](http://api.drupal.org/api/drupal/modules--image--image.field.inc/function/theme_image_formatter/7) which is called in [image\_field\_formatter\_view()](http://api.drupal.org/api/drupal/modules--image--image.field.inc/function/image_field_formatter_view/7). | You do not have to use or edit any .tpl.php file. You can access the alt or the title text of the image by doing the following:
1. Add another field to your View, your node's image field (yes, again)
2. Ignore the label and display options and go to the fieldset: *Multiple Field Settings* and uncheck the option: *Display all values in the same row*
3. Next, scroll down to the fieldset: *Rewrite Results* and then click *Rewrite the output of this field*. Check the Replacement Patterns below and you should see tokens for both alt and title. Use whichever is appropriate.
Works for me! |
4,974,727 | This .PHPT test completes: [(from PHPT docs)](http://qa.php.net/write-test.php)
File: `strtr.phpt`
```
--TEST--
strtr() function - basic test for strstr()
--FILE--
<?php
/* Do not change this test it is a README.TESTING example. */
$trans = array("hello"=>"hi", "hi"=>"hello", "a"=>"A", "world"=>"planet");
var_dump(strtr("# hi all, I said hello world! #", $trans));
?>
--EXPECT--
string(32) "# hello All, I sAid hi planet! #"
```
`$ pear run-tests --cgi strtr.phpt`
Output:
```
Running 1 tests
PASS strtr() function - basic test for strstr()[uploadTest.phpt]
TOTAL TIME: 00:00
1 PASSED TESTS
0 SKIPPED TESTS
```
However, when I try running another example test, like [`sample006.phpt`](http://qa.php.net/sample_tests/sample006.php), and any other test that uses `--GET--`, `--POST--`, `--POST_RAW--`, etc., sections, the tests always fail.
My Big Picture Goal is to test file uploads in PHPUnit by way of PHPT as described in [Testing file uploads with PHP](http://qafoo.com/blog/013_testing_file_uploads_with_php.html). The `--POST_RAW--` example used in that article fails for me as well, whereas the other examples pass successfully.
It would appear I have a local config problem, but I have no idea where I would track this down. Not much in Google, unfortunately.
One thing I've noticed between these `--POST--` tests failing, and other regular tests failing, is that the regular test failures always populate the `*.out` file with the failed output of the script. The `--POST--` tests that fail do not have anything in the `*.out` file, even when I am explicitly outputting text.
Do those example PHPT tests using `--POST_RAW--` work for anyone else?
Here are my system specs: (php 5.2, os x 10.6)
```
$ pear -V
PEAR Version: 1.9.1
PHP Version: 5.2.13
Zend Engine Version: 2.2.0
Running on: Darwin mbp.local 10.6.0 Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386 i386
``` | 2011/02/11 | [
"https://Stackoverflow.com/questions/4974727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39539/"
] | You should be able override [theme\_image\_formatter()](http://api.drupal.org/api/drupal/modules--image--image.field.inc/function/theme_image_formatter/7) which is called in [image\_field\_formatter\_view()](http://api.drupal.org/api/drupal/modules--image--image.field.inc/function/image_field_formatter_view/7). | You can use <https://www.drupal.org/project/image_caption_formatter> to display the title text of the image as a caption. |
3,474,146 | I'm an old-school database programmer. And all my life i've working with database via DAL and stored procedures. Now i got a requirement to use Entity Framework.
Could you tell me your expirience and architecture best practicies how to work with it ?
As I know ORM was made for programmers who don't know SQL expression. And this is only benefit of ORM. Am I right ?
I got architecture document and I don't know clearly what I shoud do with ORM. I think that my steps should be:
1) Create complete database
2) Create high-level entities in model such "Price" which is realy consists from few database tables
3) Map database tables on entities. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3474146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383187/"
] | An ORM does a lot more than just allow non-SQL programmers to talk to databases!
Instead of having to deal with loads of handwritten DAL code, and getting back a row/column representation of your data, an ORM turns each row of a table into a strongly-typed object.
So you end up with e.g. a `Customer`, and you can access its phone number as a strongly-typed property:
```
string customerPhone = MyCustomer.PhoneNumber;
```
That is a lot better than:
```
string customerPhone = MyCustomerTable.Rows[5].Column["PhoneNumber"].ToString();
```
You get no support whatsoever from the IDE in making this work - be aware of mistyping the column name! You won't find out 'til runtime - either you get no data back, or you get an exception.... no very pleasant.
It's first of all much easier to use that `Customer` object you get back, the properties are nicely available, strongly-typed, and discoverable in Intellisense, and so forth.
So besides possibly saving you from having to hand-craft a lot of boring SQL and DAL code, an ORM also brings a lot of benefits in using the data from the database - discoverability in your code editor, type safety and more.
I agree - the thought of an ORM generating SQL statements on the fly, and executing those, can be scary. But at least in Entity Framework v4 (.NET 4), Microsoft has done an admirable job of optimizing the SQL being used. It might not be perfect in 100% of the cases, but in a large percentage of the time, it's a lot better than any SQL any non-expert SQL programmer would write...
Plus: in EF4, if you really want to and see a need to, you can always define and use your own Stored procs for INSERT, UPDATE, DELETE on any entity. | I can relate to your sentiment of wanting to have complete control over your SQL. I have been researching ORM usage myself, and while I can't state a case nearly as well as marc\_s has, I thought I might chime in with a couple more points.
I think the point of ORM is to shift the focus away from writing SQL and DAL code, and instead focus more on the business logic. You can be more agile with an ORM tool, because you don't have to refactor your data model or stored procedures every time you change your object model. In fact, ORM essentially give you a layer of abstraction, so you can potentially make changes to your schema without affecting your code, and vice-versa. ORM might not always generate the most efficient SQL, but you may benefit in faster development time. For small projects however, the benefits of ORM might not be worth the extra time spent configuring the ORM.
I know that doesn't answer your questions though.
To your **2nd question**, it seems to me that many developers on S.O. here who are very skilled in SQL still advocate the use of and themselves use ORM tools such as Hibernate, LINQ to SQL, and Entity Framework. In fact, you still need to know SQL sometimes even if you use ORM, and it's typically the more complicated queries, so your theory about ORM being mainly ***"for programmers who don't know SQL"*** might be wrong. Plus you get caching from your ORM layer.
Furthermore, Jeff Atwood, who is the lead developer of S.O. (this site here), claims that he loves SQL (and I'd bet he's very good at it), and he also strives to avoid adding extra tenchnologies to his stack, but yet he choose to use LINQ to SQL to build S.O. Years ago already he claimed that, ["Stored Procedures should be considered database assembly language: for use in only the most performance critical situations."](http://www.codinghorror.com/blog/2004/10/who-needs-stored-procedures-anyways.html)
To your **1st question**, here's another [article from Jeff Atwood's blog that talks about varies ways (including using ORM) to deal with the object-relational impedance mistmatch problem](http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html), which helped me put things in perspective. It's also interesting because his opinion of ORM must have changed since then. In the article he said you should, ***"either abandon relational databases, or abandon objects,"*** as well as, ***"I tend to err on the side of the database-as-model camp."*** But as I said, some of the bullet points helped put things into perspective for me. |
31,891,668 | **MainActivity.java**
Okay, so this is where I load the url now progress bar is visible till the page is loaded and now when I click the links on the page, the progress bar does not appear, I'm searching a fix from 10 hours but none of them are suitable to this conditiion, the progress bar should start as the new url is loaded.
Please Help!
```
public class MainActivity extends Activity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://google.com/");
mWebView.setWebViewClient(new com.c.MyAppWebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
@Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
public void aus (MenuItem menuItem){
findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
});
}
public void cus (MenuItem menuItem){
findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
});
}
```
**activity\_main.xml**
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:indeterminate="false"
android:layout_gravity="center" />
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
</LinearLayout>
``` | 2015/08/08 | [
"https://Stackoverflow.com/questions/31891668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5204816/"
] | if you just want the progress bar to appear over the web view when loading change your layout to a RelativeLayout. Put the progress bar on the bottom so it is draw at the top of the view hierarchy.
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="false"
android:layout_centerInParent="true" />
</RelativeLayout>
```
You also need to override a method on your webview client
```
mWebView.setWebViewClient(new com.c.MyAppWebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}
});
``` | ```
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loadingBar.setVisibility(View.VISIBLE);
loadingBar.bringToFront();
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
loadingBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
});
```
and add this to your xml layout:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:visibility="gone"
android:id="@+id/purchase_loadingbar">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
``` |
8,864,802 | I have a simple page view tracker that uses a combination of PHP and MySQL to keep a running tally of the number of times the page has been refreshed. There is no complex cookies I just needed to know the raw number refreshes that occur.
It looks like this...
```
$link = mysql_connect('**********', '*********', '***********');
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**********", $link);
$query = mysql_query("select value from settings where title like 'search_number'");
$result = mysql_fetch_array($query);
$search_number = $result["value"];
$new_search_number = $search_number + 1;
mysql_query("update settings set value='$new_search_number' where title like 'search_number'");
```
This code appears to work in all the tests I was capable of running but on the live site it returns ridiculously high numbers. We average 400-500 queries a day according to yahoo, "we use search boss", but the page tracker reports 8900+ queries a day. Google analytic confirms yahoo's number. I don't see how this code could fail due to its simplicity. I was hoping somebody could shed some light on what is going on. | 2012/01/14 | [
"https://Stackoverflow.com/questions/8864802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149651/"
] | Bots will hit your page more often than you might think. You can compare to your server logs, and I suspect you will see that many requests for your page.
Also, Google Analytics works client-side, requires JavaScript, and does not always run. This has been predicted to account for as many as 10% or so page views. The bulk of the difference though is that Google Analytics filters out a lot of random hits from bots, as hardly any bots even run the analytics code.
On another note, the way you are doing your queries is a bit precarious. I recommend learning how to do prepared queries with PDO, to avoid SQL injection attacks. | Update the value direcly in MySQL otherwise concurring scripts will overwrite each others values:
```
mysql_query("update settings set value=value + 1 where title like 'search_number'");
``` |
30,599,301 | Here is my onCreate method:
```
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_social_login);
init();
hideActiveSocialNetworks();
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// not called
Log.d("fb_login_sdk", "callback success");
}
@Override
public void onCancel() {
// not called
Log.d("fb_login_sdk", "callback cancel");
}
@Override
public void onError(FacebookException e) {
// not called
Log.d("fb_login_sdk", "callback onError");
}
});
final Activity activity = this;
findViewById(R.id.fb_login_sdk).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("fb_login_sdk", "click");
List<String> perm = new ArrayList<String>();
perm.add("user_friends");
LoginManager.getInstance().logInWithReadPermissions(activity, perm);
}
});
}
```
After login the onSuccess(), onCancel(), onError() methods are not fired.
Documentation: <https://developers.facebook.com/docs/facebook-login/android/v2.3> | 2015/06/02 | [
"https://Stackoverflow.com/questions/30599301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1180686/"
] | Missing this on my activity:
```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
``` | **Your code will work when you add this to your activity class**
```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
``` |
30,599,301 | Here is my onCreate method:
```
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_social_login);
init();
hideActiveSocialNetworks();
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// not called
Log.d("fb_login_sdk", "callback success");
}
@Override
public void onCancel() {
// not called
Log.d("fb_login_sdk", "callback cancel");
}
@Override
public void onError(FacebookException e) {
// not called
Log.d("fb_login_sdk", "callback onError");
}
});
final Activity activity = this;
findViewById(R.id.fb_login_sdk).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("fb_login_sdk", "click");
List<String> perm = new ArrayList<String>();
perm.add("user_friends");
LoginManager.getInstance().logInWithReadPermissions(activity, perm);
}
});
}
```
After login the onSuccess(), onCancel(), onError() methods are not fired.
Documentation: <https://developers.facebook.com/docs/facebook-login/android/v2.3> | 2015/06/02 | [
"https://Stackoverflow.com/questions/30599301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1180686/"
] | Missing this on my activity:
```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
``` | Here is checklist to check whether your Facebook Sdk setup is correct:-
1. Check your manifest if you have setup Facebook initialization properly.
```
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
```
2. Create Facebook CallBackManager variable
```
var fbCallManager = CallbackManager.Factory.create()
```
3. On Click of Login with Facebook button. Put your required permission in Array.
```
LoginManager.getInstance()
.logInWithReadPermissions(this, Arrays.asList("public_profile", "email", "user_friends"))
LoginManager.getInstance().registerCallback(fbCallManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult?) {
//login success
}
override fun onCancel() {
//login cancelled by user
}
override fun onError(error: FacebookException?) {
//login error handle exception
}
})
```
}
4. Add callback result in onActivityResult method
```
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
fbCallManager.onActivityResult(requestCode, resultCode, data)
}
```
5. Provide the Development and Release Key Hashes for Your
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME.android\debug.keystore" | "PATH\_TO\_OPENSSL\_LIBRARY\bin\openssl" sha1 -binary | "PATH\_TO\_OPENSSL\_LIBRARY\bin\openssl" base64
>
> [Download openssl from here](https://code.google.com/archive/p/openssl-for-windows/downloads?fbclid=IwAR1A8cdroVdzLuNY0dSAUsiUsAhkZLifgZMDNraflYPSk5_P8NuU7O6Tzu0)
>
>
>
6. Setup your Keyhash and Launcher activity in Facebook developer console.
References : [Facebook](https://developers.facebook.com/docs/facebook-login/android) |
30,599,301 | Here is my onCreate method:
```
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_social_login);
init();
hideActiveSocialNetworks();
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// not called
Log.d("fb_login_sdk", "callback success");
}
@Override
public void onCancel() {
// not called
Log.d("fb_login_sdk", "callback cancel");
}
@Override
public void onError(FacebookException e) {
// not called
Log.d("fb_login_sdk", "callback onError");
}
});
final Activity activity = this;
findViewById(R.id.fb_login_sdk).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("fb_login_sdk", "click");
List<String> perm = new ArrayList<String>();
perm.add("user_friends");
LoginManager.getInstance().logInWithReadPermissions(activity, perm);
}
});
}
```
After login the onSuccess(), onCancel(), onError() methods are not fired.
Documentation: <https://developers.facebook.com/docs/facebook-login/android/v2.3> | 2015/06/02 | [
"https://Stackoverflow.com/questions/30599301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1180686/"
] | Here is checklist to check whether your Facebook Sdk setup is correct:-
1. Check your manifest if you have setup Facebook initialization properly.
```
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
```
2. Create Facebook CallBackManager variable
```
var fbCallManager = CallbackManager.Factory.create()
```
3. On Click of Login with Facebook button. Put your required permission in Array.
```
LoginManager.getInstance()
.logInWithReadPermissions(this, Arrays.asList("public_profile", "email", "user_friends"))
LoginManager.getInstance().registerCallback(fbCallManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult?) {
//login success
}
override fun onCancel() {
//login cancelled by user
}
override fun onError(error: FacebookException?) {
//login error handle exception
}
})
```
}
4. Add callback result in onActivityResult method
```
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
fbCallManager.onActivityResult(requestCode, resultCode, data)
}
```
5. Provide the Development and Release Key Hashes for Your
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME.android\debug.keystore" | "PATH\_TO\_OPENSSL\_LIBRARY\bin\openssl" sha1 -binary | "PATH\_TO\_OPENSSL\_LIBRARY\bin\openssl" base64
>
> [Download openssl from here](https://code.google.com/archive/p/openssl-for-windows/downloads?fbclid=IwAR1A8cdroVdzLuNY0dSAUsiUsAhkZLifgZMDNraflYPSk5_P8NuU7O6Tzu0)
>
>
>
6. Setup your Keyhash and Launcher activity in Facebook developer console.
References : [Facebook](https://developers.facebook.com/docs/facebook-login/android) | **Your code will work when you add this to your activity class**
```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
``` |
12,276,795 | Note that I am talking about Java 7, since the info.plist specification for a Java .app bundle seems to have changed a bit since Java 6.
Currently my code looks like this:
```
File file = new File( "documentation/index.html" );
if (file.exists()) {
// opens the URI in the browser
GUIUtils.openURI( file.toURI() );
} else {
// opens the URI in the browser
GUIUtils.openURI( getClass().getResource( "/documentation/index.html" ).toURI() );
}
```
In the `Java` subfolder in the app bundle, I have a "documentation" subfolder. I have tried multiple things, to no avail:
* In the info.plist, setting the working directory to the Java folder (with a `-Duser.dir` JVMArgument property) - the file seemingly has the right path, but `file.exists()` returns false.
* Trying to set the ClassPath to the Java folder. (`getClass().getResource()` still returns null) | 2012/09/05 | [
"https://Stackoverflow.com/questions/12276795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] | If you're prepared to use the `com.apple` extensions, `com.apple.eio.FileManager.getPathToApplicationBundle()` will give you the base path to your bundle, and you can then create a `File` relative to that. | As of Java 9, `com.apple` is not accessible.
Java 9 uses modules to export (and expose) packages so `com.apple` is now unusable and deprecated. According to [this](http://openjdk.java.net/jeps/272), `java.awt` should provide similar API functionalities.
Just wanted to provide this update as I ran into this issue following the accepted answer.
`System.getenv("LOCALAPPDATA")` can be used as an option to get application environment. |
30,498,006 | I have below json in string as parameter to a WebMethod.
How can I deserialize in such a way that value comes in Key value pair.
Json String Parameter:
```
["Ref No,0","Date,0","Amt,0","Sender Name,0","Sender Add,0","Beneficiary Name,0","Beneficiary Add,0","Phone,0","Secret Code,0","Secret Ans,0","Preferred Id,0"]
```
WebMethod:
```
[System.Web.Services.WebMethod]
public static string SaveMappings(string mappingData)
{
//string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//object obj;
//var data = serializer.Deserialize(mappingData,);
var data = mappingData.ToArray();
if (data != null)
{
}
var d2 = mappingData.Split(',');
if (d2!=null)
{
}
return mappingData;
}
``` | 2015/05/28 | [
"https://Stackoverflow.com/questions/30498006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795420/"
] | If you need to work with JSON data then use Newtonsoft.JSON library.
Convert the object to an array of strings and then split every line.
With this approach you can be sure that the given string is actually an JSON array and it is correct.
```
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
string[] objs = JsonConvert.DeserializeObject<string[]>(str);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var obj in objs)
{
var keyValue = obj.Split(',');
dic.Add(keyValue[0], keyValue[1]);
}
foreach (var record in dic)
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
```
Or this one using LINQ. It looks better and it can be written faster. However, it is less optimal (two calls of Split instead of one).
```
public Dictionary<string, string> FromJsonArray(string jsonArray)
{
return JsonConvert.DeserializeObject<string[]>(jsonArray)
.ToDictionary(obj => obj.Split(',')[0], obj => obj.Split(',')[1]);
}
// ...
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
foreach (var record in FromJsonArray(str))
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
``` | why don't you just change every `','` in the string array to `':'` then pass it to the method, from what you wrote in the question, this should work |
12,977,844 | Is there a C# / Windows Forms equivalent to Android's [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)?
For example, say I am running a (long-running) task on a worker thread and at the end I want to post the result to a GUI control (which of course I can't do from the worker thread). Is there a function as simple as [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29) that would allow me to post that refresh-display for processing by the UI thread? | 2012/10/19 | [
"https://Stackoverflow.com/questions/12977844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088880/"
] | Each control in WinForms inherits the `Invoke` and `BeginInvoke` methods.
[Invoke](http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) will run the delegate synchronously whereas [BeginInvoke](http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx) runs it asynchronously. | Look at the `Control.Invoke` method.
From MSDN: "Executes the specified delegate on the thread that owns the control's underlying window handle." |
12,977,844 | Is there a C# / Windows Forms equivalent to Android's [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)?
For example, say I am running a (long-running) task on a worker thread and at the end I want to post the result to a GUI control (which of course I can't do from the worker thread). Is there a function as simple as [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29) that would allow me to post that refresh-display for processing by the UI thread? | 2012/10/19 | [
"https://Stackoverflow.com/questions/12977844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088880/"
] | A typical way to do this is with a System.Windows.Forms.Control:
```
control.BeginInvoke((MethodInvoker)delegate { ... });
```
But, the control's handle must have already been initialized on the UI thread. A simple
```
IntPtr ignored = control.Handle;
```
on the UI thread will accomplish that. | Look at the `Control.Invoke` method.
From MSDN: "Executes the specified delegate on the thread that owns the control's underlying window handle." |
12,977,844 | Is there a C# / Windows Forms equivalent to Android's [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)?
For example, say I am running a (long-running) task on a worker thread and at the end I want to post the result to a GUI control (which of course I can't do from the worker thread). Is there a function as simple as [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29) that would allow me to post that refresh-display for processing by the UI thread? | 2012/10/19 | [
"https://Stackoverflow.com/questions/12977844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088880/"
] | Each control in WinForms inherits the `Invoke` and `BeginInvoke` methods.
[Invoke](http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) will run the delegate synchronously whereas [BeginInvoke](http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx) runs it asynchronously. | If you've got access to a winforms control or form, simply call [`Control.Invoke`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx) or [`Control.BeginInvoke`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) on that control or form. |
12,977,844 | Is there a C# / Windows Forms equivalent to Android's [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)?
For example, say I am running a (long-running) task on a worker thread and at the end I want to post the result to a GUI control (which of course I can't do from the worker thread). Is there a function as simple as [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29) that would allow me to post that refresh-display for processing by the UI thread? | 2012/10/19 | [
"https://Stackoverflow.com/questions/12977844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088880/"
] | A typical way to do this is with a System.Windows.Forms.Control:
```
control.BeginInvoke((MethodInvoker)delegate { ... });
```
But, the control's handle must have already been initialized on the UI thread. A simple
```
IntPtr ignored = control.Handle;
```
on the UI thread will accomplish that. | If you've got access to a winforms control or form, simply call [`Control.Invoke`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx) or [`Control.BeginInvoke`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) on that control or form. |
12,977,844 | Is there a C# / Windows Forms equivalent to Android's [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)?
For example, say I am running a (long-running) task on a worker thread and at the end I want to post the result to a GUI control (which of course I can't do from the worker thread). Is there a function as simple as [runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29) that would allow me to post that refresh-display for processing by the UI thread? | 2012/10/19 | [
"https://Stackoverflow.com/questions/12977844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088880/"
] | Each control in WinForms inherits the `Invoke` and `BeginInvoke` methods.
[Invoke](http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) will run the delegate synchronously whereas [BeginInvoke](http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx) runs it asynchronously. | A typical way to do this is with a System.Windows.Forms.Control:
```
control.BeginInvoke((MethodInvoker)delegate { ... });
```
But, the control's handle must have already been initialized on the UI thread. A simple
```
IntPtr ignored = control.Handle;
```
on the UI thread will accomplish that. |
36,974,458 | I have a blank data in mysql, and when I call it that blank data. The Number will Appear... Example
1. Sample Data
2. --Blank--
3. Sample Data
I want to remove the Number 2. so that it will become 1-2..
```
$num = 0;
```
I use $num++ foreach data;
```
$num = 0;
mysql_connect('localhost','root','');
mysql_select_db('dbase');
$SQL = " SELECT * FROM table ";
$query = mysql_query($SQL);
while($data = mysql_fetch_assoc($query))
{
$num++;
echo $num;
echo $data['Name']
}
```
OUTPUT :
```
1. SAMPLE
2.
3. SAMPLE
```
I want to make this
```
1. SAMPLE
2. SAMPLE
``` | 2016/05/02 | [
"https://Stackoverflow.com/questions/36974458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6270218/"
] | The simplest method will be to use
```
.*?(?:love|like).*(programming)
```
**[Regex Demo](https://regex101.com/r/xB8bV5/1)**
Using `lookaheads`
```
(?=.*?(love|like).*?(programming))
```
**[Regex Demo](https://regex101.com/r/xB8bV5/2)**
*Java Code*
```
String line = "I love programming a lov lot!";
String x = "programming";
String pattern = ".*?(?:love|like).*(" + x + ")";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
while (m.find()) {
String tmp = m.group(1);
System.out.println(tmp);
}
```
**[Ideone Demo](http://ideone.com/esKyZk)** | This is the essay way to doing this as I think
```
String s = "I love programming a lot!";
if (s.contains("like") || s.contains("love")) {
System.out.println(s);
}
``` |
36,974,458 | I have a blank data in mysql, and when I call it that blank data. The Number will Appear... Example
1. Sample Data
2. --Blank--
3. Sample Data
I want to remove the Number 2. so that it will become 1-2..
```
$num = 0;
```
I use $num++ foreach data;
```
$num = 0;
mysql_connect('localhost','root','');
mysql_select_db('dbase');
$SQL = " SELECT * FROM table ";
$query = mysql_query($SQL);
while($data = mysql_fetch_assoc($query))
{
$num++;
echo $num;
echo $data['Name']
}
```
OUTPUT :
```
1. SAMPLE
2.
3. SAMPLE
```
I want to make this
```
1. SAMPLE
2. SAMPLE
``` | 2016/05/02 | [
"https://Stackoverflow.com/questions/36974458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6270218/"
] | The simplest method will be to use
```
.*?(?:love|like).*(programming)
```
**[Regex Demo](https://regex101.com/r/xB8bV5/1)**
Using `lookaheads`
```
(?=.*?(love|like).*?(programming))
```
**[Regex Demo](https://regex101.com/r/xB8bV5/2)**
*Java Code*
```
String line = "I love programming a lov lot!";
String x = "programming";
String pattern = ".*?(?:love|like).*(" + x + ")";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
while (m.find()) {
String tmp = m.group(1);
System.out.println(tmp);
}
```
**[Ideone Demo](http://ideone.com/esKyZk)** | ```
String s = "I love programming a lot!";
String condition1 = s.indexOf("love");
String condition2 = s.indexOf("like");
String condition3 = s.indexOf("programming");
if (condition1 < condition3 || condition2 < condition3) {
System.out.println("programming"); //or get value if not hardcoded
}
``` |
36,974,458 | I have a blank data in mysql, and when I call it that blank data. The Number will Appear... Example
1. Sample Data
2. --Blank--
3. Sample Data
I want to remove the Number 2. so that it will become 1-2..
```
$num = 0;
```
I use $num++ foreach data;
```
$num = 0;
mysql_connect('localhost','root','');
mysql_select_db('dbase');
$SQL = " SELECT * FROM table ";
$query = mysql_query($SQL);
while($data = mysql_fetch_assoc($query))
{
$num++;
echo $num;
echo $data['Name']
}
```
OUTPUT :
```
1. SAMPLE
2.
3. SAMPLE
```
I want to make this
```
1. SAMPLE
2. SAMPLE
``` | 2016/05/02 | [
"https://Stackoverflow.com/questions/36974458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6270218/"
] | Don't use Pattern, just use `replaceAll()`:
```
String lovedThing = str = str.replaceAll(".*(love|like)\\s+(\\S+).*", "$2");
```
This matches the whole string, replacing it with what's captured in group 2, effectively "extracting" the target, which is matched as "non whitespace chars". | This is the essay way to doing this as I think
```
String s = "I love programming a lot!";
if (s.contains("like") || s.contains("love")) {
System.out.println(s);
}
``` |
36,974,458 | I have a blank data in mysql, and when I call it that blank data. The Number will Appear... Example
1. Sample Data
2. --Blank--
3. Sample Data
I want to remove the Number 2. so that it will become 1-2..
```
$num = 0;
```
I use $num++ foreach data;
```
$num = 0;
mysql_connect('localhost','root','');
mysql_select_db('dbase');
$SQL = " SELECT * FROM table ";
$query = mysql_query($SQL);
while($data = mysql_fetch_assoc($query))
{
$num++;
echo $num;
echo $data['Name']
}
```
OUTPUT :
```
1. SAMPLE
2.
3. SAMPLE
```
I want to make this
```
1. SAMPLE
2. SAMPLE
``` | 2016/05/02 | [
"https://Stackoverflow.com/questions/36974458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6270218/"
] | Don't use Pattern, just use `replaceAll()`:
```
String lovedThing = str = str.replaceAll(".*(love|like)\\s+(\\S+).*", "$2");
```
This matches the whole string, replacing it with what's captured in group 2, effectively "extracting" the target, which is matched as "non whitespace chars". | ```
String s = "I love programming a lot!";
String condition1 = s.indexOf("love");
String condition2 = s.indexOf("like");
String condition3 = s.indexOf("programming");
if (condition1 < condition3 || condition2 < condition3) {
System.out.println("programming"); //or get value if not hardcoded
}
``` |
46,262,003 | I need to write upload file code using vertx and then save it into PostgreSQL table. but as file is uploaded in multipart and asynchronously I am unable to get byte complete array. Following is my code
```
public static void uploadLogo(RoutingContext routingContext) {
HttpServerRequest request = routingContext.request();
HttpServerResponse response = routingContext.response();
request.setExpectMultipart(true);
request.uploadHandler(upload -> {
upload.handler(chunk -> {
byte[] fileBytes = chunk.getBytes();
});
upload.endHandler(endHandler -> {
System.out.println("uploaded successfully");
});
upload.exceptionHandler(cause -> {
request.response().setChunked(true).end("Upload failed");
});
});
}
```
Here I get byte array in `fileBytes` but only part at a time. I dont understand how to add next byte array to it as it works asynchronously. Is there any way to get byte array of entire file | 2017/09/17 | [
"https://Stackoverflow.com/questions/46262003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186584/"
] | Hi I am able to extract bytes by using below code :
```
router.post("/upload").handler(ctx->{
ctx.request().setExpectMultipart(true);
ctx.request().bodyHandler(buffer->{
byte[] bytes=buffer.getBytes();
//transfer bytes to whichever service you want from here
});
ctx.response().end();
});
``` | Request context has `.fileUploads()` method for that.
See here for the full example: <https://github.com/vert-x3/vertx-examples/blob/master/web-examples/src/main/java/io/vertx/example/web/upload/Server.java#L42>
If you want to access uploaded files:
```
Vertx vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.post("/upload").handler(ctx -> {
for (FileUpload fu : ctx.fileUploads()) {
vertx.fileSystem().readFile(fu.uploadedFileName(), fileHandler -> {
// Do something with buffer
});
}
});
``` |
46,262,003 | I need to write upload file code using vertx and then save it into PostgreSQL table. but as file is uploaded in multipart and asynchronously I am unable to get byte complete array. Following is my code
```
public static void uploadLogo(RoutingContext routingContext) {
HttpServerRequest request = routingContext.request();
HttpServerResponse response = routingContext.response();
request.setExpectMultipart(true);
request.uploadHandler(upload -> {
upload.handler(chunk -> {
byte[] fileBytes = chunk.getBytes();
});
upload.endHandler(endHandler -> {
System.out.println("uploaded successfully");
});
upload.exceptionHandler(cause -> {
request.response().setChunked(true).end("Upload failed");
});
});
}
```
Here I get byte array in `fileBytes` but only part at a time. I dont understand how to add next byte array to it as it works asynchronously. Is there any way to get byte array of entire file | 2017/09/17 | [
"https://Stackoverflow.com/questions/46262003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186584/"
] | Hi I am able to extract bytes by using below code :
```
router.post("/upload").handler(ctx->{
ctx.request().setExpectMultipart(true);
ctx.request().bodyHandler(buffer->{
byte[] bytes=buffer.getBytes();
//transfer bytes to whichever service you want from here
});
ctx.response().end();
});
``` | to get the uploaded files you have to use `fileUploads()` method after you can get the byte array.
```
JsonArray attachments = new JsonArray();
for (FileUpload f : routingContext.fileUploads()) {
Buffer fileUploaded = routingContext.vertx().fileSystem().readFileBlocking(f.uploadedFileName());
attachments.add(new JsonObject().put("body",fileUploaded.getBytes()).put("contentType",f.contentType())
.put("fileName",f.fileName()));
}
``` |
46,262,003 | I need to write upload file code using vertx and then save it into PostgreSQL table. but as file is uploaded in multipart and asynchronously I am unable to get byte complete array. Following is my code
```
public static void uploadLogo(RoutingContext routingContext) {
HttpServerRequest request = routingContext.request();
HttpServerResponse response = routingContext.response();
request.setExpectMultipart(true);
request.uploadHandler(upload -> {
upload.handler(chunk -> {
byte[] fileBytes = chunk.getBytes();
});
upload.endHandler(endHandler -> {
System.out.println("uploaded successfully");
});
upload.exceptionHandler(cause -> {
request.response().setChunked(true).end("Upload failed");
});
});
}
```
Here I get byte array in `fileBytes` but only part at a time. I dont understand how to add next byte array to it as it works asynchronously. Is there any way to get byte array of entire file | 2017/09/17 | [
"https://Stackoverflow.com/questions/46262003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186584/"
] | Hi I am able to extract bytes by using below code :
```
router.post("/upload").handler(ctx->{
ctx.request().setExpectMultipart(true);
ctx.request().bodyHandler(buffer->{
byte[] bytes=buffer.getBytes();
//transfer bytes to whichever service you want from here
});
ctx.response().end();
});
``` | You need to build it manually by appending incoming parts in `upload.handler` into Buffer. Once `upload.endHandler` is called the upload process has ended, and you can get the resulting buffer and its byte array.
```
request.uploadHandler(upload -> {
Buffer cache = null;
upload.handler(chunk -> {
if (cache == null) {
cache = chunk;
} else {
cache.appendBuffer(chunk);
}
});
upload.endHandler(end -> {
byte[] result = cache.get().getBytes();
});
});
``` |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | Keeping in mind comments of **Mr.E.** and **Arran** I made my list traversal fully on CSS selectors. The tricky part was about my own list structure and marks (changing classes, etc.), as well as about creating required selectors on the fly and keeping them in memory during traversal.
I disposed waiting for several elements by searching for anything that is not loading state. You may use ":nth-child" selector as well like here:
```
#in for loop with enumerate for i
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
```
This is my hard-commented code solution for example:
```
def parse_crippled_shifted_list(driver, frame, selector, level=1, parent_id=0, path=None):
"""
Traversal of html list of special structure (you can't know if element has sub list unless you enter it).
Supports start from remembered list element.
Nested lists have classes "closed" and "last closed" when closed and "open" and "last open" when opened (on <li>).
Elements themselves have classes "leaf" and "last leaf" in both cases.
Nested lists situate in <li> element as <ul> list. Each <ul> appears after clicking <a> in each <li>.
If you click <a> of leaf, page in another frame will load.
driver - WebDriver; frame - frame of the list; selector - selector to current list (<ul>);
level - level of depth, just for console output formatting, parent_id - id of parent category (in DB),
path - remained path in categories (ORM objects) to target category to start with.
"""
# Add current level list elements
# This method selects all but loading. Just what is needed to exclude.
selector.append(' > li > a:not([class=loading])')
# Wait for child list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "%s timed out" % ''.join(selector)
else:
# List is loaded
del selector[-1] # selector correction: delete last part aimed to get loaded content
selector.append(' > li')
children = driver.find_elements_by_css_selector(''.join(selector)) # fetch list elements
# Walk the whole list
for i, child in enumerate(children):
del selector[-1] # delete non-unique li tag selector
if selector[-1] != ' > ul' and selector[-1] != 'ul.ltr':
del selector[-1]
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
selector.append(' > a') # add 'li > a' reference to click
child_link = driver.find_element_by_css_selector(''.join(selector))
# If we parse freely further (no need to start from remembered position)
if not path:
# Open child
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.message(), '\n\n'
else:
# Determine its type
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
new_parent_id = process_category_case(child_link, parent_id, level) # add category to DB
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Parse nested list
else:
parse_crippled_shifted_list(driver, frame, selector, level + 1, new_parent_id)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf' or current_li.get_attribute('class') == 'last leaf':
process_page_case(driver, child_link, level)
else:
raise Exception('Damn! Alien class: %s' % current_li.get_attribute('class'))
# If it's required to continue from specified category
else:
# Check if it's required category
if child_link.text == path[0].name:
# Open required category
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.msg, '\n\n'
else:
# This element of list must be always category (have nested list)
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Process this nested list
else:
last = path.pop(0)
if len(path) > 0: # If more to parse
print "\t" * level, "Going deeper to: %s" % ''.join(selector)
parse_crippled_shifted_list(driver, frame, selector, level + 1,
parent_id=last.id, path=path)
else: # Current is required
print "\t" * level, "Returning target category: ", ''.join(selector)
path = None
parse_crippled_shifted_list(driver, frame, selector, level + 1, last.id, path=None)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf':
pass
else:
print "dummy"
del selector[-2:]
``` | (1) You did not mention the error you get with it
(2) Since you mention
>
> ...because driver (current element passed to this function)...
>
>
>
I'll assume this is actually a WebElement. In this case, instead of passing the object itself to your method, simply pass the selector that finds that WebElement (in your case, the `ul`). If the "driver gets lost in DOM", it could be that re-creating it inside the `while current_wait < limit:` loop could mitigate the problem
(3) yeap, `time.sleep()` will only get you that far
(4) Since the `li` elements loaded dynamically contain `class=closed`, instead of `(By.XPATH, './/ul')`, you could try `(By.CSS_SELECTOR, 'ul > li.closed')` (more details on CSS Selectors [here](http://saucelabs.com/resources/selenium/css-selectors)) |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | First and foremost the elements are [AJAX](https://www.w3schools.com/xml/ajax_intro.asp) elements.
Now, as per the requirement to locate all the desired elements and create a *list*, the simplest approach would be to induce [WebDriverWait](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336) for the [`visibility_of_all_elements_located()`](https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.visibility_of_all_elements_located) and you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `CSS_SELECTOR`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.ltr li[id^='t_b_'] > a[id^='t_a_'][href]")))
```
* Using `XPATH`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")))
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
---
Incase your usecase is to wait for certain number of elements to be loaded e.g. **10** elements, you can use you can use the *`lambda`* function as follows:
* Using `>`:
```
myLength = 9
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) > int(myLength))
```
* Using `==`:
```
myLength = 10
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) == int(myLength))
```
>
> You can find a relevant discussion in [How to wait for number of elements to be loaded using Selenium and Python](https://stackoverflow.com/questions/64746509/how-to-wait-for-number-of-elements-to-be-loaded-using-selenium-and-python/64751105#64751105)
>
>
>
---
References
----------
You can find a couple of relevant detailed discussions in:
* [Getting specific elements in selenium](https://stackoverflow.com/questions/64068370/getting-specific-elements-in-selenium/64071682#64071682)
* [Cannot find table element from div element in selenium python](https://stackoverflow.com/questions/59868291/cannot-find-table-element-from-div-element-in-selenium-python/59868504#59868504)
* [Extract text from an aria-label selenium webdriver (python)](https://stackoverflow.com/questions/63946115/extract-text-from-an-aria-label-selenium-webdriver-python/63946412#63946412) | (1) You did not mention the error you get with it
(2) Since you mention
>
> ...because driver (current element passed to this function)...
>
>
>
I'll assume this is actually a WebElement. In this case, instead of passing the object itself to your method, simply pass the selector that finds that WebElement (in your case, the `ul`). If the "driver gets lost in DOM", it could be that re-creating it inside the `while current_wait < limit:` loop could mitigate the problem
(3) yeap, `time.sleep()` will only get you that far
(4) Since the `li` elements loaded dynamically contain `class=closed`, instead of `(By.XPATH, './/ul')`, you could try `(By.CSS_SELECTOR, 'ul > li.closed')` (more details on CSS Selectors [here](http://saucelabs.com/resources/selenium/css-selectors)) |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | I created `AllEc` which basically piggybacks on WebDriverWait.until logic.
This will wait until the timeout occurs or when all of the elements have been found.
```
from typing import Callable
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
class AllEc(object):
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __call__(self, driver):
try:
for fn in self.ecs:
if not fn(driver):
return False
return True
except StaleElementReferenceException:
return False
# usage example:
wait = WebDriverWait(driver, timeout)
ec1 = EC.invisibility_of_element_located(locator1)
ec2 = EC.invisibility_of_element_located(locator2)
ec3 = EC.invisibility_of_element_located(locator3)
all_ec = AllEc(ec1, ec2, ec3, description="Required elements to show page has loaded.")
found_elements = wait.until(all_ec, "Could not find all expected elements")
```
---
Alternatively I created AnyEc to look for multiple elements but returns on the first one found.
```
class AnyEc(object):
"""
Use with WebDriverWait to combine expected_conditions in an OR.
Example usage:
>>> wait = WebDriverWait(driver, 30)
>>> either = AnyEc(expectedcondition1, expectedcondition2, expectedcondition3, etc...)
>>> found = wait.until(either, "Cannot find any of the expected conditions")
"""
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __iter__(self):
return self.ecs.__iter__()
def __call__(self, driver):
for fn in self.ecs:
try:
rt = fn(driver)
if rt:
return rt
except TypeError as exc:
raise exc
except Exception as exc:
# print(exc)
pass
def __repr__(self):
return " ".join(f"{e!r}," for e in self.ecs)
def __str__(self):
return f"{self.description!s}"
either = AnyEc(ec1, ec2, ec3)
found_element = wait.until(either, "Could not find any of the expected elements")
```
---
Lastly, if it's possible to do so, you could try waiting for Ajax to be finished.
This is not useful in all cases -- e.g. Ajax is always active. In the cases where Ajax runs and finishes it can work. There are also some ajax libraries that do not set the `active` attribute, so double check that you can rely on this.
```
def is_ajax_complete(driver)
rt = driver.execute_script("return jQuery.active", *args)
return rt == 0
wait.until(lambda driver: is_ajax_complete(driver), "Ajax did not finish")
``` | (1) You did not mention the error you get with it
(2) Since you mention
>
> ...because driver (current element passed to this function)...
>
>
>
I'll assume this is actually a WebElement. In this case, instead of passing the object itself to your method, simply pass the selector that finds that WebElement (in your case, the `ul`). If the "driver gets lost in DOM", it could be that re-creating it inside the `while current_wait < limit:` loop could mitigate the problem
(3) yeap, `time.sleep()` will only get you that far
(4) Since the `li` elements loaded dynamically contain `class=closed`, instead of `(By.XPATH, './/ul')`, you could try `(By.CSS_SELECTOR, 'ul > li.closed')` (more details on CSS Selectors [here](http://saucelabs.com/resources/selenium/css-selectors)) |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | Keeping in mind comments of **Mr.E.** and **Arran** I made my list traversal fully on CSS selectors. The tricky part was about my own list structure and marks (changing classes, etc.), as well as about creating required selectors on the fly and keeping them in memory during traversal.
I disposed waiting for several elements by searching for anything that is not loading state. You may use ":nth-child" selector as well like here:
```
#in for loop with enumerate for i
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
```
This is my hard-commented code solution for example:
```
def parse_crippled_shifted_list(driver, frame, selector, level=1, parent_id=0, path=None):
"""
Traversal of html list of special structure (you can't know if element has sub list unless you enter it).
Supports start from remembered list element.
Nested lists have classes "closed" and "last closed" when closed and "open" and "last open" when opened (on <li>).
Elements themselves have classes "leaf" and "last leaf" in both cases.
Nested lists situate in <li> element as <ul> list. Each <ul> appears after clicking <a> in each <li>.
If you click <a> of leaf, page in another frame will load.
driver - WebDriver; frame - frame of the list; selector - selector to current list (<ul>);
level - level of depth, just for console output formatting, parent_id - id of parent category (in DB),
path - remained path in categories (ORM objects) to target category to start with.
"""
# Add current level list elements
# This method selects all but loading. Just what is needed to exclude.
selector.append(' > li > a:not([class=loading])')
# Wait for child list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "%s timed out" % ''.join(selector)
else:
# List is loaded
del selector[-1] # selector correction: delete last part aimed to get loaded content
selector.append(' > li')
children = driver.find_elements_by_css_selector(''.join(selector)) # fetch list elements
# Walk the whole list
for i, child in enumerate(children):
del selector[-1] # delete non-unique li tag selector
if selector[-1] != ' > ul' and selector[-1] != 'ul.ltr':
del selector[-1]
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
selector.append(' > a') # add 'li > a' reference to click
child_link = driver.find_element_by_css_selector(''.join(selector))
# If we parse freely further (no need to start from remembered position)
if not path:
# Open child
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.message(), '\n\n'
else:
# Determine its type
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
new_parent_id = process_category_case(child_link, parent_id, level) # add category to DB
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Parse nested list
else:
parse_crippled_shifted_list(driver, frame, selector, level + 1, new_parent_id)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf' or current_li.get_attribute('class') == 'last leaf':
process_page_case(driver, child_link, level)
else:
raise Exception('Damn! Alien class: %s' % current_li.get_attribute('class'))
# If it's required to continue from specified category
else:
# Check if it's required category
if child_link.text == path[0].name:
# Open required category
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.msg, '\n\n'
else:
# This element of list must be always category (have nested list)
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Process this nested list
else:
last = path.pop(0)
if len(path) > 0: # If more to parse
print "\t" * level, "Going deeper to: %s" % ''.join(selector)
parse_crippled_shifted_list(driver, frame, selector, level + 1,
parent_id=last.id, path=path)
else: # Current is required
print "\t" * level, "Returning target category: ", ''.join(selector)
path = None
parse_crippled_shifted_list(driver, frame, selector, level + 1, last.id, path=None)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf':
pass
else:
print "dummy"
del selector[-2:]
``` | This How I solved the problem that I want to wait until certain amount of post where complete load through AJAX
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# create a new Chrome session
driver = webdriver.Chrome()
# navigate to your web app.
driver.get("http://my.local.web")
# get the search button
seemore_button = driver.find_element_by_id("seemoreID")
# Count the cant of post
seemore_button.click()
# Wait for 30 sec, until AJAX search load the content
WebDriverWait(driver,30).until(EC.visibility_of_all_elements_located(By.CLASS_NAME, "post")))
# Get the list of post
listpost = driver.find_elements_by_class_name("post")
``` |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | First and foremost the elements are [AJAX](https://www.w3schools.com/xml/ajax_intro.asp) elements.
Now, as per the requirement to locate all the desired elements and create a *list*, the simplest approach would be to induce [WebDriverWait](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336) for the [`visibility_of_all_elements_located()`](https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.visibility_of_all_elements_located) and you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `CSS_SELECTOR`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.ltr li[id^='t_b_'] > a[id^='t_a_'][href]")))
```
* Using `XPATH`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")))
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
---
Incase your usecase is to wait for certain number of elements to be loaded e.g. **10** elements, you can use you can use the *`lambda`* function as follows:
* Using `>`:
```
myLength = 9
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) > int(myLength))
```
* Using `==`:
```
myLength = 10
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) == int(myLength))
```
>
> You can find a relevant discussion in [How to wait for number of elements to be loaded using Selenium and Python](https://stackoverflow.com/questions/64746509/how-to-wait-for-number-of-elements-to-be-loaded-using-selenium-and-python/64751105#64751105)
>
>
>
---
References
----------
You can find a couple of relevant detailed discussions in:
* [Getting specific elements in selenium](https://stackoverflow.com/questions/64068370/getting-specific-elements-in-selenium/64071682#64071682)
* [Cannot find table element from div element in selenium python](https://stackoverflow.com/questions/59868291/cannot-find-table-element-from-div-element-in-selenium-python/59868504#59868504)
* [Extract text from an aria-label selenium webdriver (python)](https://stackoverflow.com/questions/63946115/extract-text-from-an-aria-label-selenium-webdriver-python/63946412#63946412) | Keeping in mind comments of **Mr.E.** and **Arran** I made my list traversal fully on CSS selectors. The tricky part was about my own list structure and marks (changing classes, etc.), as well as about creating required selectors on the fly and keeping them in memory during traversal.
I disposed waiting for several elements by searching for anything that is not loading state. You may use ":nth-child" selector as well like here:
```
#in for loop with enumerate for i
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
```
This is my hard-commented code solution for example:
```
def parse_crippled_shifted_list(driver, frame, selector, level=1, parent_id=0, path=None):
"""
Traversal of html list of special structure (you can't know if element has sub list unless you enter it).
Supports start from remembered list element.
Nested lists have classes "closed" and "last closed" when closed and "open" and "last open" when opened (on <li>).
Elements themselves have classes "leaf" and "last leaf" in both cases.
Nested lists situate in <li> element as <ul> list. Each <ul> appears after clicking <a> in each <li>.
If you click <a> of leaf, page in another frame will load.
driver - WebDriver; frame - frame of the list; selector - selector to current list (<ul>);
level - level of depth, just for console output formatting, parent_id - id of parent category (in DB),
path - remained path in categories (ORM objects) to target category to start with.
"""
# Add current level list elements
# This method selects all but loading. Just what is needed to exclude.
selector.append(' > li > a:not([class=loading])')
# Wait for child list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "%s timed out" % ''.join(selector)
else:
# List is loaded
del selector[-1] # selector correction: delete last part aimed to get loaded content
selector.append(' > li')
children = driver.find_elements_by_css_selector(''.join(selector)) # fetch list elements
# Walk the whole list
for i, child in enumerate(children):
del selector[-1] # delete non-unique li tag selector
if selector[-1] != ' > ul' and selector[-1] != 'ul.ltr':
del selector[-1]
selector.append(' > li:nth-child(%i)' % (i + 1)) # identify child <li> by its order pos
selector.append(' > a') # add 'li > a' reference to click
child_link = driver.find_element_by_css_selector(''.join(selector))
# If we parse freely further (no need to start from remembered position)
if not path:
# Open child
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.message(), '\n\n'
else:
# Determine its type
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
new_parent_id = process_category_case(child_link, parent_id, level) # add category to DB
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Parse nested list
else:
parse_crippled_shifted_list(driver, frame, selector, level + 1, new_parent_id)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf' or current_li.get_attribute('class') == 'last leaf':
process_page_case(driver, child_link, level)
else:
raise Exception('Damn! Alien class: %s' % current_li.get_attribute('class'))
# If it's required to continue from specified category
else:
# Check if it's required category
if child_link.text == path[0].name:
# Open required category
try:
double_click(driver, child_link)
except InvalidElementStateException:
print "\n\nERROR\n", InvalidElementStateException.msg, '\n\n'
else:
# This element of list must be always category (have nested list)
del selector[-1] # delete changed and already useless link reference
# If <li> is category, it would have <ul> as child now and class="open"
# Check by class is priority, because <li> exists for sure.
current_li = driver.find_element_by_css_selector(''.join(selector))
# Category case - BRANCH
if current_li.get_attribute('class') == 'open' or current_li.get_attribute('class') == 'last open':
selector.append(' > ul') # forward to nested list
# Wait for nested list to load
try:
query = WebDriverWait(driver, WAIT_LONG_TIME).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, ''.join(selector))))
except TimeoutException:
print "\t" * level, "%s timed out (%i secs). Failed to load nested list." %\
''.join(selector), WAIT_LONG_TIME
# Process this nested list
else:
last = path.pop(0)
if len(path) > 0: # If more to parse
print "\t" * level, "Going deeper to: %s" % ''.join(selector)
parse_crippled_shifted_list(driver, frame, selector, level + 1,
parent_id=last.id, path=path)
else: # Current is required
print "\t" * level, "Returning target category: ", ''.join(selector)
path = None
parse_crippled_shifted_list(driver, frame, selector, level + 1, last.id, path=None)
# Page case - LEAF
elif current_li.get_attribute('class') == 'leaf':
pass
else:
print "dummy"
del selector[-2:]
``` |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | First and foremost the elements are [AJAX](https://www.w3schools.com/xml/ajax_intro.asp) elements.
Now, as per the requirement to locate all the desired elements and create a *list*, the simplest approach would be to induce [WebDriverWait](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336) for the [`visibility_of_all_elements_located()`](https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.visibility_of_all_elements_located) and you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `CSS_SELECTOR`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.ltr li[id^='t_b_'] > a[id^='t_a_'][href]")))
```
* Using `XPATH`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")))
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
---
Incase your usecase is to wait for certain number of elements to be loaded e.g. **10** elements, you can use you can use the *`lambda`* function as follows:
* Using `>`:
```
myLength = 9
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) > int(myLength))
```
* Using `==`:
```
myLength = 10
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) == int(myLength))
```
>
> You can find a relevant discussion in [How to wait for number of elements to be loaded using Selenium and Python](https://stackoverflow.com/questions/64746509/how-to-wait-for-number-of-elements-to-be-loaded-using-selenium-and-python/64751105#64751105)
>
>
>
---
References
----------
You can find a couple of relevant detailed discussions in:
* [Getting specific elements in selenium](https://stackoverflow.com/questions/64068370/getting-specific-elements-in-selenium/64071682#64071682)
* [Cannot find table element from div element in selenium python](https://stackoverflow.com/questions/59868291/cannot-find-table-element-from-div-element-in-selenium-python/59868504#59868504)
* [Extract text from an aria-label selenium webdriver (python)](https://stackoverflow.com/questions/63946115/extract-text-from-an-aria-label-selenium-webdriver-python/63946412#63946412) | This How I solved the problem that I want to wait until certain amount of post where complete load through AJAX
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# create a new Chrome session
driver = webdriver.Chrome()
# navigate to your web app.
driver.get("http://my.local.web")
# get the search button
seemore_button = driver.find_element_by_id("seemoreID")
# Count the cant of post
seemore_button.click()
# Wait for 30 sec, until AJAX search load the content
WebDriverWait(driver,30).until(EC.visibility_of_all_elements_located(By.CLASS_NAME, "post")))
# Get the list of post
listpost = driver.find_elements_by_class_name("post")
``` |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | I created `AllEc` which basically piggybacks on WebDriverWait.until logic.
This will wait until the timeout occurs or when all of the elements have been found.
```
from typing import Callable
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
class AllEc(object):
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __call__(self, driver):
try:
for fn in self.ecs:
if not fn(driver):
return False
return True
except StaleElementReferenceException:
return False
# usage example:
wait = WebDriverWait(driver, timeout)
ec1 = EC.invisibility_of_element_located(locator1)
ec2 = EC.invisibility_of_element_located(locator2)
ec3 = EC.invisibility_of_element_located(locator3)
all_ec = AllEc(ec1, ec2, ec3, description="Required elements to show page has loaded.")
found_elements = wait.until(all_ec, "Could not find all expected elements")
```
---
Alternatively I created AnyEc to look for multiple elements but returns on the first one found.
```
class AnyEc(object):
"""
Use with WebDriverWait to combine expected_conditions in an OR.
Example usage:
>>> wait = WebDriverWait(driver, 30)
>>> either = AnyEc(expectedcondition1, expectedcondition2, expectedcondition3, etc...)
>>> found = wait.until(either, "Cannot find any of the expected conditions")
"""
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __iter__(self):
return self.ecs.__iter__()
def __call__(self, driver):
for fn in self.ecs:
try:
rt = fn(driver)
if rt:
return rt
except TypeError as exc:
raise exc
except Exception as exc:
# print(exc)
pass
def __repr__(self):
return " ".join(f"{e!r}," for e in self.ecs)
def __str__(self):
return f"{self.description!s}"
either = AnyEc(ec1, ec2, ec3)
found_element = wait.until(either, "Could not find any of the expected elements")
```
---
Lastly, if it's possible to do so, you could try waiting for Ajax to be finished.
This is not useful in all cases -- e.g. Ajax is always active. In the cases where Ajax runs and finishes it can work. There are also some ajax libraries that do not set the `active` attribute, so double check that you can rely on this.
```
def is_ajax_complete(driver)
rt = driver.execute_script("return jQuery.active", *args)
return rt == 0
wait.until(lambda driver: is_ajax_complete(driver), "Ajax did not finish")
``` | This How I solved the problem that I want to wait until certain amount of post where complete load through AJAX
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# create a new Chrome session
driver = webdriver.Chrome()
# navigate to your web app.
driver.get("http://my.local.web")
# get the search button
seemore_button = driver.find_element_by_id("seemoreID")
# Count the cant of post
seemore_button.click()
# Wait for 30 sec, until AJAX search load the content
WebDriverWait(driver,30).until(EC.visibility_of_all_elements_located(By.CLASS_NAME, "post")))
# Get the list of post
listpost = driver.find_elements_by_class_name("post")
``` |
21,631,116 | I have a list, which is dynamically loaded by AJAX.
At first, while loading, it's code is like this:
```
<ul><li class="last"><a class="loading" href="#"><ins> </ins>Загрузка...</a></li></ul>
```
When the list is loaded, all of it li and a are changed. And it's always more than 1 li.
Like this:
```
<ul class="ltr">
<li id="t_b_68" class="closed" rel="simple">
<a id="t_a_68" href="javascript:void(0)">Category 1</a>
</li>
<li id="t_b_64" class="closed" rel="simple">
<a id="t_a_64" href="javascript:void(0)">Category 2</a>
</li>
...
```
I need to check if list is loaded, so I check if it has several li.
So far I tried:
1) Custom waiting condition
```
class more_than_one(object):
def __init__(self, selector):
self.selector = selector
def __call__(self, driver):
elements = driver.find_elements_by_css_selector(self.selector)
if len(elements) > 1:
return True
return False
```
...
===
```
try:
query = WebDriverWait(driver, 30).until(more_than_one('li'))
except:
print "Bad crap"
else:
# Then load ready list
```
2) Custom function based on find\_elements\_by
```
def wait_for_several_elements(driver, selector, min_amount, limit=60):
"""
This function provides awaiting of <min_amount> of elements found by <selector> with
time limit = <limit>
"""
step = 1 # in seconds; sleep for 500ms
current_wait = 0
while current_wait < limit:
try:
print "Waiting... " + str(current_wait)
query = driver.find_elements_by_css_selector(selector)
if len(query) > min_amount:
print "Found!"
return True
else:
time.sleep(step)
current_wait += step
except:
time.sleep(step)
current_wait += step
return False
```
This doesn't work, because driver (current element passed to this function) gets lost in DOM. UL isn't changed but Selenium can't find it anymore for some reason.
3) Excplicit wait. This just sucks, because some lists are loaded instantly and some take 10+ secs to load. If I use this technique I have to wait max time every occurence, which is very bad for my case.
4) Also I can't wait for child element with XPATH correctly. This one just expects ul to appear.
```
try:
print "Going to nested list..."
#time.sleep(WAIT_TIME)
query = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, './/ul')))
nested_list = child.find_element_by_css_selector('ul')
```
Please, tell me the right way to be sure, that several heir elements are loaded for specified element.
P.S. All this checks and searches should be relative to current element. | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131830/"
] | First and foremost the elements are [AJAX](https://www.w3schools.com/xml/ajax_intro.asp) elements.
Now, as per the requirement to locate all the desired elements and create a *list*, the simplest approach would be to induce [WebDriverWait](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336) for the [`visibility_of_all_elements_located()`](https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.visibility_of_all_elements_located) and you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `CSS_SELECTOR`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.ltr li[id^='t_b_'] > a[id^='t_a_'][href]")))
```
* Using `XPATH`:
```
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")))
```
* **Note** : You have to add the following imports :
```
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
```
---
Incase your usecase is to wait for certain number of elements to be loaded e.g. **10** elements, you can use you can use the *`lambda`* function as follows:
* Using `>`:
```
myLength = 9
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) > int(myLength))
```
* Using `==`:
```
myLength = 10
WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) == int(myLength))
```
>
> You can find a relevant discussion in [How to wait for number of elements to be loaded using Selenium and Python](https://stackoverflow.com/questions/64746509/how-to-wait-for-number-of-elements-to-be-loaded-using-selenium-and-python/64751105#64751105)
>
>
>
---
References
----------
You can find a couple of relevant detailed discussions in:
* [Getting specific elements in selenium](https://stackoverflow.com/questions/64068370/getting-specific-elements-in-selenium/64071682#64071682)
* [Cannot find table element from div element in selenium python](https://stackoverflow.com/questions/59868291/cannot-find-table-element-from-div-element-in-selenium-python/59868504#59868504)
* [Extract text from an aria-label selenium webdriver (python)](https://stackoverflow.com/questions/63946115/extract-text-from-an-aria-label-selenium-webdriver-python/63946412#63946412) | I created `AllEc` which basically piggybacks on WebDriverWait.until logic.
This will wait until the timeout occurs or when all of the elements have been found.
```
from typing import Callable
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
class AllEc(object):
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __call__(self, driver):
try:
for fn in self.ecs:
if not fn(driver):
return False
return True
except StaleElementReferenceException:
return False
# usage example:
wait = WebDriverWait(driver, timeout)
ec1 = EC.invisibility_of_element_located(locator1)
ec2 = EC.invisibility_of_element_located(locator2)
ec3 = EC.invisibility_of_element_located(locator3)
all_ec = AllEc(ec1, ec2, ec3, description="Required elements to show page has loaded.")
found_elements = wait.until(all_ec, "Could not find all expected elements")
```
---
Alternatively I created AnyEc to look for multiple elements but returns on the first one found.
```
class AnyEc(object):
"""
Use with WebDriverWait to combine expected_conditions in an OR.
Example usage:
>>> wait = WebDriverWait(driver, 30)
>>> either = AnyEc(expectedcondition1, expectedcondition2, expectedcondition3, etc...)
>>> found = wait.until(either, "Cannot find any of the expected conditions")
"""
def __init__(self, *args: Callable, description: str = None):
self.ecs = args
self.description = description
def __iter__(self):
return self.ecs.__iter__()
def __call__(self, driver):
for fn in self.ecs:
try:
rt = fn(driver)
if rt:
return rt
except TypeError as exc:
raise exc
except Exception as exc:
# print(exc)
pass
def __repr__(self):
return " ".join(f"{e!r}," for e in self.ecs)
def __str__(self):
return f"{self.description!s}"
either = AnyEc(ec1, ec2, ec3)
found_element = wait.until(either, "Could not find any of the expected elements")
```
---
Lastly, if it's possible to do so, you could try waiting for Ajax to be finished.
This is not useful in all cases -- e.g. Ajax is always active. In the cases where Ajax runs and finishes it can work. There are also some ajax libraries that do not set the `active` attribute, so double check that you can rely on this.
```
def is_ajax_complete(driver)
rt = driver.execute_script("return jQuery.active", *args)
return rt == 0
wait.until(lambda driver: is_ajax_complete(driver), "Ajax did not finish")
``` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | A `DataTable` exposes a `Columns` property which is a collection of column definitions. Each item (which really is a `DataColumn` type) exposes the ***maximum allowable length***. The code sample that you found only looks at the data as stored in the table. That is, it is returning the ***current maximum length used*** by data, not the maximum supported by the column.
To retrieve the maximum allowed length, simply scan through the DataColumns property of the supplied DataTable object and use the `MaxLength` property.
Here's a snippet using LINQ syntax:
```
Dim maximumLengthForColumns = From c in dataTable.Columns.Cast(Of DataColumn)
Order By c.Ordinal
Select c.MaxLength
```
The actual type of this isn't exactly a List. It's `IQueryable(Of Integer)`. Ycan use `.ToList()` to force the enumeration and conversion instead of letting it sit idle until you actually need to use the results. You could just leave as an IQueryable if you just need to enumerate over the results as the interface does inherit from IEnumerable.
I didn't need to include an Order By clause. It will probably slow down the actual execution. But, if you have so many columns in your data table that this becomes a real bottleneck, you need to be taken out back and given some other remedial instruction.
Why didn't I add a filtering clause (`Select`)? The `MaxLength` property is exposed for all columns, not just string types. And, a simple enumeration of the results should probably match up to the number of columns in your original data table. If not, feel free to add the clause to the LINQ statement.
```
Where c.DataType = GetType(String)
``` | You have to also translate those lambdas:
```
Dim maximumLengthForColumns As List(Of Integer) = Enumerable.Range(0, dataTable.Columns.Count).Select(Function(col) dataTable.AsEnumerable().Select(Function(row) row(col)).OfType(Of String)().Max(Function(val) val.Length)).ToList()
``` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | The posted self answer is iterating all columns and treating them like string columns even if they are not. That is, it is measuring and collecting the `.ToString` length of Data which is not string (which seems not to be what's desired).
The non string datacolumns could be omitted this way:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For Each dc As DataColumn In dtSample.Columns
If dc.DataType Is GetType(String) Then
MaxColLen.Add(dc.ColumnName, 0)
For Each dr As DataRow In dtSample.Rows
If dr.Field(Of String)(dc.ColumnName).Length > MaxColLen(dc.ColumnName) Then
MaxColLen(dc.ColumnName) = dr.Field(Of String)(dc.ColumnName).Length
End If
Next
End If
Next
```
Note that it uses `For Each` to reduce the clutter in code and allow the use of `DataRow` extensions such as `Field<T>()`. Personally, I think `Field(Of T)(Col)` is more readable than `DT.Rows(x)(Col).ToString` although if you **do** actually want to measure non string data, using it on non text data will surely crash.
Note that the loop skips over non string columns. To find the longest text in 715,000 rows, the original takes ~34 ms, while the above takes ~9 ms.
A linqy version of the same dictionary approach (with comments explaining the steps):
```vb
' a) look at cols as cols
' b) just the string ones
' c) get the name and inital zed value to an Anonymous type
' d) convert to a dictionary of String, Int to store the longest
Dim txtCols = dtSample.Columns.Cast(Of DataColumn).
Where(Function(c) c.DataType = GetType(String)).
Select(Function(q) New With {.Name = q.ColumnName, .Length = 0}).
ToDictionary(Of String, Int32)(Function(k) k.Name, Function(v) v.Length)
' get keys into an array to interate
' collect the max length for each
For Each colName As String In txtCols.Keys.ToArray
txtCols(colName) = dtSample.AsEnumerable().
Max(Function(m) m.Field(Of String)(colName).Length)
Next
```
This form takes ~12 ms for the same 715k rows. Extension methods are almost always slower, but the none of these differences are worth worrying about. | You have to also translate those lambdas:
```
Dim maximumLengthForColumns As List(Of Integer) = Enumerable.Range(0, dataTable.Columns.Count).Select(Function(col) dataTable.AsEnumerable().Select(Function(row) row(col)).OfType(Of String)().Max(Function(val) val.Length)).ToList()
``` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | A `DataTable` exposes a `Columns` property which is a collection of column definitions. Each item (which really is a `DataColumn` type) exposes the ***maximum allowable length***. The code sample that you found only looks at the data as stored in the table. That is, it is returning the ***current maximum length used*** by data, not the maximum supported by the column.
To retrieve the maximum allowed length, simply scan through the DataColumns property of the supplied DataTable object and use the `MaxLength` property.
Here's a snippet using LINQ syntax:
```
Dim maximumLengthForColumns = From c in dataTable.Columns.Cast(Of DataColumn)
Order By c.Ordinal
Select c.MaxLength
```
The actual type of this isn't exactly a List. It's `IQueryable(Of Integer)`. Ycan use `.ToList()` to force the enumeration and conversion instead of letting it sit idle until you actually need to use the results. You could just leave as an IQueryable if you just need to enumerate over the results as the interface does inherit from IEnumerable.
I didn't need to include an Order By clause. It will probably slow down the actual execution. But, if you have so many columns in your data table that this becomes a real bottleneck, you need to be taken out back and given some other remedial instruction.
Why didn't I add a filtering clause (`Select`)? The `MaxLength` property is exposed for all columns, not just string types. And, a simple enumeration of the results should probably match up to the number of columns in your original data table. If not, feel free to add the clause to the LINQ statement.
```
Where c.DataType = GetType(String)
``` | Non-LINQ answer...
```
Dim maximumLengthForColumns As New List(Of Integer)
For i As Integer = 0 To dtb.Columns.Count - 1
maximumLengthForColumns.Add(dtb.Columns(i).MaxLength)
Next i
```
If the size of the column is unlimited, then the `MaxLength` property returns `-1` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | A `DataTable` exposes a `Columns` property which is a collection of column definitions. Each item (which really is a `DataColumn` type) exposes the ***maximum allowable length***. The code sample that you found only looks at the data as stored in the table. That is, it is returning the ***current maximum length used*** by data, not the maximum supported by the column.
To retrieve the maximum allowed length, simply scan through the DataColumns property of the supplied DataTable object and use the `MaxLength` property.
Here's a snippet using LINQ syntax:
```
Dim maximumLengthForColumns = From c in dataTable.Columns.Cast(Of DataColumn)
Order By c.Ordinal
Select c.MaxLength
```
The actual type of this isn't exactly a List. It's `IQueryable(Of Integer)`. Ycan use `.ToList()` to force the enumeration and conversion instead of letting it sit idle until you actually need to use the results. You could just leave as an IQueryable if you just need to enumerate over the results as the interface does inherit from IEnumerable.
I didn't need to include an Order By clause. It will probably slow down the actual execution. But, if you have so many columns in your data table that this becomes a real bottleneck, you need to be taken out back and given some other remedial instruction.
Why didn't I add a filtering clause (`Select`)? The `MaxLength` property is exposed for all columns, not just string types. And, a simple enumeration of the results should probably match up to the number of columns in your original data table. If not, feel free to add the clause to the LINQ statement.
```
Where c.DataType = GetType(String)
``` | I was forced to do as @Putonix said and use a loop over the datatable for two reasons:
1) I wasn't able to use the translated `C#` code, because it gives me error "The sequence contains no elements" even if all cells have a value and also because it seems to be written only for string fields.
At the moment my knowledge isn't enough to successfully edit this code so to adapt it to my needs.
2) The 2 answers that suggest to use `MaxLength` don't give me what I need because I need the current Length of each column and not the maximum allowed length.
Thanks to all for helping
So here's the code I used:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For y As Integer = 0 To DT.Columns.Count - 1
Dim Col As String = DT.Columns(y).ColumnName
MaxColLen.Add(Col, 0)
For x As Integer = 0 To DT.Rows.Count - 1
If DT.Rows(x)(Col).ToString.Length > MaxColLen(Col) Then
MaxColLen(Col) = DT.Rows(x)(Col).ToString.Length
End If
Next
Next
``` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | A `DataTable` exposes a `Columns` property which is a collection of column definitions. Each item (which really is a `DataColumn` type) exposes the ***maximum allowable length***. The code sample that you found only looks at the data as stored in the table. That is, it is returning the ***current maximum length used*** by data, not the maximum supported by the column.
To retrieve the maximum allowed length, simply scan through the DataColumns property of the supplied DataTable object and use the `MaxLength` property.
Here's a snippet using LINQ syntax:
```
Dim maximumLengthForColumns = From c in dataTable.Columns.Cast(Of DataColumn)
Order By c.Ordinal
Select c.MaxLength
```
The actual type of this isn't exactly a List. It's `IQueryable(Of Integer)`. Ycan use `.ToList()` to force the enumeration and conversion instead of letting it sit idle until you actually need to use the results. You could just leave as an IQueryable if you just need to enumerate over the results as the interface does inherit from IEnumerable.
I didn't need to include an Order By clause. It will probably slow down the actual execution. But, if you have so many columns in your data table that this becomes a real bottleneck, you need to be taken out back and given some other remedial instruction.
Why didn't I add a filtering clause (`Select`)? The `MaxLength` property is exposed for all columns, not just string types. And, a simple enumeration of the results should probably match up to the number of columns in your original data table. If not, feel free to add the clause to the LINQ statement.
```
Where c.DataType = GetType(String)
``` | The posted self answer is iterating all columns and treating them like string columns even if they are not. That is, it is measuring and collecting the `.ToString` length of Data which is not string (which seems not to be what's desired).
The non string datacolumns could be omitted this way:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For Each dc As DataColumn In dtSample.Columns
If dc.DataType Is GetType(String) Then
MaxColLen.Add(dc.ColumnName, 0)
For Each dr As DataRow In dtSample.Rows
If dr.Field(Of String)(dc.ColumnName).Length > MaxColLen(dc.ColumnName) Then
MaxColLen(dc.ColumnName) = dr.Field(Of String)(dc.ColumnName).Length
End If
Next
End If
Next
```
Note that it uses `For Each` to reduce the clutter in code and allow the use of `DataRow` extensions such as `Field<T>()`. Personally, I think `Field(Of T)(Col)` is more readable than `DT.Rows(x)(Col).ToString` although if you **do** actually want to measure non string data, using it on non text data will surely crash.
Note that the loop skips over non string columns. To find the longest text in 715,000 rows, the original takes ~34 ms, while the above takes ~9 ms.
A linqy version of the same dictionary approach (with comments explaining the steps):
```vb
' a) look at cols as cols
' b) just the string ones
' c) get the name and inital zed value to an Anonymous type
' d) convert to a dictionary of String, Int to store the longest
Dim txtCols = dtSample.Columns.Cast(Of DataColumn).
Where(Function(c) c.DataType = GetType(String)).
Select(Function(q) New With {.Name = q.ColumnName, .Length = 0}).
ToDictionary(Of String, Int32)(Function(k) k.Name, Function(v) v.Length)
' get keys into an array to interate
' collect the max length for each
For Each colName As String In txtCols.Keys.ToArray
txtCols(colName) = dtSample.AsEnumerable().
Max(Function(m) m.Field(Of String)(colName).Length)
Next
```
This form takes ~12 ms for the same 715k rows. Extension methods are almost always slower, but the none of these differences are worth worrying about. |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | The posted self answer is iterating all columns and treating them like string columns even if they are not. That is, it is measuring and collecting the `.ToString` length of Data which is not string (which seems not to be what's desired).
The non string datacolumns could be omitted this way:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For Each dc As DataColumn In dtSample.Columns
If dc.DataType Is GetType(String) Then
MaxColLen.Add(dc.ColumnName, 0)
For Each dr As DataRow In dtSample.Rows
If dr.Field(Of String)(dc.ColumnName).Length > MaxColLen(dc.ColumnName) Then
MaxColLen(dc.ColumnName) = dr.Field(Of String)(dc.ColumnName).Length
End If
Next
End If
Next
```
Note that it uses `For Each` to reduce the clutter in code and allow the use of `DataRow` extensions such as `Field<T>()`. Personally, I think `Field(Of T)(Col)` is more readable than `DT.Rows(x)(Col).ToString` although if you **do** actually want to measure non string data, using it on non text data will surely crash.
Note that the loop skips over non string columns. To find the longest text in 715,000 rows, the original takes ~34 ms, while the above takes ~9 ms.
A linqy version of the same dictionary approach (with comments explaining the steps):
```vb
' a) look at cols as cols
' b) just the string ones
' c) get the name and inital zed value to an Anonymous type
' d) convert to a dictionary of String, Int to store the longest
Dim txtCols = dtSample.Columns.Cast(Of DataColumn).
Where(Function(c) c.DataType = GetType(String)).
Select(Function(q) New With {.Name = q.ColumnName, .Length = 0}).
ToDictionary(Of String, Int32)(Function(k) k.Name, Function(v) v.Length)
' get keys into an array to interate
' collect the max length for each
For Each colName As String In txtCols.Keys.ToArray
txtCols(colName) = dtSample.AsEnumerable().
Max(Function(m) m.Field(Of String)(colName).Length)
Next
```
This form takes ~12 ms for the same 715k rows. Extension methods are almost always slower, but the none of these differences are worth worrying about. | Non-LINQ answer...
```
Dim maximumLengthForColumns As New List(Of Integer)
For i As Integer = 0 To dtb.Columns.Count - 1
maximumLengthForColumns.Add(dtb.Columns(i).MaxLength)
Next i
```
If the size of the column is unlimited, then the `MaxLength` property returns `-1` |
38,597,697 | I need to know the maximum current lenght of each column of a DataTable (using VB.Net)
I need the maximum `.ToString.Length` for each column.
I found the below C# code [here](https://stackoverflow.com/questions/1053560/how-to-get-max-string-length-in-every-column-of-a-datatable), but I wasn't able to translate it to VB.Net
```
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
```
**EDIT**
I finally was able to translate the code in more readable vb.net but not to adapt it to my needs:
```
maximumLengthForColumns = Enumerable.Range(0, DT.Columns.Count).
Select(Function(col)
Return DT.AsEnumerable().Select(Function(row)
Return row(col)
End Function).OfType(Of String)().Max(Function(v)
Return v.Length
End Function)
End Function).ToList()
``` | 2016/07/26 | [
"https://Stackoverflow.com/questions/38597697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293613/"
] | The posted self answer is iterating all columns and treating them like string columns even if they are not. That is, it is measuring and collecting the `.ToString` length of Data which is not string (which seems not to be what's desired).
The non string datacolumns could be omitted this way:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For Each dc As DataColumn In dtSample.Columns
If dc.DataType Is GetType(String) Then
MaxColLen.Add(dc.ColumnName, 0)
For Each dr As DataRow In dtSample.Rows
If dr.Field(Of String)(dc.ColumnName).Length > MaxColLen(dc.ColumnName) Then
MaxColLen(dc.ColumnName) = dr.Field(Of String)(dc.ColumnName).Length
End If
Next
End If
Next
```
Note that it uses `For Each` to reduce the clutter in code and allow the use of `DataRow` extensions such as `Field<T>()`. Personally, I think `Field(Of T)(Col)` is more readable than `DT.Rows(x)(Col).ToString` although if you **do** actually want to measure non string data, using it on non text data will surely crash.
Note that the loop skips over non string columns. To find the longest text in 715,000 rows, the original takes ~34 ms, while the above takes ~9 ms.
A linqy version of the same dictionary approach (with comments explaining the steps):
```vb
' a) look at cols as cols
' b) just the string ones
' c) get the name and inital zed value to an Anonymous type
' d) convert to a dictionary of String, Int to store the longest
Dim txtCols = dtSample.Columns.Cast(Of DataColumn).
Where(Function(c) c.DataType = GetType(String)).
Select(Function(q) New With {.Name = q.ColumnName, .Length = 0}).
ToDictionary(Of String, Int32)(Function(k) k.Name, Function(v) v.Length)
' get keys into an array to interate
' collect the max length for each
For Each colName As String In txtCols.Keys.ToArray
txtCols(colName) = dtSample.AsEnumerable().
Max(Function(m) m.Field(Of String)(colName).Length)
Next
```
This form takes ~12 ms for the same 715k rows. Extension methods are almost always slower, but the none of these differences are worth worrying about. | I was forced to do as @Putonix said and use a loop over the datatable for two reasons:
1) I wasn't able to use the translated `C#` code, because it gives me error "The sequence contains no elements" even if all cells have a value and also because it seems to be written only for string fields.
At the moment my knowledge isn't enough to successfully edit this code so to adapt it to my needs.
2) The 2 answers that suggest to use `MaxLength` don't give me what I need because I need the current Length of each column and not the maximum allowed length.
Thanks to all for helping
So here's the code I used:
```vb
Dim MaxColLen As New Dictionary(Of String, Integer)
For y As Integer = 0 To DT.Columns.Count - 1
Dim Col As String = DT.Columns(y).ColumnName
MaxColLen.Add(Col, 0)
For x As Integer = 0 To DT.Rows.Count - 1
If DT.Rows(x)(Col).ToString.Length > MaxColLen(Col) Then
MaxColLen(Col) = DT.Rows(x)(Col).ToString.Length
End If
Next
Next
``` |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | When seeing something like
```
#define DSF_FOO 0x800
#define DSF_BAR 2048
```
not many people are able to quickly see that only one bit is set, and which it is.
```
#define DSF_FOO (1<<11)
```
however makes this very clear. | Regardless of whether you prefer `(1 << n)` or not, everyone should be aware of what hexadecimal numbers signify. Whenever you encounter hex in source code it always means that som bit- or byte manipulations are taking place. You don't use hex notation for any other purpose. Therefore it is wise to write masks, numeric bit manipulation literals etc as hex. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | When seeing something like
```
#define DSF_FOO 0x800
#define DSF_BAR 2048
```
not many people are able to quickly see that only one bit is set, and which it is.
```
#define DSF_FOO (1<<11)
```
however makes this very clear. | Some times the position of the bits represent some bit operations like in your case:
```
#define DSF_OVER (1<<0) is 1
#define DSF_DISPLAY (1<<1) is 2
#define DSF_CALLFLOW (1<<2) is 4 (This is not 3)
```
If you were to add a new item later, you will do it as
```
#define DSF_OVER 1
#define DSF_DISPLAY 2
#define DSF_CALLFLOW 4
#define DSF_CALLNEW 5.
```
You cant have a value 5 here since it is two bits enabled (101 in binary). To avoid such potential errors it is always safe to use macros using `>>`. It can't produce a value of 5 (101) by error in when the next bit should be 1000 in binary.
It is all about programming convenience to produce error free code. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | These are bit values, e.g. 1, 2, 4. 8.
```
Bit 0 = (1 << 0) = 1
Bit 1 = (1 << 1) = 2
Bit 2 = (1 << 2) = 4
Bit 3 = (1 << 3) = 8
...etc...
```
It's a more convenient and robust way of defining them than using explicit values, especially as the bit indices get larger (e.g. `(1<<15)` is much easier to understand and more intuitive than `32768` or `0x8000`, in that it obviously means "bit 15" rather than some possibly arbitrary number). | Some times the position of the bits represent some bit operations like in your case:
```
#define DSF_OVER (1<<0) is 1
#define DSF_DISPLAY (1<<1) is 2
#define DSF_CALLFLOW (1<<2) is 4 (This is not 3)
```
If you were to add a new item later, you will do it as
```
#define DSF_OVER 1
#define DSF_DISPLAY 2
#define DSF_CALLFLOW 4
#define DSF_CALLNEW 5.
```
You cant have a value 5 here since it is two bits enabled (101 in binary). To avoid such potential errors it is always safe to use macros using `>>`. It can't produce a value of 5 (101) by error in when the next bit should be 1000 in binary.
It is all about programming convenience to produce error free code. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | Some times the position of the bits represent some bit operations like in your case:
```
#define DSF_OVER (1<<0) is 1
#define DSF_DISPLAY (1<<1) is 2
#define DSF_CALLFLOW (1<<2) is 4 (This is not 3)
```
If you were to add a new item later, you will do it as
```
#define DSF_OVER 1
#define DSF_DISPLAY 2
#define DSF_CALLFLOW 4
#define DSF_CALLNEW 5.
```
You cant have a value 5 here since it is two bits enabled (101 in binary). To avoid such potential errors it is always safe to use macros using `>>`. It can't produce a value of 5 (101) by error in when the next bit should be 1000 in binary.
It is all about programming convenience to produce error free code. | Regardless of whether you prefer `(1 << n)` or not, everyone should be aware of what hexadecimal numbers signify. Whenever you encounter hex in source code it always means that som bit- or byte manipulations are taking place. You don't use hex notation for any other purpose. Therefore it is wise to write masks, numeric bit manipulation literals etc as hex. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | The only potential advantage is that it's easier to see that the code correctly defines each constant with one distinct bit set.
Most people will see that at a glance anyway if you just write 1, 2, 4 instead of `1<<0`, `1<<1`, `1<<2`, so perhaps it's difficult to see that advantage in this example. Once you get to `1<<15`, some people would miss a typo like 32748. | It's for clarity really - it shows that the different definitions are bit masks that will typically be used together to filter values from an input. I don't know if you already know what a bit mask is - here's a link: <http://www.vipan.com/htdocs/bitwisehelp.html> |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | Using `(1<<x)` in a define makes it clear that the value is a single bit and not a number.
For the compiler it makes no difference because `(1<<2)` is computed at compile time and not at runtime. Showing clearly that they are single-bit values is instead useful for whoever reads the code because for example they could be multiple values that can be combined or that a single variable can be used to store multiple flags:
```
// Multiple options are combined with bitwise-or
show_message(DSF_CAPTION|DSF_ALERT, "Hey...");
...
// Checking is made using bitwise-and, not equality
if (status & DSF_RUNNING)
...
```
Also requiring specific bits is sometimes needed when dealing with hardware (e.g. on a certain I/O port may be you need to specify the fifth bit because that's how the hardware is wired, and `(1<<4)` is more readable than `16` for that). | Some times the position of the bits represent some bit operations like in your case:
```
#define DSF_OVER (1<<0) is 1
#define DSF_DISPLAY (1<<1) is 2
#define DSF_CALLFLOW (1<<2) is 4 (This is not 3)
```
If you were to add a new item later, you will do it as
```
#define DSF_OVER 1
#define DSF_DISPLAY 2
#define DSF_CALLFLOW 4
#define DSF_CALLNEW 5.
```
You cant have a value 5 here since it is two bits enabled (101 in binary). To avoid such potential errors it is always safe to use macros using `>>`. It can't produce a value of 5 (101) by error in when the next bit should be 1000 in binary.
It is all about programming convenience to produce error free code. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | Using `(1<<x)` in a define makes it clear that the value is a single bit and not a number.
For the compiler it makes no difference because `(1<<2)` is computed at compile time and not at runtime. Showing clearly that they are single-bit values is instead useful for whoever reads the code because for example they could be multiple values that can be combined or that a single variable can be used to store multiple flags:
```
// Multiple options are combined with bitwise-or
show_message(DSF_CAPTION|DSF_ALERT, "Hey...");
...
// Checking is made using bitwise-and, not equality
if (status & DSF_RUNNING)
...
```
Also requiring specific bits is sometimes needed when dealing with hardware (e.g. on a certain I/O port may be you need to specify the fifth bit because that's how the hardware is wired, and `(1<<4)` is more readable than `16` for that). | Regardless of whether you prefer `(1 << n)` or not, everyone should be aware of what hexadecimal numbers signify. Whenever you encounter hex in source code it always means that som bit- or byte manipulations are taking place. You don't use hex notation for any other purpose. Therefore it is wise to write masks, numeric bit manipulation literals etc as hex. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | The only potential advantage is that it's easier to see that the code correctly defines each constant with one distinct bit set.
Most people will see that at a glance anyway if you just write 1, 2, 4 instead of `1<<0`, `1<<1`, `1<<2`, so perhaps it's difficult to see that advantage in this example. Once you get to `1<<15`, some people would miss a typo like 32748. | Regardless of whether you prefer `(1 << n)` or not, everyone should be aware of what hexadecimal numbers signify. Whenever you encounter hex in source code it always means that som bit- or byte manipulations are taking place. You don't use hex notation for any other purpose. Therefore it is wise to write masks, numeric bit manipulation literals etc as hex. |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | These are bit values, e.g. 1, 2, 4. 8.
```
Bit 0 = (1 << 0) = 1
Bit 1 = (1 << 1) = 2
Bit 2 = (1 << 2) = 4
Bit 3 = (1 << 3) = 8
...etc...
```
It's a more convenient and robust way of defining them than using explicit values, especially as the bit indices get larger (e.g. `(1<<15)` is much easier to understand and more intuitive than `32768` or `0x8000`, in that it obviously means "bit 15" rather than some possibly arbitrary number). | It's for clarity really - it shows that the different definitions are bit masks that will typically be used together to filter values from an input. I don't know if you already know what a bit mask is - here's a link: <http://www.vipan.com/htdocs/bitwisehelp.html> |
7,738,005 | I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
```
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
```
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
```
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
``` | 2011/10/12 | [
"https://Stackoverflow.com/questions/7738005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496934/"
] | It's for clarity really - it shows that the different definitions are bit masks that will typically be used together to filter values from an input. I don't know if you already know what a bit mask is - here's a link: <http://www.vipan.com/htdocs/bitwisehelp.html> | Regardless of whether you prefer `(1 << n)` or not, everyone should be aware of what hexadecimal numbers signify. Whenever you encounter hex in source code it always means that som bit- or byte manipulations are taking place. You don't use hex notation for any other purpose. Therefore it is wise to write masks, numeric bit manipulation literals etc as hex. |
73,554,263 | I have some python scripts that I look to run daily form a Windows PC.
**My current workflow is:**
1. The desktop PC stays all every day except for a weekly restart over the weekend
2. After the restart I open VS Code and run a little bash script `./start.sh` that kicks off the tasks.
The above works reasonably fine, but it is also fairly painful. I need to re-run `start.sh` if I ever close VS Code (eg. for an update). Also the processes use some local python libraries so I need to stop them if I'm going to update them.
With regards to how to do this properly, 4 tools came to mind:
1. Windows Scheduler
2. Airflow
3. Prefect (<https://www.prefect.io/>)
4. Rocketry (<https://rocketry.readthedocs.io/en/stable/>)
However, I can't quite get my head around the fundamental issue that Prefect/Airflow/Rocketry run on my PC then there is nothing that will restart them after the PC reboots. I'm also not sure they will give me the isolation I'd prefer on these tools.
Docker came to mind, I could put each task into a docker image and run them via some form of docker swarm or something like that. But not sure if I'm re-inventing the wheel.
I'm 100% sure I'm not the first person in this situation. Could anyone point me to a guide on how this could be done well?
**Note:**
* I am not considering running the python scripts in the cloud. They interact with local tools that are only licenced for my PC. | 2022/08/31 | [
"https://Stackoverflow.com/questions/73554263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194313/"
] | You can definitely use Prefect for that - it's very lightweight and seems to be matching what you're looking for. You install it with `pip install prefect`, start Orion API server: `prefect orion start` and once you create a Deployment, and start an agent `prefect agent start -q default` you can even [configure schedule from the UI](https://docs.prefect.io/concepts/schedules/)
For more information about Deployments, check [our FAQ section](https://discourse.prefect.io/t/prefect-deployments-faq/1467). | It sounds Rocketry could also be suitable. Rocketry [can shut down itself using a task](https://rocketry.readthedocs.io/en/stable/tutorial/advanced.html#metatasks). You could do a task that:
1. Runs on the main thread and process (blocking starting new tasks)
2. Waits or terminates all the currently running tasks (use the session)
3. Calls `session.shut_down()` which sets a flag to the scheduler.
There is also a app configuration `shut_cond` which is simply a condition. If this condition is True, the scheduler exits so alternatively you can use this.
Then after the line `app.run()` you simply have a line that runs `shutdown -r` (restart) command on shell using a subprocess library, for example. Then you need something that starts Rocketry again when the restart is completed. For this, perhaps this could be an answer: <https://superuser.com/a/954957>, or use Windows scheduler to have a simple startup task that starts Rocketry.
Especially if you had Linux machines (Raspberry Pis for example), you could integrate Rocketry with FastAPI and make a small cluster in which Rocketry apps communicate with each other, just put script with Rocketry as a startup service. One machine could be a backup that calls another machine's API which runs Linux restart command. Then the backup executes tasks until the primary machine answers to requests again (is up and running).
But as the author of the library, I'm possibly biased toward my own projects. But Rocketry very capable on complex scheduling problems, that's the purpose of the project. |
73,554,263 | I have some python scripts that I look to run daily form a Windows PC.
**My current workflow is:**
1. The desktop PC stays all every day except for a weekly restart over the weekend
2. After the restart I open VS Code and run a little bash script `./start.sh` that kicks off the tasks.
The above works reasonably fine, but it is also fairly painful. I need to re-run `start.sh` if I ever close VS Code (eg. for an update). Also the processes use some local python libraries so I need to stop them if I'm going to update them.
With regards to how to do this properly, 4 tools came to mind:
1. Windows Scheduler
2. Airflow
3. Prefect (<https://www.prefect.io/>)
4. Rocketry (<https://rocketry.readthedocs.io/en/stable/>)
However, I can't quite get my head around the fundamental issue that Prefect/Airflow/Rocketry run on my PC then there is nothing that will restart them after the PC reboots. I'm also not sure they will give me the isolation I'd prefer on these tools.
Docker came to mind, I could put each task into a docker image and run them via some form of docker swarm or something like that. But not sure if I'm re-inventing the wheel.
I'm 100% sure I'm not the first person in this situation. Could anyone point me to a guide on how this could be done well?
**Note:**
* I am not considering running the python scripts in the cloud. They interact with local tools that are only licenced for my PC. | 2022/08/31 | [
"https://Stackoverflow.com/questions/73554263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194313/"
] | You can definitely use Prefect for that - it's very lightweight and seems to be matching what you're looking for. You install it with `pip install prefect`, start Orion API server: `prefect orion start` and once you create a Deployment, and start an agent `prefect agent start -q default` you can even [configure schedule from the UI](https://docs.prefect.io/concepts/schedules/)
For more information about Deployments, check [our FAQ section](https://discourse.prefect.io/t/prefect-deployments-faq/1467). | You can use **schtasks** for windows to schedule the tasks like running bash script or python script and it's pretty reliable too. |
73,554,263 | I have some python scripts that I look to run daily form a Windows PC.
**My current workflow is:**
1. The desktop PC stays all every day except for a weekly restart over the weekend
2. After the restart I open VS Code and run a little bash script `./start.sh` that kicks off the tasks.
The above works reasonably fine, but it is also fairly painful. I need to re-run `start.sh` if I ever close VS Code (eg. for an update). Also the processes use some local python libraries so I need to stop them if I'm going to update them.
With regards to how to do this properly, 4 tools came to mind:
1. Windows Scheduler
2. Airflow
3. Prefect (<https://www.prefect.io/>)
4. Rocketry (<https://rocketry.readthedocs.io/en/stable/>)
However, I can't quite get my head around the fundamental issue that Prefect/Airflow/Rocketry run on my PC then there is nothing that will restart them after the PC reboots. I'm also not sure they will give me the isolation I'd prefer on these tools.
Docker came to mind, I could put each task into a docker image and run them via some form of docker swarm or something like that. But not sure if I'm re-inventing the wheel.
I'm 100% sure I'm not the first person in this situation. Could anyone point me to a guide on how this could be done well?
**Note:**
* I am not considering running the python scripts in the cloud. They interact with local tools that are only licenced for my PC. | 2022/08/31 | [
"https://Stackoverflow.com/questions/73554263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194313/"
] | It sounds Rocketry could also be suitable. Rocketry [can shut down itself using a task](https://rocketry.readthedocs.io/en/stable/tutorial/advanced.html#metatasks). You could do a task that:
1. Runs on the main thread and process (blocking starting new tasks)
2. Waits or terminates all the currently running tasks (use the session)
3. Calls `session.shut_down()` which sets a flag to the scheduler.
There is also a app configuration `shut_cond` which is simply a condition. If this condition is True, the scheduler exits so alternatively you can use this.
Then after the line `app.run()` you simply have a line that runs `shutdown -r` (restart) command on shell using a subprocess library, for example. Then you need something that starts Rocketry again when the restart is completed. For this, perhaps this could be an answer: <https://superuser.com/a/954957>, or use Windows scheduler to have a simple startup task that starts Rocketry.
Especially if you had Linux machines (Raspberry Pis for example), you could integrate Rocketry with FastAPI and make a small cluster in which Rocketry apps communicate with each other, just put script with Rocketry as a startup service. One machine could be a backup that calls another machine's API which runs Linux restart command. Then the backup executes tasks until the primary machine answers to requests again (is up and running).
But as the author of the library, I'm possibly biased toward my own projects. But Rocketry very capable on complex scheduling problems, that's the purpose of the project. | You can use **schtasks** for windows to schedule the tasks like running bash script or python script and it's pretty reliable too. |
53,149,153 | I am a new beginner in C
This is my code:
```
#include <stdio.h>
int main(void) {
int choice;
int clientNum;
printf("\nAssume that in the main memory contain 16 frameSize\n");
printf("Each frame has 256 bits\n");
printf("How many clients: ");
scanf("%d", &clientNum);
printf("\nPlease choose the Scheduling Algorithm 1. FCFS 2.Round Robin: ");
scanf("%d", &choice);
while(choice !=1 || choice !=2){
printf("\nINVALID!!! The Server only has either FCFS or Round Robind Algorithm");
printf("\nPlease choose the Scheduling Algorithm again 1. FCFS 2.Round Robin: ");
scanf("%d", &choice);
}
if (choice==1){
printf("FCFS");
}
if (choice==2){
printf("Round Robind");
}
return 0;
}
```
I want to compare the value of choice with number 1 and 2. However, If statements did not work correctly. it did not compare choice with any value
Is there any error in syntax or logic?
The output:
```
gcc version 4.6.3
Assume that in the main memory contain 16 frameSize
Each frame has 256 bits
How many clients: 3
Please choose the Scheduling Algorithm 1. FCFS 2.Round Robin: 1
INVALID!!! The Server only has either FCFS or Round Robind Algorithm
Please choose the Scheduling Algorithm again 1. FCFS 2.Round Robin: 2
INVALID!!! The Server only has either FCFS or Round Robind Algorithm
Please choose the Scheduling Algorithm again 1. FCFS 2.Round Robin: 1
INVALID!!! The Server only has either FCFS or Round Robind Algorithm
Please choose the Scheduling Algorithm again 1. FCFS 2.Round Robin:
``` | 2018/11/05 | [
"https://Stackoverflow.com/questions/53149153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10526071/"
] | ```
while ((choice !=1) && (choice !=2))
{
code.....
}
```
after the loop you will end up with 2 choices either 1 or 2 so :
```
if (choice == 1)
{
printf("FCFS");
}
else
{
printf("Round Robind");
``` | This should work:
```
#include <stdio.h>
int main(void)
{
int choice;
int clientNum;
printf("\nAssume that in the main memory contain 16 frameSize\n");
printf("Each frame has 256 bits\n");
printf("How many clients: ");
scanf("%d", &clientNum);
printf("\nPlease choose the Scheduling Algorithm 1. FCFS 2.Round Robin: ");
scanf("%d", &choice);
while (choice !=1 && choice !=2) //change || into &&
{
printf("\nINVALID!!! The Server only has either FCFS or Round Robind Algorithm");
printf("\nPlease choose the Scheduling Algorithm again 1. FCFS 2.Round Robin: ");
scanf("%d", &choice);
}
if (choice == 1)
{
printf("FCFS");
}
if (choice == 2)
{
printf("Round Robind");
}
return 0;
}
``` |
24,916,347 | I am new in Neo4j and Cypher and writing on my BA-Thesis in which I compare a RDBMS against Neo4j Graph Database in case of social networks. I´ve defined some queries in SQL and Cypher for a Performance Test over JDBC and REST API in JMETER. However, I have a problem declaring the Cypher query to get the Nodes which are the mutual friends of friends for a certain Node.
My first approach was like so:
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast)-[:abonniert]->(fof:Enthusiast)<-[:abonniert]-(f) RETURN o
``` | 2014/07/23 | [
"https://Stackoverflow.com/questions/24916347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869668/"
] | I guess you're pretty close with your Cypher statement. I assume that "mutual friend on 2nd degree" means that I'm mutual friend with someone the target is mutual friend as well?
If so (shortening labels and relationship types for readbility):
```
MATCH
(me:En {Id: 488})-[:abonniert]->(f:En)-[:abonniert]->(fof:En),
(fof)-[:abonniert]->(f)-[:abonniert]->me
RETURN fof
``` | it would be nice if you can create an example scenario at <http://console.neo4j.org/> .
i would also omit the relationships direction.
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast),
(f)-[:abonniert]-(x:Enthusiast)-[:aboniert]-(y:Enthusiast)
WHERE f--y AND Id(y) <> 488
RETURN f, y, count(x) as NrMutFr
```
**edit**
try this console query, works for the scenario: <http://console.neo4j.org/r/tws07k>
my above query would in that case be
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast),
(f)-[:abonniert]->(x:Enthusiast)<-[:aboniert]-(y:Enthusiast)
WHERE me--y
RETURN f, y, count(x) as NrMutFr
```
the difference between your posted question query is that you must finish the last node with a new substitute `y` and not `f`. than also, if necessary, again match that `y` with starting `me` node |
24,916,347 | I am new in Neo4j and Cypher and writing on my BA-Thesis in which I compare a RDBMS against Neo4j Graph Database in case of social networks. I´ve defined some queries in SQL and Cypher for a Performance Test over JDBC and REST API in JMETER. However, I have a problem declaring the Cypher query to get the Nodes which are the mutual friends of friends for a certain Node.
My first approach was like so:
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast)-[:abonniert]->(fof:Enthusiast)<-[:abonniert]-(f) RETURN o
``` | 2014/07/23 | [
"https://Stackoverflow.com/questions/24916347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869668/"
] | I guess you're pretty close with your Cypher statement. I assume that "mutual friend on 2nd degree" means that I'm mutual friend with someone the target is mutual friend as well?
If so (shortening labels and relationship types for readbility):
```
MATCH
(me:En {Id: 488})-[:abonniert]->(f:En)-[:abonniert]->(fof:En),
(fof)-[:abonniert]->(f)-[:abonniert]->me
RETURN fof
``` | Once you've matched your friends you should be able to express the rest of the query as a path predicate: match "my friends", filter out everyone except "those of my friends who have some friend in common", which amounts to the same as "those of my friends who have a friend-of-friend who is a friend of mine.
```
MATCH (me:Enthusiast { Id: 488 })-[:abonniert]->(f)
WHERE f-[:abonniert]-()-[:abonniert]-()<-[:abonniert]-me
RETURN f
```
Here's a console: <http://console.neo4j.org/r/87n0j9>. If I have misunderstood your question you can make changes in that console, click "share" and post back the link here with an explanation of what result you expect to get back.
**Edit**
If you want to get the nodes that are two or more of your friends are related to in common, you can do
```
MATCH (me:Enthusiast { Id: 488 })-[:subscribed]->(f)-[:subscribed]->(common)
WITH common, count(common) AS cnt
WHERE cnt > 1
RETURN common
```
A node that is a common neighbour of your neighbours can be described as a node you can reach on at least two paths. You can therefore match your neighbour-of-neighbours, count the times each "non" is matched, and if it is matched more than once then it is a "non" that is common to at least two of your neighbours. If you want you can return that count and order the result by it as a type of scoring (since this seems to be for recommendation purposes).
```
MATCH (me:Enthusiast { Id: 488 })-[:subscribed]->(f)-[:subscribed]->(common)
WITH common, count(common) AS score
WHERE score > 1
RETURN common, score
ORDER BY score DESC
``` |
24,916,347 | I am new in Neo4j and Cypher and writing on my BA-Thesis in which I compare a RDBMS against Neo4j Graph Database in case of social networks. I´ve defined some queries in SQL and Cypher for a Performance Test over JDBC and REST API in JMETER. However, I have a problem declaring the Cypher query to get the Nodes which are the mutual friends of friends for a certain Node.
My first approach was like so:
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast)-[:abonniert]->(fof:Enthusiast)<-[:abonniert]-(f) RETURN o
``` | 2014/07/23 | [
"https://Stackoverflow.com/questions/24916347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869668/"
] | it would be nice if you can create an example scenario at <http://console.neo4j.org/> .
i would also omit the relationships direction.
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast),
(f)-[:abonniert]-(x:Enthusiast)-[:aboniert]-(y:Enthusiast)
WHERE f--y AND Id(y) <> 488
RETURN f, y, count(x) as NrMutFr
```
**edit**
try this console query, works for the scenario: <http://console.neo4j.org/r/tws07k>
my above query would in that case be
```
MATCH (me:Enthusiast {Id: 488})-[:abonniert]->(f:Enthusiast),
(f)-[:abonniert]->(x:Enthusiast)<-[:aboniert]-(y:Enthusiast)
WHERE me--y
RETURN f, y, count(x) as NrMutFr
```
the difference between your posted question query is that you must finish the last node with a new substitute `y` and not `f`. than also, if necessary, again match that `y` with starting `me` node | Once you've matched your friends you should be able to express the rest of the query as a path predicate: match "my friends", filter out everyone except "those of my friends who have some friend in common", which amounts to the same as "those of my friends who have a friend-of-friend who is a friend of mine.
```
MATCH (me:Enthusiast { Id: 488 })-[:abonniert]->(f)
WHERE f-[:abonniert]-()-[:abonniert]-()<-[:abonniert]-me
RETURN f
```
Here's a console: <http://console.neo4j.org/r/87n0j9>. If I have misunderstood your question you can make changes in that console, click "share" and post back the link here with an explanation of what result you expect to get back.
**Edit**
If you want to get the nodes that are two or more of your friends are related to in common, you can do
```
MATCH (me:Enthusiast { Id: 488 })-[:subscribed]->(f)-[:subscribed]->(common)
WITH common, count(common) AS cnt
WHERE cnt > 1
RETURN common
```
A node that is a common neighbour of your neighbours can be described as a node you can reach on at least two paths. You can therefore match your neighbour-of-neighbours, count the times each "non" is matched, and if it is matched more than once then it is a "non" that is common to at least two of your neighbours. If you want you can return that count and order the result by it as a type of scoring (since this seems to be for recommendation purposes).
```
MATCH (me:Enthusiast { Id: 488 })-[:subscribed]->(f)-[:subscribed]->(common)
WITH common, count(common) AS score
WHERE score > 1
RETURN common, score
ORDER BY score DESC
``` |
44,428,962 | I am loading a page inside the webview
```
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");
```
then inside the webview I have several function to click event below
```
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("concierge@xxxx.com.sg")) {
final Intent eIntent = new Intent(
android.content.Intent.ACTION_SEND);
eIntent.setType("plain/text");
eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[]{"xxxxxx"});
eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"");
eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"Text to be send");
startActivity(Intent.createChooser(eIntent,
"Send mail..."));
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
} else if (url.contains(".pdf")) {
//Intent intent = new Intent(Intent.ACTION_VIEW);
//intent.setDataAndType(Uri.parse(url), "application/pdf");
//try{
//view.getContext().startActivity(intent);
//} catch (ActivityNotFoundException e) {
//user does not have a pdf viewer installed
//}
// view.loadUrl("https://docs.google.com/viewer?url=" + url);
view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
} else {
view.loadUrl(url);
}
return true;
}
```
in this webview there is a click event for PDF. So if I click this the PDF not loading | 2017/06/08 | [
"https://Stackoverflow.com/questions/44428962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990291/"
] | ```
view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
```
This method call working for me, when I called to load inside the webview. So this webview layout height should be match\_parent.
Link click open the browser then simply pass the URL like below code.
```
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
```
This is solved my problem. | Please check the below example code for your requirement
```
private void init()
{
WebView webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
MyWebViewClient webViewClient = new MyWebViewClient(this, webview);
webViewClient.loadUrl(YOUR_URL);
}
private class MyWebViewClient extends WebViewClient
{
private static final String TAG = "MyWebViewClient";
private static final String PDF_EXTENSION = ".pdf";
private static final String PDF_VIEWER_URL = "https://drive.google.com/viewerng/viewer?embedded=true&url=";
private Context mContext;
private WebView mWebView;
private ProgressDialog mProgressDialog;
private boolean isLoadingPdfUrl;
public MyWebViewClient(Context context, WebView webView)
{
mContext = context;
mWebView = webView;
mWebView.setWebViewClient(this);
}
public void loadUrl(String url)
{
mWebView.stopLoading();
if (!TextUtils.isEmpty(url))
{
isLoadingPdfUrl = isPdfUrl(url);
if (isLoadingPdfUrl)
{
mWebView.clearHistory();
}
showProgressDialog();
}
mWebView.loadUrl(url);
}
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl)
{
handleError(errorCode, description.toString(), failingUrl);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
final Uri uri = request.getUrl();
return shouldOverrideUrlLoading(webView, uri.toString());
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public void onReceivedError(final WebView webView, final WebResourceRequest request, final WebResourceError error)
{
final Uri uri = request.getUrl();
handleError(error.getErrorCode(), error.getDescription().toString(), uri.toString());
}
@Override
public void onPageFinished(final WebView view, final String url)
{
Log.i(TAG, "Finished loading. URL : " + url);
dismissProgressDialog();
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
if (url.contains("concierge@xxxx.com.sg"))
{
Intent eIntent = new Intent(android.content.Intent.ACTION_SEND);
eIntent.setType("plain/text");
eIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"xxxxxx"});
eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
eIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text to be send");
startActivity(Intent.createChooser(eIntent, "Send mail..."));
return true;
}
else if (url.startsWith("tel:"))
{
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
else if (!isLoadingPdfUrl && isPdfUrl(url))
{
mWebView.stopLoading();
final String pdfUrl = PDF_VIEWER_URL + url;
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
loadUrl(pdfUrl);
}
}, 300);
return true;
}
return false; // Load url in the webView itself
}
private void handleError(final int errorCode, final String description, final String failingUrl)
{
Log.e(TAG, "Error : " + errorCode + ", " + description + " URL : " + failingUrl);
}
private void showProgressDialog()
{
dismissProgressDialog();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
private void dismissProgressDialog()
{
if (mProgressDialog != null && mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
private boolean isPdfUrl(String url)
{
if (!TextUtils.isEmpty(url))
{
url = url.trim();
int lastIndex = url.toLowerCase().lastIndexOf(PDF_EXTENSION);
if (lastIndex != -1)
{
return url.substring(lastIndex).equalsIgnoreCase(PDF_EXTENSION);
}
}
return false;
}
}
```
Checkout the example code for handling redirect urls and open PDF without download, in webview. <https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500> |
44,428,962 | I am loading a page inside the webview
```
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");
```
then inside the webview I have several function to click event below
```
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("concierge@xxxx.com.sg")) {
final Intent eIntent = new Intent(
android.content.Intent.ACTION_SEND);
eIntent.setType("plain/text");
eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[]{"xxxxxx"});
eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"");
eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"Text to be send");
startActivity(Intent.createChooser(eIntent,
"Send mail..."));
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
} else if (url.contains(".pdf")) {
//Intent intent = new Intent(Intent.ACTION_VIEW);
//intent.setDataAndType(Uri.parse(url), "application/pdf");
//try{
//view.getContext().startActivity(intent);
//} catch (ActivityNotFoundException e) {
//user does not have a pdf viewer installed
//}
// view.loadUrl("https://docs.google.com/viewer?url=" + url);
view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
} else {
view.loadUrl(url);
}
return true;
}
```
in this webview there is a click event for PDF. So if I click this the PDF not loading | 2017/06/08 | [
"https://Stackoverflow.com/questions/44428962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990291/"
] | ```
view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
```
This method call working for me, when I called to load inside the webview. So this webview layout height should be match\_parent.
Link click open the browser then simply pass the URL like below code.
```
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
```
This is solved my problem. | That the use of these methods need to log in to Google.
Other way use [pdf.js](https://github.com/mozilla/pdf.js/)
You must save pdf file into sdcard and load in webview.
Add the pdfjs files to your Assets directory
```
else if (url.contains(".pdf"))
{
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");
view.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");
}
```
[Full sample project](https://github.com/loosemoose/androidpdf) |
3,089,127 | I'm new to Java programming.
I am curious about speed of execution and also speed of creation and distruction of objects.
I've got several methods like the following:
```
private static void getAbsoluteThrottleB() {
int A = Integer.parseInt(Status.LineToken.nextToken());
Status.AbsoluteThrottleB=A*100/255;
Log.level1("Absolute Throttle Position B: " + Status.AbsoluteThrottleB);
}
```
and
```
private static void getWBO2S8Volts() {
int A = Integer.parseInt(Status.LineToken.nextToken());
int B = Integer.parseInt(Status.LineToken.nextToken());
int C = Integer.parseInt(Status.LineToken.nextToken());
int D = Integer.parseInt(Status.LineToken.nextToken());
Status.WBO2S8Volts=((A*256)+B)/32768;
Status.WBO2S8VoltsEquivalenceRatio=((C*256)+D)/256 - 128;
Log.level1("WideBand Sensor 8 Voltage: " + Double.toString(Status.WBO2S8Volts));
Log.level1("WideBand Sensor 8 Volt EQR:" + Double.toString(Status.WBO2S8VoltsEquivalenceRatio));
```
Would it be wise to create a separate method to process the data since it is repetative? Or would it just be faster to execute it as a single method? I have several of these which would need to be rewritten and I am wondering if it would actually improve speed of execution or if it is just as good, or if there is a number of instructions where it becomes a good idea to create a new method.
Basically, what is faster or when does it become faster to use a single method to process objects versus using another method to process several like objects?
It seems like at runtime, pulling a new variable, then performing a math operation on it is quicker then creating a new method and then pulling a varible then performing a math operation on it. My question is really where the speed is at..
These methods are all called only to read data and set a Status.Variable. There are nearly 200 methods in my class which generate data. | 2010/06/21 | [
"https://Stackoverflow.com/questions/3089127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/368817/"
] | The speed difference of invoking a piece of code inside a method or outside of it is negligible. Specially compared with using the right algorithm for the task.
I would recommend you to use the method anyway, not for performance but for maintainability. If you need to change one line of code which turn out to introduce a bug or something and you have this code segment copy/pasted in 50 different places, it would be much harder to change ( and spot ) than having it in one single place.
So, don't worry about the performance penalty introduced by using methods because, it is practically nothing( even better, the VM may inline some of the calls ) | >
> I am curious about speed of execution and also speed of creation and destruction of objects.
>
>
>
Creation of objects in Java is fast enough that you shouldn't need to worry about it, except in extreme and unusual situations.
Destruction of objects in a modern Java implementation has zero cost ... unless you use finalizers. And there are very few situations that you should even *think* of using a finalizer.
>
> Basically, what is faster or when does it become faster to use a single method to process objects versus using another method to process several like objects?
>
>
>
The difference is negligible relative to everything else that is going on.
---
As @S.Lott says: "Please don't micro-optimize". Focus on writing code that is simple, clear, precise and correct, and that uses the most appropriate algorithms. Only "micro" optimize when you have clear evidence of a critical bottleneck. |
3,089,127 | I'm new to Java programming.
I am curious about speed of execution and also speed of creation and distruction of objects.
I've got several methods like the following:
```
private static void getAbsoluteThrottleB() {
int A = Integer.parseInt(Status.LineToken.nextToken());
Status.AbsoluteThrottleB=A*100/255;
Log.level1("Absolute Throttle Position B: " + Status.AbsoluteThrottleB);
}
```
and
```
private static void getWBO2S8Volts() {
int A = Integer.parseInt(Status.LineToken.nextToken());
int B = Integer.parseInt(Status.LineToken.nextToken());
int C = Integer.parseInt(Status.LineToken.nextToken());
int D = Integer.parseInt(Status.LineToken.nextToken());
Status.WBO2S8Volts=((A*256)+B)/32768;
Status.WBO2S8VoltsEquivalenceRatio=((C*256)+D)/256 - 128;
Log.level1("WideBand Sensor 8 Voltage: " + Double.toString(Status.WBO2S8Volts));
Log.level1("WideBand Sensor 8 Volt EQR:" + Double.toString(Status.WBO2S8VoltsEquivalenceRatio));
```
Would it be wise to create a separate method to process the data since it is repetative? Or would it just be faster to execute it as a single method? I have several of these which would need to be rewritten and I am wondering if it would actually improve speed of execution or if it is just as good, or if there is a number of instructions where it becomes a good idea to create a new method.
Basically, what is faster or when does it become faster to use a single method to process objects versus using another method to process several like objects?
It seems like at runtime, pulling a new variable, then performing a math operation on it is quicker then creating a new method and then pulling a varible then performing a math operation on it. My question is really where the speed is at..
These methods are all called only to read data and set a Status.Variable. There are nearly 200 methods in my class which generate data. | 2010/06/21 | [
"https://Stackoverflow.com/questions/3089127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/368817/"
] | The speed difference of invoking a piece of code inside a method or outside of it is negligible. Specially compared with using the right algorithm for the task.
I would recommend you to use the method anyway, not for performance but for maintainability. If you need to change one line of code which turn out to introduce a bug or something and you have this code segment copy/pasted in 50 different places, it would be much harder to change ( and spot ) than having it in one single place.
So, don't worry about the performance penalty introduced by using methods because, it is practically nothing( even better, the VM may inline some of the calls ) | I think S. Lott's comment on your question probably hits the nail perfectly on the head - there's no point optimizing code until you're sure the code in question actually needs it. You'll most likely end up spending a lot of time and effort for next to no gain, otherwise.
I'll also second Support's answer, in that the difference in execution time between invoking a separate method and invoking the code inline is negligible (this was actually what I wanted to post, but he kinda beat me to it). It may even be zero, if an optimizing compiler or JIT decides to inline the method anyway (I'm not sure if there are any such compilers/JITs for Java, however).
There is one advantage of the separate method approach however - if you separate your data-processing code into a separate method, you could in theory achieve some increased performance by having that method called from a separate thread, thus decoupling your (possibly time-consuming) processing code from your other code. |
1,409,762 | How can I use PerfMon counters to record the average execution time of a method in C#?
So far I've only found sample code to incrememnt or decrement a PerfMon counter. | 2009/09/11 | [
"https://Stackoverflow.com/questions/1409762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113141/"
] | Here's some sample code I once wrote to do exactly that.
First, you need to specify and install the performance counters in question. You can do this by using an Installer:
```
public class CreditPerformanceMonitorInstaller : Installer
{
private PerformanceCounterInstaller counterInstaller_;
public CreditPerformanceMonitorInstaller()
{
this.counterInstaller_ = new PerformanceCounterInstaller();
this.counterInstaller_.CategoryName = CreditPerformanceCounter.CategoryName;
this.counterInstaller_.CategoryType = PerformanceCounterCategoryType.SingleInstance;
CounterCreationData transferAverageData = new CounterCreationData();
transferAverageData.CounterName = CreditPerformanceCounter.AverageTransferTimeCounterName;
transferAverageData.CounterHelp = "Reports the average execution time of transfer operations";
transferAverageData.CounterType = PerformanceCounterType.AverageTimer32;
this.counterInstaller_.Counters.Add(transferAverageData);
CounterCreationData transferAverageBaseData = new CounterCreationData();
transferAverageBaseData.CounterName = CreditPerformanceCounter.AverageTransferTimeBaseCounterName;
transferAverageBaseData.CounterHelp = "Base for average transfer time counter";
transferAverageBaseData.CounterType = PerformanceCounterType.AverageBase;
this.counterInstaller_.Counters.Add(transferAverageBaseData);
this.Installers.Add(this.counterInstaller_);
}
public Installer PerformanceCounterInstaller
{
get { return this.counterInstaller_; }
}
}
```
To write to the performance counter, you can do it like this:
```
public void RecordTransfer(long elapsedTicks)
{
using (PerformanceCounter averageTransferTimeCounter = new PerformanceCounter(),
averageTransferTimeBaseCounter = new PerformanceCounter())
{
averageTransferTimeCounter.CategoryName = CreditPerformanceCounter.CategoryName;
averageTransferTimeCounter.CounterName = CreditPerformanceCounter.AverageTransferTimeCounterName;
averageTransferTimeCounter.ReadOnly = false;
averageTransferTimeBaseCounter.CategoryName = CreditPerformanceCounter.CategoryName;
averageTransferTimeBaseCounter.CounterName = CreditPerformanceCounter.AverageTransferTimeBaseCounterName;
averageTransferTimeBaseCounter.ReadOnly = false;
averageTransferTimeCounter.IncrementBy(elapsedTicks);
averageTransferTimeBaseCounter.Increment();
}
}
``` | Take a look at the different [PerformanceCounterTypes](http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx).
There are several types for calculating average time or count. You will also find some examples.
Hope this helps. |
71,758,620 | I am struggling to install python version 3.7.6 using pyenv on my new macbook pro M1 running on mac os 12.3.1.
My configuration
```
$ clang -v
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
```
```
$ pyenv install 3.7.6
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.6.tar.xz...
-> https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tar.xz
Installing Python-3.7.6...
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
BUILD FAILED (OS X 12.3.1 using python-build 2.2.5-10-g58427b9a)
Inspect or clean up the working tree at /var/folders/4t/1qfwng092qz2qxwxm6ss2f1c0000gp/T/python-build.20220405170233.32567
Results logged to /var/folders/4t/1qfwng092qz2qxwxm6ss2f1c0000gp/T/python-build.20220405170233.32567.log
Last 10 log lines:
checking for --with-cxx-main=<compiler>... no
checking for clang++... no
configure:
By default, distutils will build C++ extension modules with "clang++".
If this is not intended, then set CXX on the configure command line.
checking for the platform triplet based on compiler characteristics... darwin
configure: error: internal configure error for the platform triplet, please file a bug report
``` | 2022/04/05 | [
"https://Stackoverflow.com/questions/71758620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9479543/"
] | Finally this patch works in installing 3.7.6 on macbook m1 using pyenv.
To install python 3.7.6 version in mac os 12+ , M1 chip, apple clang version 13+ using pyenv, create a file anywhere in your local and call it python-3.7.6-m1.patch and copy the contents(below) to that file and save it.
```html
diff --git a/configure b/configure
index b769d59629..8b018b6fe8 100755
--- a/configure
+++ b/configure
@@ -3370,7 +3370,7 @@ $as_echo "#define _BSD_SOURCE 1" >>confdefs.h
# has no effect, don't bother defining them
Darwin/[6789].*)
define_xopen_source=no;;
- Darwin/1[0-9].*)
+ Darwin/[12][0-9].*)
define_xopen_source=no;;
# On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
# used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -5179,8 +5179,6 @@ $as_echo "$as_me:
fi
-MULTIARCH=$($CC --print-multiarch 2>/dev/null)
-
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for the platform triplet based on compiler characteristics" >&5
$as_echo_n "checking for the platform triplet based on compiler characteristics... " >&6; }
@@ -5338,6 +5336,11 @@ $as_echo "none" >&6; }
fi
rm -f conftest.c conftest.out
+if test x$PLATFORM_TRIPLET != xdarwin; then
+ MULTIARCH=$($CC --print-multiarch 2>/dev/null)
+fi
+
+
if test x$PLATFORM_TRIPLET != x && test x$MULTIARCH != x; then
if test x$PLATFORM_TRIPLET != x$MULTIARCH; then
as_fn_error $? "internal configure error for the platform triplet, please file a bug report" "$LINENO" 5
@@ -9247,6 +9250,9 @@ fi
ppc)
MACOSX_DEFAULT_ARCH="ppc64"
;;
+ arm64)
+ MACOSX_DEFAULT_ARCH="arm64"
+ ;;
*)
as_fn_error $? "Unexpected output of 'arch' on OSX" "$LINENO" 5
;;
diff --git a/configure.ac b/configure.ac
index 49acff3136..2f66184b26 100644
--- a/configure.ac
+++ b/configure.ac
@@ -490,7 +490,7 @@ case $ac_sys_system/$ac_sys_release in
# has no effect, don't bother defining them
Darwin/@<:@6789@:>@.*)
define_xopen_source=no;;
- Darwin/1@<:@0-9@:>@.*)
+ Darwin/@<:@[12]@:>@@<:@0-9@:>@.*)
define_xopen_source=no;;
# On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
# used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -724,8 +724,7 @@ then
fi
-MULTIARCH=$($CC --print-multiarch 2>/dev/null)
-AC_SUBST(MULTIARCH)
+
AC_MSG_CHECKING([for the platform triplet based on compiler characteristics])
cat >> conftest.c <<EOF
@@ -880,6 +879,11 @@ else
fi
rm -f conftest.c conftest.out
+if test x$PLATFORM_TRIPLET != xdarwin; then
+ MULTIARCH=$($CC --print-multiarch 2>/dev/null)
+fi
+AC_SUBST(MULTIARCH)
+
if test x$PLATFORM_TRIPLET != x && test x$MULTIARCH != x; then
if test x$PLATFORM_TRIPLET != x$MULTIARCH; then
AC_MSG_ERROR([internal configure error for the platform triplet, please file a bug report])
```
NOW we can Install python 3.7.6 using pyenv as follows (need to be in the same directory as the patch file that we just created):
```
pyenv install --patch 3.7.6 < python-3.7.6-m1.patch
```
**To install other python version on mac os 12+ , M1 chip, apple clang version 13+ using pyenv (not tested but should work)**
Shallow clone the branch of python version you are interested in installing. go to <https://github.com/python/cpython> and find the versions available for cloning under "tags" dropdown
```
git clone https://github.com/python/cpython --branch v3.x.x --single-branch
cd cpython
```
Now make changes to the two files in it (configure.ac and configure). the git diff should look like the one shown above. The line numbers will be different based on which version of python you are installing, this git diff file is for 3.7.6 and can't be directly used for other versions. for other versions of python, search for the exact line of code being edited/deleted in the exact file as shown in the above git diff and make the changes accordingly. then save the git diff in a new file as follows.
```
git diff > python-3.x.x-m1.patch
```
Now we can install that version using:
```
pyenv install --patch 3.x.x < python-3.x.x-m1.patch
``` | If you are not bound to a particular patch (i.e. z in x.y.z), this excerpt from the following [link](https://github.com/pyenv/pyenv/issues/2143#issuecomment-1070640288) could help you:
>
> I can confirm yesterday's releases 3.7.13, 3.8.13, 3.9.11 and 3.10.3 all work fine on my Intel mac. The GCC solution was not a viable one for me as it caused issues with pip modules that were built with clang. I don't think I need 3.6 or older branches at the moment but I suspect they might need manual patches via pyenv since they're EOL upstream.
>
>
>
I personally needed the 3.8.x version and succeeded with `pyenv install 3.8.13`. |
45,782 | During *Goblet of Fire*, Hagrid is seen showing interest in Madame Maxime and, at one point, she seems to show some interest back (canon quotes can be added if someone doubts this).
Is there any indication from JKR (books/interviews/web) on whether that relationship progressed/continued past their flirting in *Goblet of Fire*, either during their mission to the giants or afterwards? | 2013/12/04 | [
"https://scifi.stackexchange.com/questions/45782",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/976/"
] | J.K. Rowling addressed this in [an interview in 2007](https://web.archive.org/web/20080724011245/http://www.the-leaky-cauldron.org/2007/10/20/j-k-rowling-at-carnegie-hall-reveals-dumbledore-is-gay-neville-marries-hannah-abbott-and-scores-more), after the publication of the final book:
>
> **Did Hagrid ever get married and have children?**
>
>
> Oh, did Hagrid ever get married and have children? No. […]
>
>
> Realistically, Hagrid's pool of potential girlfriends is extremely limited. Because with the giants killing each other off, the number of giantesses around is infinitesimal and he met one of the only [ones], and I'm afraid, she thought he was kind of cute, but she was a little more, how should I put it, sophisticated than Hagrid. So no, bless him.
>
>
>
The “only one” that Rowling refers to must be Maxime, so we can assume that any romantic feelings they had for each other weren’t enough to keep them together.
However, they didn’t part on bad terms. They clearly remained friends, as shown when they greeted each other at Dumbledore’s funeral:
>
> Harry watched from a window as a gigantic and handsome olive- skinned, black-haired woman descended the carriage steps and threw herself into the waiting Hagrid’s arms.
>
>
> — *Half-Blood Prince*, chapter 30 (*The White Tomb*)
>
>
> | In book five, Hagrid went with Madame Maxime to try to win over the giants. I believe they went together because of affection for each other, rather than because someone else (Dumbledore!) told them to. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | Me thinks the answer given below by Tadmas was very helpful and I want you guys to hack/bully my implementation below. As Tadmas points out all my numbers are 40 bits (12 digit number is 10^12 which is 2^40 approx).
I copied the sun.security.rsa.RSAKeyPairGenerator (link) and created my own generator for a 40 bit RSA algorithm. The standard one needs between 512-1024 bits so I removed the input check around it. Once I create a suitable n, e, d values (e seems to be 65537 as per the alog). The following code served fine,
```
public void testSimple() throws NoSuchAlgorithmException {
MyKeyPairGenerator x = new MyKeyPairGenerator();
x.initialize(40, new SecureRandom("password".getBytes()));
MyPublicPrivateKey keypair = x.generateKeyPair();
System.out.println(keypair);
BigInteger message = new BigInteger("167890871234");
BigInteger encoded = message.modPow(keypair.e, keypair.n);
System.out.println(encoded); //gives some encoded value
BigInteger decoded = encoded.modPow(keypair.d, keypair.n);
System.out.println(decoded); //gives back original value
}
```
Disadvantages
1. The encoded may not always be 12 digits (sometimes it may start with 0 which means only 11 digits). I am thinking always pad 0 zeroes in the front and add some CHECKSUM digit at the start which might alleviate this problem. So a 13 digit always...
2. A 40 bits RSA is weaker than 512 bit (not just 512/40 times but an exponential factor of times). Can you experts point me to links as to how secure is a 40bit RSA compared to 512 bit RSA (I can see some stuff in wiki but cannot concretely confirm possibility of attacks)? Any links (wiki?) on probabilities/number of attempts required to hack RSA as a function of N where n is the number of bits used will be great ! | If I understand your problem correctly you have a problem with the 16 bytes after decrypting. The trick is to use: Cipher.getInstance("DES/ECB/PKCS5Padding");
(just in case code is helpful):
```
public void mytestSimple(long code, String password) throws Exception
{ SecretKey key = new SecretKeySpec (password.getBytes(),"DES");
Cipher ecipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] plaintext = new byte[8];
for (int i=0; i<8; i++)
{ plaintext[7-i] = (byte) (code & 0x00FF);
>>>= 8;
}
ecipher.init (Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(plaintext);
System.out.println("--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] crypttext = dcipher.doFinal(encrypted);
long decoded = 0;
for (int i=0; i<8; i++)
{ decoded <<= 8;
decoded += crypttext[i] & 0x00FF;
}
System.out.println(decode + "--" + crypttext.length);
}
``` |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | You're not going to be able to convert 16 bytes into a 12 digit number without losing information. 256 ^ 16 > 10^12. (Not that you even have 10^12 options, as you've only got the range [100000000000, 999999999999].
I doubt that you'll be able to use any traditional encryption libraries, as your requirements are somewhat odd. | One potential solution could be built on [Feistel ciphers](http://en.wikipedia.org/wiki/Feistel_cipher).
This constructions allows to build a pseudorandom permutation based on a pseudorandom functions. E.g. the pseudorandom functions could be constructed from an appropriate block cipher by truncating the result to a 6 digit numbers.
This construction has been analyzed in the following paper
M. Luby and C. Rackoff, "How to construct pseudorandom permutations from pseudorandom functions" SIAM Journal on Computing, Vol.17, No.2, pp.373--386, 1988
---
A concrete proposal is the [Feistel Finite Set Encryption Mode](http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffsem/ffsem-spec.pdf), which has been
submitted to NIST for potential inclusion into an upcoming standard. This proposal also
addresses the problem of encrypting ranges that are not a power of 2. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | If the strict 1:1 mapping is more important than protecting against cryptanalysis, then you can convert the password to a 12-digit number (via hash or otherwise) and simply add to your original number mod 10^12. If you absolutely must remove leading zeros from the output, you can subtract 10^11, do the math mod (10^12 - 10^11), and then add 10^11 back again. Granted, that's extremely insecure, but it's quite simple. :)
If the range of inputs is bounded by a prime less than (10^12 - 10^11), you may be able to use message ^ password mod prime to form a ring that will satisfy your requirements and be a little harder to crack. (This is similar to how RSA works.) I think this could work if you don't need to decrypt it.
I agree with Jon Skeet: requiring a strict 1:1 mapping without the output range being bigger than the input domain is something that most encryption libraries are not going to handle. | One potential solution could be built on [Feistel ciphers](http://en.wikipedia.org/wiki/Feistel_cipher).
This constructions allows to build a pseudorandom permutation based on a pseudorandom functions. E.g. the pseudorandom functions could be constructed from an appropriate block cipher by truncating the result to a 6 digit numbers.
This construction has been analyzed in the following paper
M. Luby and C. Rackoff, "How to construct pseudorandom permutations from pseudorandom functions" SIAM Journal on Computing, Vol.17, No.2, pp.373--386, 1988
---
A concrete proposal is the [Feistel Finite Set Encryption Mode](http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffsem/ffsem-spec.pdf), which has been
submitted to NIST for potential inclusion into an upcoming standard. This proposal also
addresses the problem of encrypting ranges that are not a power of 2. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | One potential solution could be built on [Feistel ciphers](http://en.wikipedia.org/wiki/Feistel_cipher).
This constructions allows to build a pseudorandom permutation based on a pseudorandom functions. E.g. the pseudorandom functions could be constructed from an appropriate block cipher by truncating the result to a 6 digit numbers.
This construction has been analyzed in the following paper
M. Luby and C. Rackoff, "How to construct pseudorandom permutations from pseudorandom functions" SIAM Journal on Computing, Vol.17, No.2, pp.373--386, 1988
---
A concrete proposal is the [Feistel Finite Set Encryption Mode](http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffsem/ffsem-spec.pdf), which has been
submitted to NIST for potential inclusion into an upcoming standard. This proposal also
addresses the problem of encrypting ranges that are not a power of 2. | I would use a [stream](http://en.wikipedia.org/wiki/Stream_cipher) [cipher](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation). *N* bytes go in, *N* bytes come out. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | If the numbers are for user IDs, this is what I'd do:
(1) Generate an AES key from the password. Just calling getBytes() is sort of OK if you trust the administrator to use a really really really strong password. Ideally, use the standard "password-based encryption" technique of hashing the bytes, say, a few thousand times, each time adding in the random "salt" bytes that you initially generated to avoid dictionary attacks.
(2) Encrypt the number in question with that AES key.
(3) Chop off 12 digits' worth of bits from the resulting encrypted block, convert it to decimal, and present that number to the user. (To do this, you can wrap a BigInteger around the bytes, call toString() on it, and pull off, say, the bytes between position 4 and 16.) Experimentally, it looks like you shouldn't take the digits from the rightmost end.
[**Update**: I *think* this is probably because BigInteger literally allocates its numbers from left to rightmost bit-- but I haven't checked-- so there'll potentially be "spare" bits in the very rightmost byte, and hence fewer possible numbers if you include the very last byte.]
Now, I hear you cry, this obviously isn't a 1-1 mapping. But unless you're going to have more than tens of thousands of users, it's really good enough. With a 12-digit number, you'd expect on average to encrypt around 300,000 numbers before getting a collision. So although you don't strictly have a 1-1 mapping, in practice, it's as near as dammit.
(In any case, if your application really has hundreds of thoudands of users and security is crucial, then you'll probably want to invest in some serious consulting over this kind of thing...)
Just to convince yourself that it really is OK to pretend it's a 1-1 mapping, you can run a simulation that repeatedly tries to allocate, say, 200,000 user IDs with random keys, and prints out how many collisions there were on each run:
```
next_pass :
for (int pass = 0; pass < 100; pass++) {
byte[] key = new byte[16];
(new SecureRandom()).nextBytes(key);
Cipher ciph = Cipher.getInstance("AES");
SecretKeySpec ks = new SecretKeySpec(key, "AES");
ByteBuffer bb = ByteBuffer.allocate(16);
Set<String> already = new HashSet<String>(100000);
int colls = 0;
for (int i = 0; i < 200000; i++) {
bb.putLong(0, i);
ciph.init(Cipher.ENCRYPT_MODE, ks);
byte[] encr = ciph.doFinal(bb.array());
encr[0] &= 0x7f; // make all numbers positive
BigInteger bigint = new BigInteger(encr);
String userNo = bigint.toString();
userNo = userNo.substring(4, 16);
if (!already.add(userNo)) {
System.out.println("Coll after " + i);
continue next_pass;
}
}
System.out.println("No collision.");
}
``` | I would use a [stream](http://en.wikipedia.org/wiki/Stream_cipher) [cipher](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation). *N* bytes go in, *N* bytes come out. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | One potential solution could be built on [Feistel ciphers](http://en.wikipedia.org/wiki/Feistel_cipher).
This constructions allows to build a pseudorandom permutation based on a pseudorandom functions. E.g. the pseudorandom functions could be constructed from an appropriate block cipher by truncating the result to a 6 digit numbers.
This construction has been analyzed in the following paper
M. Luby and C. Rackoff, "How to construct pseudorandom permutations from pseudorandom functions" SIAM Journal on Computing, Vol.17, No.2, pp.373--386, 1988
---
A concrete proposal is the [Feistel Finite Set Encryption Mode](http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffsem/ffsem-spec.pdf), which has been
submitted to NIST for potential inclusion into an upcoming standard. This proposal also
addresses the problem of encrypting ranges that are not a power of 2. | This thread is 4 years old, but for those finding the thread in Google: have a look at Format Preserving Ciphers: <http://en.wikipedia.org/wiki/Format-preserving_encryption> |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | If the strict 1:1 mapping is more important than protecting against cryptanalysis, then you can convert the password to a 12-digit number (via hash or otherwise) and simply add to your original number mod 10^12. If you absolutely must remove leading zeros from the output, you can subtract 10^11, do the math mod (10^12 - 10^11), and then add 10^11 back again. Granted, that's extremely insecure, but it's quite simple. :)
If the range of inputs is bounded by a prime less than (10^12 - 10^11), you may be able to use message ^ password mod prime to form a ring that will satisfy your requirements and be a little harder to crack. (This is similar to how RSA works.) I think this could work if you don't need to decrypt it.
I agree with Jon Skeet: requiring a strict 1:1 mapping without the output range being bigger than the input domain is something that most encryption libraries are not going to handle. | If you're prepared to accept a rather **weak solution**...
Treat the 12-digit number as two 6-digit numbers. Then use the hash of the password as a seed to a random number generator which shuffles a table of 999,990 consecutive values. Then use the two 6-digit numbers to look up entries in the table. The concatenation of the two results is your 1:1 mapped 12-digit 'encrypted' input based on a password.
Let's do an example with 4-digits instead of 12...
```
Input: 4852
Password: passw0rd1 => hashcode = 37592
```
Now take this array..
```
a = [10, 11, 12, 13, .. 98, 99]
```
And shuffle it with 37592 as the random seed...
```
b = [45, 15, 56, 49, .. 33, 88]
```
Now split the input: 48, 52 and look up those indices in the shuffled array, say...
```
b[48] => 23
b[52] => 96
```
So our encrypted version of 4852 is 2396
It really isn't a strong solution but the constraints in your question will not lead to a strong solution. You may need to relax those constraints a bit. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | Me thinks the answer given below by Tadmas was very helpful and I want you guys to hack/bully my implementation below. As Tadmas points out all my numbers are 40 bits (12 digit number is 10^12 which is 2^40 approx).
I copied the sun.security.rsa.RSAKeyPairGenerator (link) and created my own generator for a 40 bit RSA algorithm. The standard one needs between 512-1024 bits so I removed the input check around it. Once I create a suitable n, e, d values (e seems to be 65537 as per the alog). The following code served fine,
```
public void testSimple() throws NoSuchAlgorithmException {
MyKeyPairGenerator x = new MyKeyPairGenerator();
x.initialize(40, new SecureRandom("password".getBytes()));
MyPublicPrivateKey keypair = x.generateKeyPair();
System.out.println(keypair);
BigInteger message = new BigInteger("167890871234");
BigInteger encoded = message.modPow(keypair.e, keypair.n);
System.out.println(encoded); //gives some encoded value
BigInteger decoded = encoded.modPow(keypair.d, keypair.n);
System.out.println(decoded); //gives back original value
}
```
Disadvantages
1. The encoded may not always be 12 digits (sometimes it may start with 0 which means only 11 digits). I am thinking always pad 0 zeroes in the front and add some CHECKSUM digit at the start which might alleviate this problem. So a 13 digit always...
2. A 40 bits RSA is weaker than 512 bit (not just 512/40 times but an exponential factor of times). Can you experts point me to links as to how secure is a 40bit RSA compared to 512 bit RSA (I can see some stuff in wiki but cannot concretely confirm possibility of attacks)? Any links (wiki?) on probabilities/number of attempts required to hack RSA as a function of N where n is the number of bits used will be great ! | For mathematical reasons, most cyphers will produce "more" bytes (i.e. they will pad the input). So you will have to accept that the code generates 16bytes out of your 12 digit number.
When the string is decoded, you will get the 12 digit number back but during transport, you need 16 bytes. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | If the strict 1:1 mapping is more important than protecting against cryptanalysis, then you can convert the password to a 12-digit number (via hash or otherwise) and simply add to your original number mod 10^12. If you absolutely must remove leading zeros from the output, you can subtract 10^11, do the math mod (10^12 - 10^11), and then add 10^11 back again. Granted, that's extremely insecure, but it's quite simple. :)
If the range of inputs is bounded by a prime less than (10^12 - 10^11), you may be able to use message ^ password mod prime to form a ring that will satisfy your requirements and be a little harder to crack. (This is similar to how RSA works.) I think this could work if you don't need to decrypt it.
I agree with Jon Skeet: requiring a strict 1:1 mapping without the output range being bigger than the input domain is something that most encryption libraries are not going to handle. | I suggest a very simple algorithm.
1. Feed the password into a hash function.
2. Initialize a random number generator with the hash or something you derived from the hash.
3. Generate a 12 digit random number.
4. Add this random number to the input digit by digit modulo 10 to encrypt.
To decrypt subtract the random number modulo 10. This is actually a form of [One Time Pad](http://en.wikipedia.org/wiki/One-time_pad). Because of the comments on this answer I realized that refering to [One Time Pad](http://en.wikipedia.org/wiki/One-time_pad) was a bad choice. A better reference is [Polyalphabetic cipher](http://en.wikipedia.org/wiki/Polyalphabetic_substitution) - while One Time Pad uses polyalphabetic substitution its main characteristic is not to use any key bit twice.
```
Input 1234 1234 1234
Random number 6710 3987 2154
Output 7944 4111 3388
```
There is one remaining problem with that - the algorithm might create leading zeros. To solve this problem one could use `XOR` instead of addition and substraction. Just transform the digits with `XOR`. If the first digit turns into a zero, don't encrypt the first digit. When you decrypt with `XOR` again, the first digit will turn into zero and you know that the first digit was not enrcypted.
**UPDATE**
A simple `XOR` is not the solution because it will produce to large numbers - `2 XOR 9 = 11` for example. Going to rethinks this...
**UPDATE**
The nice propoerties of `XOR` are `XOR(a, b) = XOR(b, a)` and `XOR(XOR(a, b), b) = a`. This makes encryption and decryption the same and allows to detect the unencrypted leading digit. But it is further required that our function only returns values in the range from 0 to 9 what `XOR` doesn't do.
But maybe we can build a custom function with all required properties. So we create an array `FUNC` with 10 columns and 10 rows and use it as a lookup table for our function. What values to but in? I actually don't know - I am not even sure that it is possible. But if we pick three number from the range 0 to 9 we have to make the following six entries. (It is a symmetric matrix.)
```
FUNC[x,y] = z FUNC[x,z] = y FUNC[y,z] = x
FUNC[y,x] = z FUNC[z,x] = y FUNC[z,y] = x
```
So maybe it is possible to create such a function by repeatedly choosing random numbers and filling the six entries if there is no conflict. Maybe it is not. I would like to see the table if one finds a solution. |
858,476 | I have already read [Using Java to encrypt integers](https://stackoverflow.com/questions/321787/using-java-to-encrypt-integers) and [Encrypting with DES Using a Pass Phrase](http://www.exampledepot.com/egs/javax.crypto/PassKey.html).
All I need is a simple Encrypter which transforms a 12 digit number to a 12 digit number with the following constraints:
1. The encryption must depend on a password (which will be constant throughout the life time of an application) and nothing else.
2. The mapping must be 1-1 (No hashing and multiple inputs giving same output and vice versa).
3. The mapping must not change between different VMs or when VM is started (like when you restart Java, the utility should give you same mappings which means that it must be purely dependent on the password that is supplied).
4. Numbers starting with 0 is not a valid 12 digit number (also input numbers won't start with 0).
5. The key/password should never be guessable. For example running the utility with multiple inputs and analysing the outputs should not allow one to guess the key/pwd/hash or whatever.
6. All inputs will be exactly 12 digits and less than a 12 digit prime number (which means we could use modulo arithmetic).
Having trawled through the literature I have this code with me
```
public void mytestSimple(long code, String password) throws Exception {
SecretKey key = new SecretKeySpec(password.getBytes(), "DES");
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(ecipher.getOutputSize(8));
byte[] encrypted = ecipher.doFinal(numberToBytes(code));
System.out.println(encrypted + "--" + encrypted.length);
Cipher dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = dcipher.doFinal(encrypted);
System.out.println(bytesToNumber(decrypted) + "--" + decrypted.length);
}
public void testSimple() throws Exception {
mytestSimple(981762654986L, "password");
}
```
I am running into problems as to
1. How to convert the 16 bytes into a 12 digit number.
2. Maintain 1-1 mapping.
3. Keep the encryption/decryption same across multiple VM invocations.
\*\*\*\* Answer added by me below\*\*\*\*
I have added one answer which is a 40bit RSA pulled out of standard Java RSA keypair gen logic. I still have to work on the edge cases. I am going to accept the answer and upvote "Tadmas" who I think kinda lead me to the answer. Can someone tell me if my algorithm is going to be weak/attackable? | 2009/05/13 | [
"https://Stackoverflow.com/questions/858476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | This thread is 4 years old, but for those finding the thread in Google: have a look at Format Preserving Ciphers: <http://en.wikipedia.org/wiki/Format-preserving_encryption> | If you're prepared to accept a rather **weak solution**...
Treat the 12-digit number as two 6-digit numbers. Then use the hash of the password as a seed to a random number generator which shuffles a table of 999,990 consecutive values. Then use the two 6-digit numbers to look up entries in the table. The concatenation of the two results is your 1:1 mapped 12-digit 'encrypted' input based on a password.
Let's do an example with 4-digits instead of 12...
```
Input: 4852
Password: passw0rd1 => hashcode = 37592
```
Now take this array..
```
a = [10, 11, 12, 13, .. 98, 99]
```
And shuffle it with 37592 as the random seed...
```
b = [45, 15, 56, 49, .. 33, 88]
```
Now split the input: 48, 52 and look up those indices in the shuffled array, say...
```
b[48] => 23
b[52] => 96
```
So our encrypted version of 4852 is 2396
It really isn't a strong solution but the constraints in your question will not lead to a strong solution. You may need to relax those constraints a bit. |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | There's a lot of confusing information out there on virtual environments, because of how they have evolved. Since Python 3.3, the `venv` module is available with Python as part of the standard library to create virtual environments, and if you're just getting started, I'd recommend learning it first. There's nothing extra to install after you've installed Python 3.8.
From your project's home directory in the VSCode terminal, try this:
```
python3 -m venv venv
. venv/bin/activate
pip install Django
```
Here's what the three lines do:
1. Call the Python module `venv` and create a new virtual environment in the directory `venv`
2. Run the script to activate the virtual environment that is located in the path `venv/bin/activate`
3. Now that the `venv` is activated, install Django.
After the first time install, you'll just need to repeat step (2) to activate it. You can also point VSCode to automatically start it when you fire up the IDE. You can click the bar at the bottom of VSCode after installing the Python plugin to select the Python version in the `venv` you've created. Good luck!
**Update:**
Here's an example of it working in `zsh` on my machine:
```
$ zsh
% python3 --version
Python 3.8.2
% python3 -m venv venv
% . venv/bin/activate
(venv) % pip install Django
Collecting Django
Collecting pytz (from Django)
Collecting asgiref~=3.2.10 (from Django)
Collecting sqlparse>=0.2.2 (from Django)
Installing collected packages: pytz, asgiref, sqlparse, Django
Successfully installed Django-3.1.1 asgiref-3.2.10 pytz-2020.1 sqlparse-0.3.1
``` | I was stuck on this for a good while
but you can try venv:
```
python -m venv virtualenvname
#to activate the virtual environment
source virtualenvname/Scripts/activate
``` |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | There's a lot of confusing information out there on virtual environments, because of how they have evolved. Since Python 3.3, the `venv` module is available with Python as part of the standard library to create virtual environments, and if you're just getting started, I'd recommend learning it first. There's nothing extra to install after you've installed Python 3.8.
From your project's home directory in the VSCode terminal, try this:
```
python3 -m venv venv
. venv/bin/activate
pip install Django
```
Here's what the three lines do:
1. Call the Python module `venv` and create a new virtual environment in the directory `venv`
2. Run the script to activate the virtual environment that is located in the path `venv/bin/activate`
3. Now that the `venv` is activated, install Django.
After the first time install, you'll just need to repeat step (2) to activate it. You can also point VSCode to automatically start it when you fire up the IDE. You can click the bar at the bottom of VSCode after installing the Python plugin to select the Python version in the `venv` you've created. Good luck!
**Update:**
Here's an example of it working in `zsh` on my machine:
```
$ zsh
% python3 --version
Python 3.8.2
% python3 -m venv venv
% . venv/bin/activate
(venv) % pip install Django
Collecting Django
Collecting pytz (from Django)
Collecting asgiref~=3.2.10 (from Django)
Collecting sqlparse>=0.2.2 (from Django)
Installing collected packages: pytz, asgiref, sqlparse, Django
Successfully installed Django-3.1.1 asgiref-3.2.10 pytz-2020.1 sqlparse-0.3.1
``` | ```
Solution of the problem of virtual environment created but not activated.
=========================================================================
to make activate just add a space between .(dot) and your venv path. i,e
$ . yourvirtualenv/bin/activate
Hope this will work. But not use like:
$ yourvirtualenv/bin/activate
or
$ /yourvirtualenv/bin/activate
Here is my command and the output:
admin@osboxes:~/pysrc$ . my_env/bin/activate
(my_env) admin@osboxes:~/pysrc$
---
Output of the wrong command:
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$ sudo my_env/bin/activate
[sudo] password for admin:
sudo: my_env/bin/activate: command not found
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$
``` |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | There's a lot of confusing information out there on virtual environments, because of how they have evolved. Since Python 3.3, the `venv` module is available with Python as part of the standard library to create virtual environments, and if you're just getting started, I'd recommend learning it first. There's nothing extra to install after you've installed Python 3.8.
From your project's home directory in the VSCode terminal, try this:
```
python3 -m venv venv
. venv/bin/activate
pip install Django
```
Here's what the three lines do:
1. Call the Python module `venv` and create a new virtual environment in the directory `venv`
2. Run the script to activate the virtual environment that is located in the path `venv/bin/activate`
3. Now that the `venv` is activated, install Django.
After the first time install, you'll just need to repeat step (2) to activate it. You can also point VSCode to automatically start it when you fire up the IDE. You can click the bar at the bottom of VSCode after installing the Python plugin to select the Python version in the `venv` you've created. Good luck!
**Update:**
Here's an example of it working in `zsh` on my machine:
```
$ zsh
% python3 --version
Python 3.8.2
% python3 -m venv venv
% . venv/bin/activate
(venv) % pip install Django
Collecting Django
Collecting pytz (from Django)
Collecting asgiref~=3.2.10 (from Django)
Collecting sqlparse>=0.2.2 (from Django)
Installing collected packages: pytz, asgiref, sqlparse, Django
Successfully installed Django-3.1.1 asgiref-3.2.10 pytz-2020.1 sqlparse-0.3.1
``` | I just prefer using 'venv' as a name for all my virtual environments, so always I'll use the same command to activate environments in my machine.
Try:
```
# Create the virtual environment inside your project's folder
$ python3 -m venv venv
#Activate it
$ source venv/bin/activate
```
As I need to change projects and environments quite often, I created two alias in the system (ubuntu 20.04), one for creating and another to activate it, as shown above:
To create I chose 'venv' as my alias name. Before creating I certified that an existing 'venv' folder was deleted.
```
venv='rm -rf venv && python3.9 -m venv venv'
```
To activate I chose 'activate' as my alias name
```
activate='source venv/bin/activate'
```
Window commands to create and activate are a little different as you can notice in [this answer](https://stackoverflow.com/a/66432333/11755155). |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | There's a lot of confusing information out there on virtual environments, because of how they have evolved. Since Python 3.3, the `venv` module is available with Python as part of the standard library to create virtual environments, and if you're just getting started, I'd recommend learning it first. There's nothing extra to install after you've installed Python 3.8.
From your project's home directory in the VSCode terminal, try this:
```
python3 -m venv venv
. venv/bin/activate
pip install Django
```
Here's what the three lines do:
1. Call the Python module `venv` and create a new virtual environment in the directory `venv`
2. Run the script to activate the virtual environment that is located in the path `venv/bin/activate`
3. Now that the `venv` is activated, install Django.
After the first time install, you'll just need to repeat step (2) to activate it. You can also point VSCode to automatically start it when you fire up the IDE. You can click the bar at the bottom of VSCode after installing the Python plugin to select the Python version in the `venv` you've created. Good luck!
**Update:**
Here's an example of it working in `zsh` on my machine:
```
$ zsh
% python3 --version
Python 3.8.2
% python3 -m venv venv
% . venv/bin/activate
(venv) % pip install Django
Collecting Django
Collecting pytz (from Django)
Collecting asgiref~=3.2.10 (from Django)
Collecting sqlparse>=0.2.2 (from Django)
Installing collected packages: pytz, asgiref, sqlparse, Django
Successfully installed Django-3.1.1 asgiref-3.2.10 pytz-2020.1 sqlparse-0.3.1
``` | I had the same problem. It came right out of nowhere. To keep it simple please use **source** for running the activate script. In Linux e.g.
```
source .virtualenvs/test/bin/activate
```
I don't know why but these became crucial.
Code up Donald |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | I was stuck on this for a good while
but you can try venv:
```
python -m venv virtualenvname
#to activate the virtual environment
source virtualenvname/Scripts/activate
``` | I just prefer using 'venv' as a name for all my virtual environments, so always I'll use the same command to activate environments in my machine.
Try:
```
# Create the virtual environment inside your project's folder
$ python3 -m venv venv
#Activate it
$ source venv/bin/activate
```
As I need to change projects and environments quite often, I created two alias in the system (ubuntu 20.04), one for creating and another to activate it, as shown above:
To create I chose 'venv' as my alias name. Before creating I certified that an existing 'venv' folder was deleted.
```
venv='rm -rf venv && python3.9 -m venv venv'
```
To activate I chose 'activate' as my alias name
```
activate='source venv/bin/activate'
```
Window commands to create and activate are a little different as you can notice in [this answer](https://stackoverflow.com/a/66432333/11755155). |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | I was stuck on this for a good while
but you can try venv:
```
python -m venv virtualenvname
#to activate the virtual environment
source virtualenvname/Scripts/activate
``` | I had the same problem. It came right out of nowhere. To keep it simple please use **source** for running the activate script. In Linux e.g.
```
source .virtualenvs/test/bin/activate
```
I don't know why but these became crucial.
Code up Donald |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | ```
Solution of the problem of virtual environment created but not activated.
=========================================================================
to make activate just add a space between .(dot) and your venv path. i,e
$ . yourvirtualenv/bin/activate
Hope this will work. But not use like:
$ yourvirtualenv/bin/activate
or
$ /yourvirtualenv/bin/activate
Here is my command and the output:
admin@osboxes:~/pysrc$ . my_env/bin/activate
(my_env) admin@osboxes:~/pysrc$
---
Output of the wrong command:
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$ sudo my_env/bin/activate
[sudo] password for admin:
sudo: my_env/bin/activate: command not found
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$
``` | I just prefer using 'venv' as a name for all my virtual environments, so always I'll use the same command to activate environments in my machine.
Try:
```
# Create the virtual environment inside your project's folder
$ python3 -m venv venv
#Activate it
$ source venv/bin/activate
```
As I need to change projects and environments quite often, I created two alias in the system (ubuntu 20.04), one for creating and another to activate it, as shown above:
To create I chose 'venv' as my alias name. Before creating I certified that an existing 'venv' folder was deleted.
```
venv='rm -rf venv && python3.9 -m venv venv'
```
To activate I chose 'activate' as my alias name
```
activate='source venv/bin/activate'
```
Window commands to create and activate are a little different as you can notice in [this answer](https://stackoverflow.com/a/66432333/11755155). |
63,694,874 | New to running Python in virtual environments, messing with Django, and can't activate a virtual environment.
Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck.
Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc.
"pip install virtualenv" output:
--------------------------------
Collecting virtualenv
Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB)
Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.0.31
"virtualenv venv" output:
-------------------------
created virtual environment CPython3.8.5.final.0-64 in 416ms
creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app\_data\_dir=/Users/garrettpinto/Library/Application Support/virtualenv)
added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
"source venv/bin/activate" returns nothing
------------------------------------------
"./venv/bin/activate" output:
-----------------------------
zsh: permission denied: ./venv/bin/activate
"sudo ./venv/bin/activate" output:
----------------------------------
sudo: ./venv/bin/activate: command not found
Thoughts? | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200457/"
] | ```
Solution of the problem of virtual environment created but not activated.
=========================================================================
to make activate just add a space between .(dot) and your venv path. i,e
$ . yourvirtualenv/bin/activate
Hope this will work. But not use like:
$ yourvirtualenv/bin/activate
or
$ /yourvirtualenv/bin/activate
Here is my command and the output:
admin@osboxes:~/pysrc$ . my_env/bin/activate
(my_env) admin@osboxes:~/pysrc$
---
Output of the wrong command:
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$ sudo my_env/bin/activate
[sudo] password for admin:
sudo: my_env/bin/activate: command not found
admin@osboxes:~/pysrc$ my_env/bin/activate
bash: my_env/bin/activate: Permission denied
admin@osboxes:~/pysrc$
``` | I had the same problem. It came right out of nowhere. To keep it simple please use **source** for running the activate script. In Linux e.g.
```
source .virtualenvs/test/bin/activate
```
I don't know why but these became crucial.
Code up Donald |
14,824,491 | More specifically, if a computer has a server (a `java.net.ServerSocket` instance) can I connect to it using a C# `System.Net.Sockets.Socket` instance? | 2013/02/12 | [
"https://Stackoverflow.com/questions/14824491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392195/"
] | The main issue is that you need to be very careful with the encoding of the data that you send and receive. Here is a pair of programs that work together. The C# client sends a string, by first sending its length as an integer, and then sending the bytes of the string itself. The Java server reads the length, then reads the message and prints an output to the console. Then composes an echo message, computes its length, extracts the bytes and sends it back to the C# client. The client reads the length, the message and prints an output. There should be a way to avoid all the bitwise stuff, but honestly I'm a little rusty with this stuff, especially on the Java side.
A Java server:
```
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class JavaSocket {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4343, 10);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Receiving
byte[] lenBytes = new byte[4];
is.read(lenBytes, 0, 4);
int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
byte[] receivedBytes = new byte[len];
is.read(receivedBytes, 0, len);
String received = new String(receivedBytes, 0, len);
System.out.println("Server received: " + received);
// Sending
String toSend = "Echo: " + received;
byte[] toSendBytes = toSend.getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff);
toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff);
toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff);
os.write(toSendLenBytes);
os.write(toSendBytes);
socket.close();
serverSocket.close();
}
}
```
A C# client:
```
using System;
using System.Net;
using System.Net.Sockets;
namespace CSharpSocket
{
class MainClass
{
public static void Main (string[] args)
{
string toSend = "Hello!";
IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse("192.168.0.6"), 4343);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(serverAddress);
// Sending
int toSendLen = System.Text.Encoding.ASCII.GetByteCount(toSend);
byte[] toSendBytes = System.Text.Encoding.ASCII.GetBytes(toSend);
byte[] toSendLenBytes = System.BitConverter.GetBytes(toSendLen);
clientSocket.Send(toSendLenBytes);
clientSocket.Send(toSendBytes);
// Receiving
byte[] rcvLenBytes = new byte[4];
clientSocket.Receive(rcvLenBytes);
int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0);
byte[] rcvBytes = new byte[rcvLen];
clientSocket.Receive(rcvBytes);
String rcv = System.Text.Encoding.ASCII.GetString(rcvBytes);
Console.WriteLine("Client received: " + rcv);
clientSocket.Close();
}
}
}
``` | I figure how to loop this method so you can send client message over and over again. Let me know if you found this useful. I build this on Eclipse with Export Ant script. I will include ant script as well
```
package lineage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class l2protector {
public static void main(String[] args) throws IOException {
boolean runserver = true;
ServerSocket serverSocket = new ServerSocket(1040, 10);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
do
{
try {
serverSocket = new ServerSocket(1040, 10);
socket = serverSocket.accept();
is = socket.getInputStream();
os = socket.getOutputStream();
// Receiving
byte[] lenBytes = new byte[4];
is.read(lenBytes, 0, 4);
int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
byte[] receivedBytes = new byte[len];
is.read(receivedBytes, 0, len);
String received = new String(receivedBytes, 0, len);
if(received != null) {
System.out.println("Server received: " + received);
}
// Sending
String toSend = "Echo: " + received;
byte[] toSendBytes = toSend.getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff);
toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff);
toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff);
os.write(toSendLenBytes);
os.write(toSendBytes);
socket.close();
}
catch(Exception e) {
serverSocket.close();
}
}
while(runserver);
serverSocket.close();
}
}
```
Ant Script:
```
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project name="AntiCheat" default="dist" basedir=".">
<description>
simplest example build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src" />
<property name="build" location="build" />
<property name="dist" location="dist" />
<property name="version" value="1.0" />
<target name="init">
<!-- Create the time stamp -->
<tstamp />
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}" />
</target>
<target name="compile" depends="init" description="compile the source">
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}" />
</target>
<target name="dist" depends="compile" description="generate the distribution">
<buildnumber />
<!-- Create the distribution directory -->
<mkdir dir="${dist}/lib" />
<!-- Put everything in ${build} into the MyApplication-${version}.${build.number}.jar -->
<jar destfile="${dist}/lib/MyApplication-${version}.${build.number}.jar" basedir="${build}" />
</target>
<target name="clean" description="clean up">
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}" />
<delete dir="${dist}" />
</target>
</project>
``` |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | Those are actually very different constructs.
This form is the only way to actually allocate memory for data:
```
string MyData;
```
This is called a "field".
This form is called an "automatically implemented property":
```
string MyData { get; set; }
```
The compiler translates this onto something like this:
```
string myDataField;
string MyData
{
get { return myDataField; }
set { myDataField = value; }
}
```
So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility. | The first one is a field, not a property. Have a look at this question:
[What is the difference between a Field and a Property in C#?](https://stackoverflow.com/q/295104/50079) |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | If the "latter made it work", you are probably using data-binding; data-binding *usually* works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.
Note that changing from a field to a property can break serialization if you are using `BinaryFormatter` (which IMO is deeply flawed anyway), but properties are **very much** preferred over fields. Absolutely make this change ;p | Those are actually very different constructs.
This form is the only way to actually allocate memory for data:
```
string MyData;
```
This is called a "field".
This form is called an "automatically implemented property":
```
string MyData { get; set; }
```
The compiler translates this onto something like this:
```
string myDataField;
string MyData
{
get { return myDataField; }
set { myDataField = value; }
}
```
So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility. |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | The first is a public field, the second an automatically implemented public property.
They are not the same. With the auto implemented property the compiler will generate a private backing field.
Though both can work as a way to expose data from your class, you should be using properties following the principle of information hiding - fields should be private and only accessed through properties. This allows you to make changes to the implementation without breaking the callers. | Those are actually very different constructs.
This form is the only way to actually allocate memory for data:
```
string MyData;
```
This is called a "field".
This form is called an "automatically implemented property":
```
string MyData { get; set; }
```
The compiler translates this onto something like this:
```
string myDataField;
string MyData
{
get { return myDataField; }
set { myDataField = value; }
}
```
So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility. |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | Those are actually very different constructs.
This form is the only way to actually allocate memory for data:
```
string MyData;
```
This is called a "field".
This form is called an "automatically implemented property":
```
string MyData { get; set; }
```
The compiler translates this onto something like this:
```
string myDataField;
string MyData
{
get { return myDataField; }
set { myDataField = value; }
}
```
So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility. | **Needed for Data Annotations**
For ASP.NET 3.1, use automatically implemented public property for models that use Data Annotations like `[Required]`.
I learned the hard way that a public field won't work. `ModelState.IsValid` will always return `true`. |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | The first one is a field, not a property. Have a look at this question:
[What is the difference between a Field and a Property in C#?](https://stackoverflow.com/q/295104/50079) | Please check this...
[What's the difference between encapsulating a private member as a property and defining a property without a private member?](https://stackoverflow.com/questions/4267144/whats-the-difference-between-encapsulating-a-private-member-as-a-property-and-de)
it might help... |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | If the "latter made it work", you are probably using data-binding; data-binding *usually* works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.
Note that changing from a field to a property can break serialization if you are using `BinaryFormatter` (which IMO is deeply flawed anyway), but properties are **very much** preferred over fields. Absolutely make this change ;p | The first one is a field, not a property. Have a look at this question:
[What is the difference between a Field and a Property in C#?](https://stackoverflow.com/q/295104/50079) |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | The first is a public field, the second an automatically implemented public property.
They are not the same. With the auto implemented property the compiler will generate a private backing field.
Though both can work as a way to expose data from your class, you should be using properties following the principle of information hiding - fields should be private and only accessed through properties. This allows you to make changes to the implementation without breaking the callers. | If the "latter made it work", you are probably using data-binding; data-binding *usually* works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.
Note that changing from a field to a property can break serialization if you are using `BinaryFormatter` (which IMO is deeply flawed anyway), but properties are **very much** preferred over fields. Absolutely make this change ;p |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | Those are actually very different constructs.
This form is the only way to actually allocate memory for data:
```
string MyData;
```
This is called a "field".
This form is called an "automatically implemented property":
```
string MyData { get; set; }
```
The compiler translates this onto something like this:
```
string myDataField;
string MyData
{
get { return myDataField; }
set { myDataField = value; }
}
```
So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility. | Please check this...
[What's the difference between encapsulating a private member as a property and defining a property without a private member?](https://stackoverflow.com/questions/4267144/whats-the-difference-between-encapsulating-a-private-member-as-a-property-and-de)
it might help... |