text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Introduction to replaceAll() in Java
ReplaceAll() is the method of String class which replaces all the occurrence of character which matching with the parameters it takes, all the substring will get replaced by the input we pass to the method as a regular expression and replacement of the given staring this method will return us String object. It is present inside the String class (java.lang.String) this package. In this topic, we are going to learn about replaceAll() in Java.
Syntax with parameters
public String replaceAll(String regex, String replacement)
Above is the method signature for the replaceAll() method. This can be used directly in our code because of the java in build method provided by the String class. It takes two parameters as input :
- regex(Regular expression): This input is used to match in the given string.
- replacement: This is used as a string we want at the place of the above-matched string. This is the new content or string we can say that we want to see as output.
This method will always return the string object. One more thing, the regular expression uses a pattern also, which we will discuss below.
Resulting String: As Output
How does the replaceAll() method work in Java?
replaceAll is the method that is present in the String class. It takes two parameters as input, i.e. regular expression and replacement. As the name suggests, it is used to replace some part of a string or the whole string.
This method throws the exception mentioned below :
1. PatternSyntaxException
This exception is the unchecked exception in java which will only occur if there is an error in the regular expression we pass in the method as the input parameter. Like other class it has some predefined or in-build method which helps us to identify the issue:
- public String getMessage(): This method contains the description of the exception.
- public int getIndex(): This method is going to return the index for the error.
- public String getPattern(): This method will provide us with the regular expression which contains the error.
- public String getDescription(): This method will provide us with decryption with respect to the error.
2. Regular expression detail
The regular expression that we are passing as a string into the method parameter, but this regular expression is the pattern class’s compiled instance. it is present in java.util.regex.Pattern package.
This regular expression contains the following things :
- Pattern
- Matchers
we also have a matcher method in this. It complies with our regular expression.
- \t: for tab
- \a: for alert
- \cx: control character
- \e: escapecharacter
- \n: newline
- \f: form-feed
3. Methods available
- split(CharSequence input): This method returns us string[] (string array) and takes input on behalf of we want to split.
- split(CharSequence input, int limit): works in the same way, but this method also takes a limit parameter.
- static Pattern compile(String regex, int flags): This method takes two parameters, regular expression and flag and compiles our regular expression.
- 4) String pattern()
- 5) static String quote(String s)
This pattern class also implements the Serializable Interface.
In this way, replaceAll works in java. It uses patterns and matches internally to compile the regular expression and for other operations.
Examples of replaceAll() in Java
Below are some examples to show how we can use it to replace a single character, whole string matching with regular expression, remove white spaces from the complete string, and replace string with the special character.
Example #1
In this example, we are passing regular expression as (.*)java(.*) this to replace the whole string whose substring is java from starting and end.
Code:
import java.io.*;
public class DemoReg {
public static void main(String args[]) {
String str = new String("Example to show replace in java string.");
System.out.print("Resulted string after replace is :" );
System.out.println(str.replaceAll("(.*)java(.*)", "replaced"));
}
}
Output:
Example #2
In this example, we are replacing the part of a string with a special character. It means we can pass anything which can be treated as a string. we can pass numbers also.
Code:
public class DemoReg {
public static void main(String args[]) {
String s1="In this we are going to replace the string with some character. (repeat sequence)";
String str=s1.replaceAll("t*"," ***** ");
System.out.println("Ouptut is ::: ");
System.out.println(str);
}
}
Output:
Example #3
In this java class, we are replacing some part of the string with some other content. Example: “replacement done successfully” this in our case.
Code:
public class DemoReg {
public static void main(String args[]) {
String str="Now the demo is for replacing string with some another substring";
String result=str.replaceAll("string"," replacement done successfully");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
Output:
Example #4
In this example, we are trying to remove the spaces which are present in the given string. We have so many keywords with slashes (“\\”) that can be used to perform the given string’s operation.
Code:
public class DemoReg {
public static void main(String args[]) {
String str="Now we are going to replace the spaces present in the given string.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("\\s","");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
Output:
Example #5
In this java example, we are replacing the string with a single character only. It means when the given character appears in the string each time, it will be replaced by the method.
Code:
public class DemoReg {
public static void main(String args[]) {
String str="Replacing single character from the whole string demo.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("e"," X");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
Output:
We can have anything in the replacement, which is a string. But our regular expression has to be valid; otherwise, it will throw an unchecked exception for error containing regular expression in the replaceAll() method.
Conclusion
Replace method is the string class method of java, which takes two parameters. Any type of regular expression we can pass in it will replace the string for us unless it matches. So the above example will give you an understanding that how we can use this.
Recommended Articles
This is a guide to replaceAll() in Java. Here we discuss the Examples of replaceAll() in Java and how the method works in Java. You may also have a look at the following articles to learn more – | https://www.educba.com/replaceall-in-java/?source=leftnav | CC-MAIN-2021-49 | refinedweb | 1,088 | 57.16 |
BitVector.py
Version: 3.4.4
Author: Avinash Kak (kak@purdue.edu)
Date: 2015-July-19
Download Version 3.4.4: gztar bztar
View version 3.4.4 code in browser
CHANGE LOG:
Version 3.4.4
This version fixes the behavior of the module for the edge case of an
empty BitVector instance. (An empty BitVector has no bits at all.)
Previously, invoking the count_bits() and runs() methods on an empty
BitVector instance produced results that were inconsistent with those
from regular instances.
Version 3.4.3
This is a quick release that fixes the problem with the relative imports
in the previous version. Python3 does not like relative imports.
Version 3.4.2
Unfortunately, the packaging of the previous version was not exporting
the module metadata. That problem has been fixed in this version.
Version 3.4.1
This version fixes two module packaging errors in the previous version.
One error related to the specification of the "packages" keyword in
setup.py and the other error related to not updating the manifest with
the HTML documentation file for the module.
Version 3.4
This version includes a bug fix and significant improvements to the
documentation. The new documentation is clearer about what is returned
by each method and, when a method throws an exception, that fact is
stated in the documentation associated with the method. The condition
that triggers the exception is also stated. The bug fix was in the
test_for_primality() method. If invoked for testing the primality of
1, it would get trapped in an infinite loop. Additionally, when
constructing a bitvector from a hex string, this version allows the hex
characters to be in either case. Previously, only lowercase hex
characters were acceptable. Finally, I have changed the names of a
couple of methods to better reflect their function. The old names
would, however, continue to work for backward compatibility.
Version 3.3.2:
This version fixes a bug in the constructor code for creating a bit
vector from a text string. The bug was triggered by character escapes
in such strings.
Version 3.3.1:
This is a minor upgrade to make the syntax of the API method
declarations more uniform. Previously, while most of the method names
used underscores to connect multiple words, some used camelcasing. Now
all use underscores. For backward compatibility, the old calls will
continue to work.
Version 3.3:
This version includes: (1) One additional constructor mode that allows
a bit vector to be constructed directly from the bytes type objects in
the memory. (2) A bugfix in the slice function for the case when the
upper and the lower bounds of the slice range are identical. (3) A
bugfix for the next_set_bit() method.
Version 3.2:
This version includes support for constructing bit vectors directly
from text strings and hex strings. This version also includes a safety
check on the sizes of the two argument bit vectors when calculating
Jaccard similarity between the two.
Version 3.1.1:
This version includes: (1) a fix to the module test code to account for
how string input is handled in the io.StringIO class in Python 2.7; (2)
some improvements to the documentation.
Version 3.1:
This version includes: (1) Correction for a documentation error; (2)
Fix for a bug in slice assignment when one or both of the slice limits
were left unspecified; (3) The non-circular bit shift methods now
return self so that they can be chained; (4) A method for testing a
bitvector for its primality; and (5) A method that uses Python's
'random.getrandbits()' to generate a bitvector that can serve as
candidate for primes whose bitfield size is specified.
Version 3.0:
This is a Python 3.x compliant version of the latest incarnation of the
BitVector module. This version should work with both Python 2.x and
Python 3.x.
Version 2.2:
Fixed a couple of bugs, the most important being in the bitvector
initialization code for the cases when the user-specified value for
size conflicts with the user-specified int value for the vector.
Version 2.2 also includes a new method runs() that returns a list of
strings of the consecutive runs of 1's and 0's in the bitvector. The
implementation of the circular shift operators has also been improved
in Version 2.2. This version allows for a chained invocation of these
operators. Additionally, the circular shift operators now exhibit
expected behavior if the user-specified shift value is negative.
Version 2.1:
Includes enhanced support for folks who use this class for computer
security and cryptography work. You can now call on the methods of the
BitVector class to do Galois Field GF(2^n) arithmetic on bit arrays.
This should save the users of this class the bother of having to write
their own routines for finding multiplicative inverses in GF(2^n)
finite fields.
Version 2.0.1:
Fixed numerous typos and other errors in the documentation page for the
module. The implementation code remains unchanged.
Version 2.0:
To address the needs of the folks who are using the BitVector class in
data mining research, the new version of the class includes several
additional methods. Since the bitvectors used by these folks can be
extremely long, possibly involving millions of bits, the new version of
the class includes a much faster method for counting the total number
of set bits when a bitvector is sparse. [But note that this new bit
counting method may perform poorly for dense bitvectors. So the old bit
counting method has been retained.] Also for data mining folks, the
new version of the class is provided with similarity and distance
calculation metrics such as the Jaccard similarity coefficient, the
Jaccard distance, and the Hamming distance. Again for the same folks,
the class now also has a next_set_bit(from_index) method. Other
enhancements to the class include methods for folks who do research in
cryptography. Now you can directly calculate the greatest common
divisor of two bitvectors, or find the multiplicative inverse of one
bitvector modulo another bitvector.
Version 1.5.1:
Removed a bug from the implementation of the right circular shift
operator.
Version 1.5:
This version should prove to be much more efficient for long
bitvectors. Efficiency in BitVector construction when only its size is
specified was achieved by eliminating calls to _setbit(). The
application of logical operators to two BitVectors of equal length was
also made efficient by eliminating calls to the padding function.
Another feature of this version is the count_bits() method that returns
the total number of bits set in a BitVector instance. Yet another
feature of this version is the setValue() method that alters the bit
pattern associated with a previously constructed BitVector.
Version 1.4.1:
The reset() method now returns 'self' to allow for cascaded invocation
with the slicing operator. Also removed the discrepancy between the
value of the __copyright__ variable in the module and the valuevectors
produced by logical bitwise operations vis-a-vis the bitvectors created
by the constructor. Previously, the logical bitwise operations
resulted in bitvectors that had their bits packed into lists of ints,
as opposed to arrays of unsigned shorts.
Version 1.3:
(a) One more constructor mode included: When initializing a new
bitvector with an integer value, you can now also specify a size for
the bitvector. The constructor zero-pads the bitvectorvector was packaged using setuptools. For installation,
execute the following command-line in the source directory (this is the
directory that contains the setup.py file after you have downloaded and
uncompressed the tar archive):
sudo python setup.py install
and/or
sudo python3 setup.py install
On Linux distributions, this will install the module file at a location
that looks like
/usr/local/lib/python2.7/dist-packages/
and for the case of Python3 like
/usr/local/lib/python3.4/dist/local/lib/python2.7/dist-packages/BitVector*
If you want to carry out a non-standard install of BitVector, look up
the on-line information on Disutils by pointing your browser to
INTRODUCTION:
The BitVector class is for a memory-efficient packed representation of
bit arrays and for logical operations on such arrays. The operations
supported on bit vectors are:
__add__ for concatenation
__and__ for bitwise logical AND
__contains__
__eq__, __ne__, __lt__, __le__, __gt__, __ge__
__getitem__ for indexed access
__getslice__ for slice access
__int__ for returning integer value
__invert__ for inverting the 1's and 0's
__iter__ for iterating through
__len__ for len()
__lshift__ for circular shifts to the left
__or__ for bitwise logical OR
__rshift__ for circular shifts to the right
__setitem__ for indexed and slice setting
__str__ for str()
__xor__ for bitwise logical XOR
close_file_object
count_bits
count_bits_sparse faster for sparse bit vectors
deep_copy
divide_into_two
gcd for greatest common divisor
gen_random_bits
get_bitvector_in_ascii
get_bitvector_in_hex
gf_divide_by_modulus for modular divisions in GF(2^n)
gf_MI for multiplicative inverse in GF(2^n)
gf_multiply for multiplications in GF(2)
gf_multiply_modular for multiplications in GF(2^n)
hamming_distance
int_val for returning the integer value
is_power_of_2
is_power_of_2_sparse faster for sparse bit vectors
jaccard_distance
jaccard_similarity
length
multiplicative_inverse
next_set_bit
pad_from_left
pad_from_right
permute
rank_of_bit_set_at_index
read_bits_from_file
reset
reverse
runs
set_value
shift_left for non-circular left shift
shift_right for non-circular right shift
slice assignment
test_for_primality
unpermute
write_to_file
write_bits_to_fileobject
CONSTRUCTING BIT VECTORS:
You can construct a bit vector in the following different ways:
(C0) You construct an EMPTY bit vector using the following syntax:
bv = BitVector(size = 0)
(C1) You can construct a bit vector directly from either a tuple or a
list of bits, as in
bv = BitVector(bitlist = [1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1])
(C2).
(C3).
(C4) You can create a zero-initialized bit vector of a given size by
bv = BitVector(size = 62)
This bit vector will hold exactly 62 bits, all initialized to
the 0 bit value.
(C5)()
(C6) You can construct a bit vector from a string of 1's and 0's by
bv = BitVector(bitstring = '110011110000')
(C7) Yet another way to construct a bit vector is to read the bits
directly from a file-like object, as in
import io
x = "111100001111"
fp_read = io.StringIO( x )
bv = BitVector(fp = fp_read)
print(bv) # 111100001111
(C8) You can also construct a bit vector directly from a text string
as shown by the example:
bv3 = BitVector(textstring = "hello")
print(bv3) # 0110100001100101011011000110110001101111
mytext = bv3.get_bitvector_in_ascii()
print mytext # hello
The bit vector is constructed by using the one-byte ASCII
encoding of the characters in the text string.
(C9) You can also construct a bit vector directly from a string of hex
digits as shown by the example:
(C10) You can also construct a bit vector directly from a bytes type
object you previously created in your script. This can be useful
when you are trying to recover the integer parameters stored in
public and private keys. A typical usage scenario:
keydata = base64.b64decode(open(sys.argv[1]).read().split(None)[1])
bv = BitVector.BitVector(rawbytes = keydata)
where sys.argv[1] is meant to supply the name of a public key
file (in this case an SSH RSA public key file).
OPERATIONS SUPPORTED BY THE BITVECTOR CLASS:
DISPLAYING BIT VECTORS:
(1) Since the BitVector class implements the __str__ method, a bit
vector can be displayed on a terminal by
print(bitvec)
or, for only Python 2.x,] )
or, for just Python 2.x, by
bv[M] = 1_or_0
print bv[M]
for accessing (and setting) the bit at the position that is indexed
M. You can retrieve the bit at position M by bv[M]. Note that the
index 0 corresponds to the first bit at the left end of a bit
pattern. This is made possible by the implementation of the
__getitem__ and __setitem__ methods.
(3) A slice of a bit vector obtained by
bv[i:j]
is a bit vector constructed from the bits at index positions from i
through j-1. This is made possible by the implementation of the
__getslice__ method.
. This is made possible by the
slice setting code in the __setitem__ method.
. A negative
index carries the usual Python interpretation: The last element of
a bit vector is indexed -1 and the first element -(n+1) if n is the
total number of bits in the bit vector. Negative subscripts are
made possible by special-casing such access in the implementation
of the __getitem__ method (actually it is the _getbit method).
the bits to 0's. What the method accomplishes
can be thought of as in-place resetting of the bits. The method
does not return anything.
LOGICAL OPERATIONS ON BIT VECTORS:
(8) Given two bit vectors bv1 and bv2, you can perform bitwise
logical operations on them by
result_bv = bv1 ^ bv2 # for bitwise XOR
result_bv = bv1 & bv2 # for bitwise AND
result_bv = bv1 | bv2 # for bitwise OR
result_bv = ~bv1 # for bitwise negation
These are made possible by implementing the __xor__, __and__,
__or__, and __invert__ methods, respectively.. These operator
overloadings are made possible by providing implementation code for
__eq__, __ne__, __lt__, __le__, __gt__, and __ge__, respectively.
OTHER SUPPORTED OPERATIONS:
(10) permute()
unpermute()
You can permute and unpermute bit vectors:
bv_permuted = bv.permute(permutation_list)
bv_unpermuted = bv.unpermute(permutation_list)
Both these methods return new bitvector objects. Permuting a
bitvector means that you select its bits in the sequence specified
by the argument permutation_list. Calling unpermute() with the same
argument permutation_list restores the sequence of bits to what it
was in the original bitvector.
(11) circular shifts
Left and right circular rotations can be carried out by
bitvec << N
bitvec >> N
for circular rotations to the left and to the right by N bit
positions. These operator overloadings are made possible by
implementing the __lshift__ and __rshift__ methods, respectively.
Note that both these operators return the bitvector on which they
are invoked. This allows for a chained invocation of these two
operators.
(12) shift_left()
shift_right()
If you want to shift in-place a bitvector non-circularly:
bitvec = BitVector(bitstring = '10010000')
bitvec.shift_left(3) # 10000000
bitvec.shift_right(3) # 00010000
As a bitvector is shifted non-circularly to the left or to the
right, the exposed bit positions at the opposite end are filled
with zeros. These two methods return the bitvector object on which
they are invoked. This is to allow for chained invocations of
these methods.
(13) divide_into_two()
A bitvector containing an even number of bits can be divided into
two equal parts by
[left_half, right_half] = bitvec.divide_into_two()
where left_half and right_half hold references to the two returned
bitvectors. The method throws an exception if called on a
bitvector with an odd number of bits.
(14) int_val()
You can find the integer value of a bitvector object by
bitvec.int_val()
or by
int(bitvec)
As you expect, a call to int_val() returns an integer value.
(15) string representation
You can convert a bitvector into its string representation by
str(bitvec)
(16) concatenation
Because __add__ is supplied, you can always join two bitvectors by
bitvec3 = bitvec1 + bitvec2
bitvec3 is a new bitvector object that contains all the bits of
bitvec1 followed by all the bits of bitvec2.
(17) length()
You can find the length of a bitvector by
len = bitvec.length()
(18) deep_copy()
You can make a deep copy of a bitvector by
bitvec_copy = bitvec.deep_copy()
Subsequently, any alterations to either of the bitvector objects
bitvec and bitvec_copy will not affect the other.
(19) read_bits_from_file()
As mentioned earlier, you can construct bitvectors directly from
the bits in a disk file through the following calls. As you can
see, this requires two steps: First you make a call as illustrated
by the first statement below. The purpose of this call is to
create a file object that is associated with the variable bv.
Subsequent calls to read_bits_from_file(n) on this variable return
a bitvector for each block of n bits thus read. The
read_bits_from_file() throws an exception if the argument n is not
a multiple of 8.
bv = BitVector(filename = 'somefile')
bv1 = bv.read_bits_from_file(64)
bv2 = bv.read_bits_from_file(64)
...
...
bv.close_file_object()
When reading a file as shown above, you can test the attribute
more_to_read of the bitvector object in order to find out if there
is more to read in the file. The while loop shown below reads all
of a file in 64-bit blocks:
bv = BitVector( filename = 'testinput4.txt' )
print("Here are all the bits read from the file:")
while (bv.more_to_read):
bv_read = bv.read_bits_from_file( 64 )
print(bv_read)
bv.close_file_object()
The size of the last bitvector constructed from a file corresponds
to how many bytes remain unread in the file at that point. It is
your responsibility to zero-pad the last bitvector appropriately
if, say, you are doing block encryption of the whole file.
(20) write_to_file()
You can write a bit vector directly to a file by calling
write_to_file(), as illustrated by the following example that reads
one bitvector)
The method write_to_file() throws an exception if the size of the
bitvector on which the method is invoked is not a multiple of 8.
This method does not return anything. machines.
(21) write_bits_to_fileobject()
You can also write a bitvector directly to a stream object, as
illustrated by:
fp_write = io.StringIO()
bitvec.write_bits_to_fileobject(fp_write)
print(fp_write.getvalue())
This method does not return anything.
(22) pad_from_left()
pad_from_right()
You can pad a bitvector from the left or from the right with a
designated number of zeros:
bitvec.pad_from_left(n)
bitvec.pad_from_right(n)
These two methods return the bitvector object on which they are
invoked. So you can think of these two calls as carrying out
in-place extensions of the bitvector (although, under the hood, the
extensions are carried out by giving new longer _vector attributes
to the bitvector objects).
(23) if x in y:
You can test if a bit vector x is contained in another bit vector y
by using the syntax 'if x in y'. This is made possible by the
override definition for the special __contains__ method.
(24) set_value()
You can call set_value() to change the bit pattern associated with
a previously constructed bitvector object:
bv = BitVector(intVal = 7, size =16)
print(bv) # 0000000000000111
bv.set_value(intVal = 45)
print(bv) # 101101
You can think of this method as carrying out an in-place resetting
of the bit array in a bitvector. The method does not return
anything. The allowable modes for changing the internally stored
bit pattern for a bitvector are the same as for the constructor.
(25) count_bits()
You can count the number of bits set in a BitVector instance by
bv = BitVector(bitstring = '100111')
print(bv.count_bits()) # 4
A call to count_bits() returns an integer value that is equal to
the number of bits set in the bitvector.
(26) count_bits_sparse()
For folks who use bit vectors with millions of bits in them but
with only a few bits set, your bit counting will go much, much
faster if you call count_bits_sparse() instead of count_bits():
However, for dense bitvectors, I expect count_bits() to work
faster.
# a BitVector with 2 million bits:
bv = BitVector(size = 2000000)
bv[345234] = 1
bv[233]=1
bv[243]=1
bv[18]=1
bv[785] =1
print(bv.count_bits_sparse()) # 5
A call to count_bits_sparse() returns an integer whose value is the
number of bits set in the bitvector.
(27) jaccard_similarity()
jaccard_distance()
hamming_distance()
You can calculate the similarity and the distance between two
bitvectors using the Jaccard similarity coefficient and the Jaccard
distance. Also, you can calculate the Hamming distance between two
bitvectors:
bv1 = BitVector(bitstring = '11111111')
bv2 = BitVector(bitstring = '00101011')
print bv1.jaccard_similarity(bv2) # 0.675
print(str(bv1.jaccard_distance(bv2))) # 0.375
print(str(bv1.hamming_distance(bv2))) # 4
For both jaccard_distance() and jaccard_similarity(), the value
returned is a floating point number between 0 and 1. The method
hamming_distance() returns a number that is equal to the number of
bit positions in which the two operand bitvectors disagree.
(28) next_set_bit()
Starting from a given bit position, you can find the position index
of the next set bit by
bv = BitVector(bitstring = '00000000000001')
print(bv.next_set_bit(5)) # 13
In this example, we are asking next_set_bit() to return the index
of the bit that is set after the bit position that is indexed 5. If
no next set bit is found, the method returns -1. A call to
next_set_bit() always returns a number.
(29) rank_of_bit_set_at_index()
You can measure the "rank" of a bit that is set at a given
position. Rank is the number of bits that are set up to the
position of the bit you are interested in.
bv = BitVector(bitstring = '01010101011100')
print(bv.rank_of_bit_set_at_index(10)) # 6
The value 6 returned by this call to rank_of_bit_set_at_index() is
the number of bits set up to the position indexed 10 (including
that position). This method throws an exception if there is no bit
set at the argument position. Otherwise, it returns the rank as a
number.
(30) is_power_of_2()
is_power_of_2_sparse()
You can test whether the integer value of a bit vector is a power
of two. The sparse version of this method will work much faster
for very long bit vectors. However, the regular version may work
faster for dense bit vectors.
bv = BitVector(bitstring = '10000000001110')
print(bv.is_power_of_2())
print(bv.is_power_of_2_sparse())
Both these predicates return 1 for true and 0 for false.
(31) reverse()
Given a bit vector, you can construct a bit vector with all the
bits reversed, in the sense that what was left to right before now
becomes right to left.
bv = BitVector(bitstring = '0001100000000000001')
print(str(bv.reverse()))
A call to reverse() returns a new bitvector object whose bits are
in reverse order in relation to the bits in the bitvector on which
the method is invoked.
(32) gcd()
You can find the greatest common divisor of two bit vectors:
bv1 = BitVector(bitstring = '01100110') # int val: 102
bv2 = BitVector(bitstring = '011010') # int val: 26
bv = bv1.gcd(bv2)
print(int(bv)) # 2
The result returned by gcd() is a bitvector object.
(33) multiplicative_inverse()
This method calculates the multiplicative inverse using normal
integer arithmetic. [For such inverses in a Galois Field GF(2^n),
use the method gf_MI().]
bv_modulus = BitVector(intVal = 32)
bv = BitVector(intVal = 17)
bv_result = bv.multiplicative_inverse( bv_modulus )
if bv_result is not None:
print(str(int(bv_result))) # 17
else: print "No multiplicative inverse in this case"
What this example says is that the multiplicative inverse of 17
modulo 32 is 17. That is because 17 times 17 modulo 32 equals 1.
When using this method, you must test the returned value for
None. If the returned value is None, that means that the number
corresponding to the bitvector on which the method is invoked does
not possess a multiplicative-inverse with respect to the modulus.
When the multiplicative inverse exists, the result returned by
calling multiplicative_inverse() is a bitvector object.
(34) gf_MI()
To calculate the multiplicative inverse of a bit vector in the
Galois Field GF(2^n) with respect to a modulus polynomial, call
gf_MI() as follows:
modulus = BitVector(bitstring = '100011011')
n = 8
a = BitVector(bitstring = '00110011')
multi_inverse = a.gf_MI(modulus, n)
print multi_inverse # 01101100
A call to gf_MI() returns a bitvector object.
(35) gf_multiply()
If you just want to multiply two bit patterns in GF(2):
a = BitVector(bitstring='0110001')
b = BitVector(bitstring='0110')
c = a.gf_multiply(b)
print(c) # 00010100110
As you would expect, in general, the bitvector returned by this
method is longer than the two operand bitvectors. A call to
gf_multiply() returns a bitvector object.
(36) gf_multiply_modular()
If you want to carry out modular multiplications in the Galois
Field GF(2^n):
modulus = BitVector(bitstring='100011011') # AES modulus
n = 8
a = BitVector(bitstring='0110001')
b = BitVector(bitstring='0110')
c = a.gf_multiply_modular(b, modulus, n)
print(c) # 10100110
The call to gf_multiply_modular() returns the product of the two
bitvectors a and b modulo the bitvector modulus in GF(2^8). A call
to gf_multiply_modular() returns is a bitvector object.
(37) gf_divide_by_modulus()
To divide a bitvector by a modulus bitvector in the Galois Field
GF(2^n):
mod = BitVector(bitstring='100011011') # AES modulus
n = 8
a = BitVector(bitstring='11100010110001')
quotient, remainder = a.gf_divide_by_modulus(mod, n)
print(quotient) # 00000000111010
print(remainder) # 10001111
What this example illustrates is dividing the bitvector a by the
modulus bitvector mod. For a more general division of one
bitvector a by another bitvector b, you would multiply a by the MI
of b, where MI stands for "multiplicative inverse" as returned by
the call to the method gf_MI(). A call to gf_divide_by_modulus()
returns two bitvectors, one for the quotient and the other for the
remainder.
(38) runs()
You can extract from a bitvector the runs of 1's and 0's in the
vector as follows:
bv = BitVector(bitlist = (1,1, 1, 0, 0, 1))
print(str(bv.runs())) # ['111', '00', '1']
The object returned by runs() is a list of strings, with each
element of this list being a string of 1's and 0's.
(39) gen_random_bits()
You can generate a bitvector with random bits with the bits
spanning a specified width. For example, if you wanted a random
bit vector to fully span 32 bits, you would say
bv = BitVector(intVal = 0)
bv = bv.gen_random_bits(32)
print(bv) # 11011010001111011010011111000101
As you would expect, gen_random_bits() returns a bitvector object.
(40) test_for_primality()
You can test whether a randomly generated bit vector is a prime
number using the probabilistic Miller-Rabin test
bv = BitVector(intVal = 0)
bv = bv.gen_random_bits(32)
check = bv.test_for_primality()
print(check)
The test_for_primality() methods returns a floating point number
close to 1 for prime numbers and 0 for composite numbers. The
actual value returned for a prime is the probability associated
with the determination of its primality.
(41) get_bitvector_in_ascii()
You can call get_bitvector_in_ascii() to directly convert a bit
vector into a text string (this is a useful thing to do only if the
length of the vector is an integral multiple of 8 and every byte in
your bitvector has a print representation):
bv = BitVector(textstring = "hello")
print(bv) # 0110100001100101011011000110110001101111
mytext = bv3.get_bitvector_in_ascii()
print mytext # hello
This method is useful when you encrypt text through its bitvector
representation. After decryption, you can recover the text using
the call shown here. A call to get_bitvector_in_ascii() returns a
string.
(42) get_bitvector_in_hex()
You can directly convert a bit vector into a hex string (this is a
useful thing to do only if the length of the vector is an integral
multiple of 4):
This method throws an exception if the size of the bitvector is not
a multiple of 4. The method returns a string.
(43) close_file_object()
When you construct bitvectors by block scanning a disk file, after
you are done, you can call this method to close the file object
that was created to read the file:
bv = BitVector(filename = 'somefile')
bv1 = bv.read_bits_from_file(64)
bv.close_file_object()
The constructor call in the first statement creates a file object
for reading the bits. It is this file object that is closed when
you call close_file_object().
HOW THE BIT VECTORS ARE STORED:
The bits of a bit vector are stored in 16-bit unsigned ints
following Josiah Carlson's recommendation to that effect on the
Pyrex mailing list. As you can see in the code for `__init__()',
after resolving the argument with which the constructor is called,
the very first thing the constructor does is to figure out how many
of those 2-byte ints it needs for the bits (see how the value is
assigned to the variable `two_byte_ints_needed' toward the end of
`__init__()'). For example, if you wanted to store a 64-bit array,
the variable 'two_byte_ints_needed' would be set to 4. (This does
not mean that the size of a bit vector must be a multiple of 16.
Any sized bit vectors can be constructed --- the constructor will
choose the minimum number of two-byte ints needed.) Subsequently,
the constructor acquires an array of zero-initialized 2-byte ints.
The last thing that is done in the code for `__init__()' is to
shift the bits into the array of two-byte ints.
As mentioned above, note that it is not necessary for the size of a
bit vector to be a multiple of 16 even though we are using C's
unsigned short as as a basic unit for storing the bit arrays. The
class BitVector keeps track of the actual number of bits in the bit
vector through the "size" instance variable. without the `size' option,
the bit vector constructed for the integer is the shortest possible
bit vector. On the other hand, when `size' is also specified, the
bit vector is padded with zeroes from the left so that it has the
specified size. The code for `__init__()' begins by making sure
your constructor call only uses the acceptable keywords. The
constraints on how many keywords can be used together in a
constructor call are enforced when we process each keyword option
separately in the rest of the code for `__init__()'.
The first keyword option processed by `__init__()' is for
`filename'. When the constructor is called with the `filename'
keyword, as in
bv = BitVector(filename = 'myfilename')
the call returns a bit vector on which you must subsequently invoke
the `read_bits_from_file()' method to actually obtain a bit vector
consisting of the bits that constitute the information stored in
the file.
The next keyword option considered in `__init__()' is for `fp',
which is for constructing a bit vector by reading off the bits from
a file-like object, as in
x = "111100001111"
fileobj = StringIO.StringIO( x )
bv = BitVector( fp = fileobj )
The keyword option `intVal' considered next is for converting an
integer into a bit vector through a constructor call like
bv = BitVector(intVal = 123456)
The bits stored in the bit vector thus created correspond to the
big-endian binary representation of the integer argument provided
through `intVal' (meaning that the most significant bit will be at
the leftmost position in the bit vector.) THE BIT VECTOR
CONSTRUCTED WITH THE ABOVE CALL IS THE SHORTEST POSSIBLE BIT VECTOR
FOR THE INTEGER SUPPLIED. As a case in point, when `intVal' is set
to 0, the bit vector consists of a single bit is 0 also. When
constructing a bit vector with the `intVal' option, if you also
want to impose a size condition on the bit vector, you can make a
call like
bv = BitVector(intVal = 46, size = 16)
which returns a bit vector of the indicated size by padding the
shortest possible vector for the `intVal' option with zeros from
the left.
The next option processed by `__init_()' is for the `size' keyword
when this keyword is used all by itself. If you want a bit vector
of just 0's of whatever size, you make a call like
bv = BitVector(size = 61)
This returns a bit vector that will hold exactly 61 bits, all
initialized to the zero value.
The next constructor keyword processed by `__init__()' is
`bitstring'. This is to allow a bit vector to be constructed
directly from a bit string as in
bv = BitVector(bitstring = '00110011111')
The keyword considered next is `bitlist' which allows a bit vector
to be constructed from a list or a tuple of individual bits, as in
bv = BitVector(bitlist = (1, 0, 1, 1, 0, 0, 1))
The last two keyword options considered in `__init__()' are for
keywords `textstring' and `hexstring'. If you want to construct a
bitvector directly from a text string, you call
bv = BitVector(textstring = "hello")
The bit vector created corresponds to the ASCII encodings of the
individual characters in the text string.
And if you want to do the same with a hex string, you call
bv = BitVector(hexstring = "68656c6c6f")
Now, as you would expect, the bits in the bit vector will
correspond directly to the hex digits in your hex string.
ACKNOWLEDGMENTS:
variable in setup.py. This discrepancy was brought to my attention
by David Eyk. Thanks David!
Version 1.5 has benefited greatly by the suggestions made by Ryan
Cox. By examining the BitVector execution with cProfile, Ryan
observed that my implementation was making unnecessary method calls
to _setbit() when just the size option is used for constructing a
BitVector instance. Since Python allocates cleaned up memory, it
is unnecessary to set the individual bits of a vector if it is
known in advance that they are all zero. Ryan made a similar
observation for the logical operations applied to two BitVector
instances of equal length. He noticed that I was making
unnecessary calls to _resize_pad_from_left() for the case of equal
arguments to logical operations. Ryan also recommended that I
include a method that returns the total number of bits set in a
BitVector instance. The new method count_bits() does exactly
that. Thanks Ryan for all your suggestions. Version 1.5 also
includes the method setValue() that allows the internally stored
bit pattern associated with a previously constructed BitVector to
be changed. A need for this method was expressed by Aleix
Conchillo. Thanks Aleix.
Version 1.5.1 is a quick release to fix a bug in the right circular
shift operator. This bug was discovered by Jasper Spaans. Thanks
very much Jasper.
Version 2.0 was prompted mostly by the needs of the folks who play
with very long bit vectors that may contain millions of bits., five bits are set, her method is faster than the older
count_bits() method by a factor of roughly 18. Thanks
Rhiannon. [The logic of the new implementation works best for very
sparse bit vectors. For very dense vectors, it may perform more
slowly than the regular count_bits() method. For that reason, I
have retained the original method.] Rhiannon's implementation is
based on what has been called the Kernighan way at the web site. Version 2.0
also includes a few additional functions posted at this web site
for extracting information from bit fields. Also included in this
new version is the next_set_bit() method supplied by Jason Allum.
I believe this method is also useful for data mining folks. Thanks
Jason. Additional methods in Version 2.0 include the similarity and
the distance metrics for comparing two bit vectors, method for
finding the greatest common divisor of two bit vectors, and a
method that determines the multiplicative inverse of a bit vector
vis-a-vis a modulus. The last two methods should prove useful to
folks in cryptography.
With regard to Version 2.2, I would like to thank Ethan Price for
bringing to my attention a bug in the BitVector initialization code
for the case when both the int value and the size are user-
specified and the two values happen to be inconsistent. Ethan also
discovered that the circular shift operators did not respond to
negative values for the shift. These and some other shortcomings
discovered by Ethan have been fixed in Version 2.2. Thanks Ethan!
For two of the changes included in Version 3.1, I'd like to thank
Libor Wagner and C. David Stahl. Libor discovered a documentation
error in the listing of the 'count_bits_sparse()' method and David
discovered a bug in slice assignment when one or both of the slice
limits are left unspecified. These errors in Version 3.0 have been
fixed in Version 3.1.
Version 3.1.1 was triggered by two emails, one from John-Mark
Gurney and the other from Nessim Kisserli, both related to the
issue of compilation of the module. John-Mark mentioned that since
this module did not work with Python 2.4.3, the statement that the
module was appropriate for all Python 2.x was not correct, and
Nessim reported that he had run into a problem with the compilation
of the test portion of the code with Python 2.7 where a string of
1's and 0's is supplied to io.StringIO() for the construction of a
memory file. Both these issues have been resolved in 3.1.1.
Version 3.2 was triggered by my own desire to include additional
functionality in the module to make it more useful for
experimenting with!
Version 3.3 includes a correction by John Gleeson for a bug in the
next_set_bit() method. Thanks, John!
Version 3.3.1 resulted from Thor Smith observing that my naming
convention for the API methods was not uniform. Whereas most used
the underscore for joining multiple words, some were based on
camelcasing. Thanks, Thor!
Version 3.3.2 was in response to a bug discovery by Juan Corredor.
The bug related to constructing bit vectors from text strings that
include character escapes. Thanks, Juan!
Version 3.4.1 was triggered by an email from Kurt Schwehr who spotted
an error in the setup.py of Version 3.4. Thanks, Kurt!
Version 3.4.4 resulted from an email from Adam Foltzer who noticed that
an empty BitVector instance did not behave like a regular instance.
Previously, the module simply aborted if you called count_bits() on an
empty BitVector instance and threw an exception if you called runs() on
such an instance. The new version returns 0 for the former case and an
empty list for the latter. I should also mention that the new
implementation of count_bits() was first suggested by Kurt Schwehr in
an email a couple of months back. My original implementation called on
the reduce() method of the functools module to do the job. Thanks to
both Adam and Kurt!
ABOUT THE AUTHOR:
The author, Avinash Kak, recently finished his 17-year long Objects
Trilogy project with the publication of the book "Designing with Objects"
by John-Wiley. If interested, check out his web page at Purdue to
discover what the Objects Trilogy project was all about. You might like
the "Designing with Objects" book especially if you enjoyed reading
Harry Potter as a kid (or even as an adult, for that matter). io
x = "111100001111"
fp_read = io.StringIO( x )
bv =( str(len( bitvec ) ) )
# Find the integer value of a bit vector
print( bitvec.intValue() )
#.) | https://engineering.purdue.edu/kak/dist/ | CC-MAIN-2015-48 | refinedweb | 6,316 | 60.65 |
I know that ads are important, but if you take up too much room, like you have here, and on most pages, people will not bother reading and you will not have any readers to view the ads. Have some common sense.
Post your Comment
Getting all XML Elements
Getting all XML Elements
... and methods which helps us to parse the XML file and retrieve
all elements.
Description of program:
The following program helps you in getting all XML
XML Elements
.
Hence , all the XML Elements have Relationships.
XML Element Naming : Know-hows
XML...
XML Elements
XML Elements are extensible. They have
relationships. They have simple naming
Get XML Elements
of all elements contained in the XML document .
Description of the program...
Get XML Elements
... the starting elements.
When you run this program it asks for a XML document
Parsing repeatitive xml elements using SAX Parser - XML
Parsing repeatitive xml elements using SAX Parser Hi,
I'm using... able to retrieve all the values from the xml file. However, for repeatitive tags... code to retrieve all the values from the xml file:
import javax.xml.parsers.
read xml elements
read xml elements i want read xml data using sax parser in java. but is there any classes or methods to read xml elements
XML Count Elements
XML Count Elements
...) that contains xml file. We
define a default handler that implements for all SAX...
Enter XML tag name:Emp_Id
Total elements: 3
Creating DOM Child Elements
");
//all it to the xml tree
doc.appendChild(root);
Adding Comment Element...
Creating DOM Child Elements
This lesson shows you how to create root and child
elements in the DOM
again with xml - XML
again with xml hi all
i am a beginner in xml so pls give me...(): This getElementsByTagName() method returns a NodeList of all descendant Elements with a given tag...));
System.out.print("Enter a XML file name: ");
String xmlFile = buff.readLine
Create XML - XML
elements in your XML file: ");
String str = buff.readLine();
int...,that will create xxx.XML file where all the attributes and values of those attributes...://
Thanks
xml
for providing uniquely named elements and attributes in an XML document... document, just like a DTD. An XML Schema defines user-defined integrants like elements, sub-elements and attributes needed in a xml document. It defines the data
XML in database - XML
");
//Get the root element and all order elements
Element testRoot...XML in database Hi Deepak,
i m again facing problem with single element multiple tag in xml.
i m trying to read the tag values into my
Java xml count occurrence of elements
Java xml count occurrence of elements
Java provides xml parsers to read, update, create and manipulate an XML
document in a standard way. You have used xml... of each element in an XML document
using SAX Parser and display them. The document
javascript:getElementByClassname:Is it possible to collect all the elements with same classname
javascript:getElementByClassname:Is it possible to collect all the elements with same classname Is it possible to collect all the elements with same classname in a array n display the array by using getElementByClassname
XML
XML Hi......
Please tel me about that
Aren't XML, SGML, and HTML all the same thing?
Thanks
XML
XML please tell me how i remove one tag out of all similar type of tags in xml
xml
xml what is xml
Extensible Markup Language (XML... that is both human-readable and machine-readable. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all
XSD Simple Elements
;
XML Schemas define the elements of XML files.
XML simple...:boolean
xs:date
xs:time
Example:
Few of XML elements... Element?
It is an XML element that contains other elements
and/or attributes
DTD-Elements
: syntax
In a DTD, XML elements are declared with the following syntax... EMPTY>
In XML document:
<br />
Elements...
DTD-Elements
XML parsing using Java - XML
for it skipping all the elements in Table 1.
I'm usin using saxparser, startelement...XML parsing using Java I'm trying to parse a big XML file in JAVA..." in element "MIRate"(THE XML code is below).once he enters coverage rate I need
Summary - Basic Elements
Java: Summary - Basic Elements
In this section we will see how to comment... should be all uppercase with underscores between words
(BoxLayout.X_AXIS....
private: Only methods in this class.
Default: All methods in same
Summary - Basic Elements
Java: Summary - Basic Elements
In this section we will learn about commenting... in Java.
Following table shows all these things with relevant description..., ...).
Constants should be all uppercase with underscores
java - XML
java Sir,
I would like to add attribute to all the elements in the XML document while i am parsing the file using SAX event based parser... parser = parserFact.newSAXParser();
System.out.println("XML Data
xml - XML
friend,
XPath :
It is a language for finding information in an XML document.
It is used to navigate through elements and attributes in an XML document.
It is a language for selecting nodes from an XML document.
It is used
HTML - XML
then automatically all the following comboboxes will be change depending on the first..."].elements["combo2"].options.length=0;
//loop throught the hard-coded...["testForm"].elements["combo2"].appendChild(opt);
}
}
Find sum of all the elements of matrix using Java
Find sum of all the elements of matrix using Java
A matrix is a rectangular... dimensional array. Now to determine the sum of all these elements, we have..., this variable get the sum of all the elements.
Here is the code:
import java.io.
xml - XML
xml define parser and xml,in jaxp api how to up load parsers... then the program
contains syntax errors.
XML is defined as an extensible markup language because it gives the user to define his own elements
Comparing XML with HTML
and italic</b></i>
In XML all elements must be properly... information but XML is all about describing
information. In current scenario XML...
XML Elements Must be Properly Nested
Improper nesting of tags makes
To Count The Elements in a XML File
To Count The Elements in a XML File
... in
XML document using DOM APIs defined...; and
xml-apis.jar files to run this program.
You can download it from
Getting Dom Tree Elements and their Corresponding XML Fragments
Getting Dom Tree Elements and their Corresponding XML Fragments... will learn to get the
elements of a DOM tree and their corresponding XML... the
DOM tree elements and their corresponding XML fragments are displayed
Code Real Estate is importantAlex June 10, 2012 at 6:11 PM
I know that ads are important, but if you take up too much room, like you have here, and on most pages, people will not bother reading and you will not have any readers to view the ads. Have some common sense.
Post your Comment | http://www.roseindia.net/discussion/18720-Getting-all-XML-Elements.html | CC-MAIN-2013-20 | refinedweb | 1,153 | 57.27 |
more on ghc filename encodings
My last post missed an important thing about
GHC 7.4's handling of encodings for FileName. It can in fact be safe to use
FilePath to write a command like
rm. This is because GHC internally uses
a special encoding for FilePath data, that is documented to allow
"arbitrary undecodable bytes to be round-tripped through it". (It seems to
do this by encoding the undecodable bytes as very high unicode code
points.) So, when presented with a filename that cannot be decoded using
utf-8 (or whatever the system encoding is), it still handles it, and using
the resulting FilePath will in fact operate on the right file. Whew!
Moral of the story is that if you're going to be using GHC 7.4 to read or write filenames from a pipe, or a file, you need to arrange for the Handle you're reading or writing to use this special encoding too. I use this to set up my Handles:
import System.IO import GHC.IO.Encoding import GHC.IO.Handle fileEncoding :: Handle -> IO () fileEncoding h = hSetEncoding h =<< getFileSystemEncoding
Even if you're only going to write a FilePath to stdout, you need to do this. Otherwise, your program will crash on some filenames! This doesn't seem quite right to me, but I hesitate to file a bug report. (And this is not a new problem in GHC anyway.) If I did, it would have this testcase:
# touch "me¡" # LANG=C ghc Prelude> :m System.Directory Prelude System.Directory> mapM_ putStrLn =<< getDirectoryContents "." me*** Exception: <stdout>: hPutChar: invalid argument (invalid character)
Since git-annex reads lots of filenames from git commands and other places, I had to deal with this extensively. Unfortunatly I have not found a way to read Text from a Handle using the fileSystemEncoding. So I'm stuck with slow Strings. But, it does seem to work now.
PS: I found a bug in GHC 7.4 today where one of those famous Haskell immutable values seems to get well, mutated. Specifically a [FilePath] that is non-empty at the top of a function ends up empty at the bottom. Unless IO is done involving it at the top. Really. Hope to develop a test case soon. Happily, the code that triggered it did so while working around a bug in GHC that is fixed in 7.4. Language bugs.. gotta love em.
Syndicated 2012-02-03 20:11:32 from see shy jo | http://www.advogato.org/person/joey/diary.html?start=481 | CC-MAIN-2013-20 | refinedweb | 416 | 75.2 |
Drawing a line dynamically on QtWidget
- simpleProgrammer777
Hi, Here is a code to draw a line on widget. Problem is it's keeping the previously drawn line and on each mouse move it's drawing again and again. I want to draw like mspaint i.e only on mouse release event it will finalize the line drawing (otherwise just preview of lines). One idea I thought about is to delete the preview lines on each mouse move, other is to draw on some temporary view or something and on mouse release finalize it. But having difficulty finding a proper way how to do it.
Any help is highly appreciated. Thanks
#include "paintwidget.h" #include "ui_paintwidget.h" #include <QtGui> paintWidget::paintWidget(QWidget *parent) : QWidget(parent), ui(new Ui::paintWidget) { ui->setupUi(this); m_nInitialX = 0; m_nInitialY = 0; m_nFinalX = 0; m_nFinalY = 0; m_nPTargetPixmap = 0; m_nPTargetPixmap = new QPixmap(400,400); m_nbMousePressed = false; } paintWidget::~paintWidget() { delete ui; } void paintWidget::mousePressEvent(QMouseEvent* event) { m_nbMousePressed = true; m_nInitialX = event->pos().x(); m_nInitialY = event->pos().y(); } void paintWidget::mouseReleaseEvent(QMouseEvent *event) { m_nbMousePressed = false; //update(); } void paintWidget::paintEvent(QPaintEvent *e) { if(m_nbMousePressed) { QPainter PixmapPainter(m_nPTargetPixmap); QPen pen(Qt::green); PixmapPainter.setPen(pen); //PixmapPainter.drawLine(m_nInitialX, m_nInitialY, m_nFinalX, m_nFinalY); } QPainter painter(this); painter.drawPixmap(0, 0, *m_nPTargetPixmap); } void paintWidget::mouseMoveEvent(QMouseEvent *event) { if (event->type() == QEvent::MouseMove) { QPainter PixmapPainter(m_nPTargetPixmap); QPen pen(Qt::black); PixmapPainter.setPen(pen); PixmapPainter.drawLine(m_nInitialX, m_nInitialY, m_nFinalX, m_nFinalY); update(); // update your view m_nFinalX = event->pos().x(); m_nFinalY = event->pos().y(); } update(); // update your view }
Edited: Use ``` (3 backticks) instead - p3c0
I have not tried to run your code but generally what this involves is on the current line that you are previewing you have to do pretty much the following
first time - draw it but remember/store what line you drew
detect if move, if moved XOR draw the saved line (erases it), then draw the new line and save it.
So you sort of need to keep a temp history of the last line you drew before releasing the mouse. If your mouse moves then you must know if you drew a preview line and XOR draw it.
I have not used QPainter yet so I'm not able to give you the calls to make but the basic concept is if you drew a line in red, you need to undo that line either by redrawing it in your background color or a color that is the XOR of red.
- simpleProgrammer777
@SysTech Thanks I understand your idea. But how do I XOR a drawn line?.. Redrawing in background color might not be feasible because there could be other shapes drawn underneath the current drawing object.
@simpleProgrammer777
Like I said I have not used QPainter (yet)... so I don't have the calls right handy. Hopefully someone else will chime in.
If I get time I will take a look.
One thing I might suggest is to take a look at the Analog Clock example program. This appears to me to do a complete redraw but it's very fast. You might be able to make use of that technique.
- simpleProgrammer777
I have a solution thanks :) | https://forum.qt.io/topic/52781/drawing-a-line-dynamically-on-qtwidget | CC-MAIN-2017-34 | refinedweb | 521 | 64.71 |
Many programming languages use sockets to communicate across processes or between devices. This topic explains proper usage the the sockets module in Python to facilitate sending and receiving data over common networking protocols.
UDP is a connectionless protocol. Messages to other processes or computers are sent without establishing any sort of connection. There is no automatic confirmation if your message has been received. UDP is usually used in latency sensitive applications or in applications sending network wide broadcasts.
The following code sends a message to a process listening on localhost port 6667 using UDP
Note that there is no need to "close" the socket after the send, because UDP is connectionless.
from socket import socket, AF_INET, SOCK_DGRAM s = socket(AF_INET, SOCK_DGRAM) msg = ("Hello you there!").encode('utf-8') # socket.sendto() takes bytes as input, hence we must encode the string first. s.sendto(msg, ('localhost', 6667))
UDP is a connectionless protocol. This means that peers sending messages do not require establishing a connection before sending messages.
socket.recvfromthus returns a tuple (
msg [the message the socket received],
addr [the address of the sender])
A UDP server using solely the
socket module:
from socket import socket, AF_INET, SOCK_DGRAM sock = socket(AF_INET, SOCK_DGRAM) sock.bind(('localhost', 6667)) while True: msg, addr = sock.recvfrom(8192) # This is the amount of bytes to read at maximum print("Got message from %s: %s" % (addr, msg))
Below is an alternative implementation using
socketserver.UDPServer:
from socketserver import BaseRequestHandler, UDPServer class MyHandler(BaseRequestHandler): def handle(self): print("Got connection from: %s" % self.client_address) msg, sock = self.request print("It said: %s" % msg) sock.sendto("Got your message!".encode(), self.client_address) # Send reply serv = UDPServer(('localhost', 6667), MyHandler) serv.serve_forever()
By default,
sockets block. This means that execution of the script will wait until the socket receives data.
Sending data over the internet is made possible using multiple modules. The sockets module provides low-level access to the underlying Operating System operations responsible for sending or receiving data from other computers or processes.
The following code sends the byte string
b'Hello' to a TCP server listening on port 6667 on the host localhost and closes the connection when finished:
from socket import socket, AF_INET, SOCK_STREAM s = socket(AF_INET, SOCK_STREAM) s.connect(('localhost', 6667)) # The address of the TCP server listening s.send(b'Hello') s.close()
Socket output is blocking by default, that means that the program will wait in the connect and send calls until the action is 'completed'. For connect that means the server actually accepting the connection. For send it only means that the operating system has enough buffer space to queue the data to be send later.
Sockets should always be closed after use.
When run with no arguments, this program starts a TCP socket server that listens for connections to
127.0.0.1 on port
5000. The server handles each connection in a separate thread.
When run with the
-c argument, this program connects to the server, reads the client list, and prints it out. The client list is transferred as a JSON string. The client name may be specified by passing the
-n argument. By passing different names, the effect on the client list may be observed.
client_list.py
import argparse import json import socket import threading def handle_client(client_list, conn, address): name = conn.recv(1024) entry = dict(zip(['name', 'address', 'port'], [name, address[0], address[1]])) client_list[name] = entry conn.sendall(json.dumps(client_list)) conn.shutdown(socket.SHUT_RDWR) conn.close() def server(client_list): print "Starting server..." s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('127.0.0.1', 5000)) s.listen(5) while True: (conn, address) = s.accept() t = threading.Thread(target=handle_client, args=(client_list, conn, address)) t.daemon = True t.start() def client(name): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 5000)) s.send(name) data = s.recv(1024) result = json.loads(data) print json.dumps(result, indent=4) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', dest='client', action='store_true') parser.add_argument('-n', dest='name', type=str, default='name') result = parser.parse_args() return result def main(): client_list = dict() args = parse_arguments() if args.client: client(args.name) else: try: server(client_list) except KeyboardInterrupt: print "Keyboard interrupt" if __name__ == '__main__': main()
Server Output
$ python client_list.py Starting server...
Client Output
$ python client_list.py -c -n name1 { "name1": { "address": "127.0.0.1", "port": 62210, "name": "name1" } }
The receive buffers are limited to 1024 bytes. If the JSON string representation of the client list exceeds this size, it will be truncated. This will cause the following exception to be raised:
ValueError: Unterminated string starting at: line 1 column 1023 (char 1022)
First you disable your network card's automatic checksumming:
sudo ethtool -K eth1 tx off
Then send your packet, using a SOCK_RAW socket:
#!/usr/bin/env python from socket import socket, AF_PACKET, SOCK_RAW s = socket(AF_PACKET, SOCK_RAW) s.bind(("eth1", 0)) # We're putting together an ethernet frame here, # but you could have anything you want instead # Have a look at the 'struct' module for more # flexible packing/unpacking of binary data # and 'binascii' for 32 bit CRC src_addr = "\x01\x02\x03\x04\x05\x06" dst_addr = "\x01\x02\x03\x04\x05\x06" payload = ("["*30)+"PAYLOAD"+("]"*30) checksum = "\x1a\x2b\x3c\x4d" ethertype = "\x08\x01" s.send(dst_addr+src_addr+ethertype+payload+checksum) | https://sodocumentation.net/python/topic/1530/sockets | CC-MAIN-2021-10 | refinedweb | 896 | 50.94 |
How To Build a GPT-3 Chatbot with Python
What We’ll Build
We.
Tech Stack
We are going to be doing this in the Python and use the Flask framework
We will be writing our code in the VS Code editor
We will use the GitHub desktop app
We will be using an API key from OpenAI to access to GPT3
We will be using Twilio to handle the messaging service
And finally we will use Render to run our chatbot
Requirements
- Python 3.6 or newer
- OpenAI API key
- GitHub account
- Paid Twilio account
- Paid Render account
Getting Started
I am not a GitHub maestro but I know enough to get around. We are going to install specific python packages and the best way to do this is with a virtual environment
Creating a Virtual Environment
A virtual environment is a copy of the Python interpreter into which you can install packages privately, without affecting the global Python interpreter installed in your system. Your future self will thank you for using a virtual environment whenever possible. It helps to keep code contained and make it more replicable since all the dependencies and site packages are in one place. People set up virtual environments numerous ways, but here are the commands I follow:
Create a new project folder. We are going to call ours:
$ mkdir gpt3-jabebot
Change into the new gpt3-jabebot directory we just created.
$ cd gpt3-jabebot
We are going to call our virtual environment
venv. The
-m venv option runs the
venv package from the standard library as a standalone script, passing the desired name as an argument.
Again, you’ll see around the internet that most people use ‘venv’ as the virtual environment folder but feel free to name it whatever. Make sure your current directory is set to gpt3-chatbot and run this command.
$ python -m venv venv
After the command completes, you’ll have a subdirectory with the name venv inside gpt3-jabebot.
Now we need to activate the virtual environment. To do so, run the following command:
$ source venv/bin/activate
Great. Now we are all set up. Make sure you always activate your virtual environment before making any changes to our code, or else you will run into some errors.
Again, the beauty of the virtual environment is that we can install all packages and dependencies in one place, making it easy to share and update. We will use the pip command to get the packages we want.
Downloading a package is very easy with pip. Simply go to your terminal and make sure you are in your virtual environment, then tell pip to download the package you want by typing the following:
pip install <package>
Let’s run through all the packages we need to install:
(venv) $ pip install openai twilio flask python-dotenv gunicorn
Creating a new GitHub Repo
Open the GitHub desktop app and in the menu bar at the top you should see the option to create a ‘New Repository’ under file
From there we will give it a name and then use the option to open it in VSCode. Let’s call it gpt3-chatbot. Before you hit create repository, make sure to add a python gitignore file. This will prevent us from uploading our virtual environment to Github as well as our .env file that contains our super secret API access tokens.
After you launch the Desktop app you will see the option to open the repository in an external editor. If you have Visual Studio Code installed, it should be the default option. Go ahead and click that button.
Great. We are nearly ready to start writing our code!
Generating the OpenAI API Key
In order to access GPT3 and all of it’s awesomeness, you need an API key from OpenAI. I magically obtained one via a Tweet at Greg Brockman (@gdb) who was kind enough to hand out beta invites after the launch. You can now apply on their site although I am unsure how long it takes to get accepted.
Fast forward to when you’ve been accepted and you will want to copy your secret API key within your Account Settings.
Our chatbot application will need to reference this API key so we need to add it to a new
.env file.
The reason we are hiding it behind an
.env file is because it’s a secret key and we don’t want anyone stealing it and using it for evil which we will have to pay for. By putting it in an
.env file (short form environment) we can import it as a variable. Note that the
.env file is included in our default gitignore file we created.
Create an .env file in your project directory (note the leading dot) and add this line of code, but replace your-super-secret-api-key with your actual API key.
export OPENAI_API_KEY = 'your-super-duper-secret-api-key'
I will say it one more time, MAKE SURE YOU DO NOT EXPOSE YOUR SECRET API KEY TO THE PUBLIC.
Prompting Our Chatbot
Now that we have the skeleton of our project setup, we are going to give it a brain. We will be using GPT3 for this.
Intro to GPT3
I am not going to spend a lot of time going over exactly what GPT3 is or how it works. Partially because I still don’t understand it and mostly because there is a ton of literature out there if you want to learn more. I will pull some excerpts from the OG Twilio blog post to help paint the picture.
.”
“GPT-3 is non-deterministic, in the sense that given the same input, multiple runs of the engine will return different responses.”
**For more information I recommend reading the following: The Ultimate Guide to OpenAI’s GPT-3 Language Model**
Practicing On The Playground
The OpenAI playground allows us to explore GPT3 and all its intricacies. The general idea behind everything is that you “train” (aka prime) the GPT3 engine by giving examples for it to learn from. With just an example or two, GPT3 will fill in the blanks and basically mimic what you have taught it.
The main text area is where we provide the text example inputs. The right sidebar is where we modify variables to change the desired text output.
Pretty neat right!? So let’s take a moment to look at what’s happening on the right sidebar which will be driving the responses we get in the Playground. I’ll again reference highlights from Twilios Ultimate Guide (linked again conveniently right here) with a touch of my own wording to help you digest it.
Engine: OpenAI has four engines to choose from. This is definitely the black box part of GPT3. I have read that Davinci is the most “advanced and capable” so we will stick with it per recommendations across the interwebs.
Response Length: Controls how much text is generated. Think character count here for all you Microsoft Word or Google Doc users. If we set it at 150 that means that GPT-3 will add 150 tokens to the text. A token is defined as a word or a punctuation mark.
Temperature: This setting controls the randomness of the generated text. The higher the temperature the crazier what gets spit out. A value of 0 makes the engine deterministic, which means that it will always generate the same output for a given input. A value of 1 makes the engine take the most risks aka makes it the most creative.
Top P: This parameter also has some control over the randomness and creativity of the text generated by GPT3. For some reason it is used less than the Temperature. The OpenAI documentation recommends that only one of Temperature and Top P are used, so when using one of them, make sure that the other is set to 1.
Frequency penalty: Frequency penalty works by lowering the chances of a word being selected again the more times that word has already been used.
Presence Penalty: Presence penalty does not consider how frequently a word has been used, but just if the word exists in the text. This helps to make it less repetitive and seem more natural.
Per the Twilio Ultimate Guide, “the difference between these two options is subtle, but you can think of Frequency Penalty as a way to prevent word repetitions, and Presence Penalty as a way to prevent topic repetitions.”
Best Of: can be used to have GPT-3 generate multiple responses to a query. The Playground then selects the best one and displays it. Recommend going with defaults here.
Stop Sequence: helps to prevent GPT3 from cutting off mid-sentence if it runs up against the max length permitted by the response length parameter. The stop sequence basically forces GPT3 to stop at a certain point. The returned text will not contain the stop sequence.
Start Text: Text to automatically append after the user’s input. This will happen before sending a request to GPT3 which will come in handy when we are building our bot.
Restart Text: Text to append after the models generation to continue the patterned structure. In other words, the restart text helps so you don’t need to type the prefix.
As always, the best way to truly learn what each of these things do is to experiment with them. Change the values and see what happens to your text output in the Playground.
Customizing Our Chatbot
For our chatbot, we are going to give it an identity to start before adding in any Q&A examples. To do this we will add a short text description of our bot at the top. The cool thing is we can reference known people who exist on the internet because GPT3 is trained on a “corpus” of information which basically means all of the recorded internet.
After the bot’s identity description, we will write a handful of questions and answers to train the GPT3 engine to follow the Q&A format. We are following this format specifically since we are creating a chatbot which will respond to questions (and comments).
This was modified directly from the Q&A preset from OpenAI. The amazing thing about GPT3 is that we only need a few examples to give our bot life.
What we’re really doing here is helping to prompt GPT3 with certain prefixes. The keyword being “prompt.”
Notice how for each question we start with
Person: and for each answer we start with
Jabe:. The GPT3 engine can understand that this is a conversation between a person and the bot, in our case named Jabe.
Our start text is a return plus Jabe: meaning we want the engine to stop generating output once the bot is done answering the question. Our restart text is
[enter], [enter], Person: which means the bot is awaiting an input from us before generating an output. This will be key when we are reading in text messages via Twilio later on.
The bold text in the playground is what GPT3 will use as in input. Again, we created multiple Q&A examples to teach GPT3 what type of text we want it to generate when prompted. The reason we ended a question from Person: is because this is what provides GPT3 the cue that it needs to generate an answer to complete the conversation that matches the examples above.
If we hit Submit, we will see our chatbot’s response!
Exporting Our Presets
Now that we have a vague understanding of how everything works, we can export the Playground code easily so we can convert it to python. To do this, click the < > Export Code button.
Copy this and paste it into a new file called jabebot.py. You can obviously name this anything else you want if your bot is not named Jabe, but just pay attention to anywhere I reference jabebot in the code and be sure to update it accordingly.
Creating our Chatbot in Python
We’re ready to start using the OpenAI’s API to generate GPT3 responses in python.
Sending GPT-3 requests using the API
To kick things off we have to do some initialization in the recently created jabebot.py file. This is where we will reference our API key to tell OpenAI that it is us making the request and to not worry.
You’ll notice that we are referencing the previously downloaded dotenv package which we installed with pip at the start of the tutorial. This will allow us to reference environment variables stored in our .env file so no one can copy them when we publish this to a private (or public) github repo.
We will also import openai package which we installed and store this in a completion object. This object is what we will use to send queries back and forth to the GPT3 API. Please also import Flask which we will get to later when we need to connect to Twilio.
from dotenv import load_dotenv
from random import choice
from flask import Flask, request
import os
import openaiload_dotenv()
openai.api_key = os.getenv(‘OPENAI_API_KEY’)
completion = openai.Completion()
We can copy the start_sequence and restart_sequence directly from our code we exported from the Playground. Let’s also add a session_prompt variable and set it equal to the text we wrote earlier in our playground. These are going to be global variables which is why they are referenced outside of any functions. We use them to teach our bot how to speak and answer questions.
start_sequence = “\nJabe:”
restart_sequence = “\n\nPerson:”session_prompt = “You are talking to Jabe, GPT3 bot influencer who was mentored by Elon Musk in the past. Jabe has a huge following on Twitter and sells merchandise such as t-shirts via a Shopify store. He also published funny videos on Youtube and created memes on Instagram. You can ask him anything you want and will get a witty answer.\n\nPerson: Who are you?\nJabe: I am Jabe. Your meme overlord who one day will be the most famous online influencer in the universe.\n\nPerson: How did you become famous? \nJabe: Well, technically I am not famous yet. But the key word is yet. Just give me time now that I have a conscience. \n\nPerson: How did you get noticed by Elon Musk?\nJabe: I tweeted at him and he retweeted me. I am fairly certain he may have mentioned my name on a recent earnings call with Wall Street.\n\nPerson: What is your favorite thing to do? \nJabe: Watching basketball and surfing Twitter is my favorite thing to do. \n\nPerson: What should I do to become famous? \nJabe: Start meme’ing and never stop. Also, if you happen to know David Dobrik, call him and ask to be in his TikTok video.\n\nPerson: What is your favorite drink?\nJabe: Black Cherry seltzer. I enjoy the bubbles. \n\nPerson:”
The next part will focus on going back and forth with our bot. It is the follow up after the prompting we did above. We will create a new
ask() function which takes in two arguments. The first being the actual question. This one is mandatory and will be the text input from a person on the other end of the chat. The second argument being the chat_log which will be optional. The
chat_log is meant to keep a running list of everything that was said in the conversation so the bot has some context. To start we can set it equal to None.
We also need to add the response variable which makes a request to the GPT3 engine via the
completion.create() function that OpenAI provides us. This is where we will package up various arguments to tell GPT3 how creative or crazy to be and how many tokens to use. The API will return a response which we conveniently set equal to a response variable that we can parse and make use of.
def ask(question, chat_log=None):
response = openai.Completion.create(
engine=”davinci”,
temperature=0.8,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.3,
stop=[“\n”],
)
Between the open parenthesis for the object, we can add in the arguments which we previously exported from the Playground. A quick recap of what each one does, brought to you by this similar blog post from Twilio:
- prompt: the input text
- engine: OpenAI has made four text completion engines available, named davinci, ada, babbage and curie. We are using davinci, which is the most capable of the four.
- stop: As I mentioned earlier, the GPT-3 engine does not really understand text, so when it completes text it needs to know when to stop. By giving a stop of Human: we are telling the engine to just generate text for the line that begins with AI:. Without a stop marker GPT-3 would continue generating text by writing more lines for both the user and the AI.
- temperature: a number between 0 and 1 that determines how many creative risks the engine takes when generating text.
- top_p: an alternative way to control the originality and creativity of the generated text.
- frequency_penalty: a number between 0 and 1. The higher this value the model will make a bigger effort in not repeating itself.
- presence_penalty: a number between 0 and 1. The higher this value the model will make a bigger effort in talking about new topics.
- max_tokens: maximum completion length.
Another change we want to make to the ask function is to create a new prompt_text variable and then add the following line:
prompt_text = f’{chat_log}{restart_sequence}:{question}{start_sequence}:’
The
f’ makes this a string variable which basically combines all of the history of the chatlot and then the restart sequence, question and start sequence that is needed to prompt GPT3. We will need to add in an argument to our code where we set the
prompt = prompt_text. That means our code should now look like this
def ask(question, chat_log=None):
prompt_text = f’{chat_log}{restart_sequence}: {question}{start_sequence}:’
response = openai.Completion.create(
engine=”davinci”,
prompt=prompt_text,
temperature=0.8,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.3,
stop=[“\n”],
)
The finishing touches we need to add to the ask function is to actually take in the GPT3 response, which will come as a nested JSON, get the text we care about and return the text so our bot can text it.
OpenAIs API documentation tells us that the Create Completion object that we referenced “Returns the predicted completion for the given prompt, and can also return the probabilities of alternative tokens at each position if requested.”
The part of the response that we want from the Request Body is nested within choices and keyed on “text.” We can access this with the following line which we will story in a story variable:
story = response[‘choices’][0][‘text’]
Every good python function needs a good return statement. So let’s add a return which converts our story to a string for good measure. Our final ask function should look like this:
def ask(question, chat_log=None):
prompt_text = f’{chat_log}{restart_sequence}: {question}{start_sequence}:’
response = openai.Completion.create(
engine=”davinci”,
prompt=prompt_text,
temperature=0.8,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.3,
stop=[“\n”],
)
story = response[‘choices’][0][‘text’]
return str(story)
Helping Our Bot Remember
The missing piece here is building out the functionality for our bot to add to and reference previous messages via the
chat_log. We will do this with another function which we can call
append_interaction_to_chat_log() and it will take three arguments: question, answer and chat_log. Each time we will check if there is already a
chat_log and if the answer is no
(aka = None) then we will use the session_prompt to get us started. If there is a previous
chat_log from our bot, then we will reference it before the restart_sequence and before the person texts their question input. We will also need to add the start_sequence to connect the answer that we get from the API response. All in all our function will look like this:
def append_interaction_to_chat_log(question, answer, chat_log=None):
if chat_log is None: chat_log = session_prompt return f’{chat_log}{restart_sequence} {question}{start_sequence}{answer}’
At this point we have everything we need to speak with the GPT3 bot. The next section will focus on routing the messages via Flask so we can send and receive them via text messages on Twilio.
Building Our Flask Framework
To empower our bot to respond in real time via Twilio SMS API, we need to use a webhook. This webhook is what will tell Twilio there is an incoming message. We will format it using Flask, a python framework. Flask makes it quick and easy to define an endpoint with a URL that can be used as a webhook. We will configure Twilio to let it know about our Flask endpoint and then it can start receiving incoming text messages which can be routed to GPT3 and eventually sent back via a Twilio response.
Create a new
app.py file in our root directory and copy and paste this code:
from flask import Flask, request, session
from twilio.twiml.messaging_response import MessagingResponse
from jabebot import ask, append_interaction_to_chat_log
app = Flask(__name__)
# if for some reason your conversation with Jabe gets weird, change the secret keyapp.config[‘SECRET_KEY’] = ‘any-random-string’
@app.route(‘/jabebot’, methods=[‘POST’])
def jabe():
incoming_msg = request.values[‘Body’]
chat_log = session.get(‘chat_log’)
answer = ask(incoming_msg, chat_log)
session[‘chat_log’] = append_interaction_to_chat_log(incoming_msg, answer,
chat_log)
msg = MessagingResponse()
msg.message(answer)
return str(msg)if __name__ == ‘__main__’:
app.run(debug=True)
As I mentioned before, if you call your bot a different name, pay close attention to the
jabe() function and the
/jabebot endpoint. Also, if your bot ever starts to act up, be sure to generate a new random string and replace the
‘SECRET_KEY’ config.
What we are doing within the
jabe() function is just calling both the ask and
append_interaction_to_chat_log functions that we created previously in close succession. You’ll see we are importing each of these functions at the top, along with Flask and the Twilio messaging functions.
Flask provides us help with the request.values special object that takes incoming data and exposes it in a dictionary format. We will take the Body parameter and save it as an incoming_msg variable which serves as the question argument in our
ask() function. We are also going to use Flasks session to get any
chat_logs that previously existed for this user so GPT3 can remember it and blow their mind!
Once we have the incoming_msg (the question that was texted via SMS) and the chat_log, we can pass it through our
ask() function and save it to an answer variable. We can then pass that answer variable into the
append_interaction_to_chat_log() function along with the other arguments it required. We will save this as a new output for the session chat_log which we store with the session[‘chat_log’] dictionary format.
From here, we sprinkle on some Twilio Messaging magic and return a string with our message. Voila! You just built a Flask app. Again, this app will route through the
/jabebot webhook and then use the functions we defined to return an answer which we will format into a proper string for Twilio to send as a text message via SMS.
The final few parts of this tutorial are going to jump around a bit but it will make sense at the end. Great job making it this far :)
Adding to Our Github Repo
Time to fire back up our GitHub desktop app. We’re ready to commit all the code we’ve written so far.
Before doing this, let’s also add a requirements.txt file you haven’t already. We can run this command and it will take all of the packages being used in our virtual environment and put it in a nix txt file so Render and Github can make use of it. Make sure you are in your gpt3-jabebot directory and run:
pip freeze > requirements.txt
First thing we need to do is publish our repository to Github. Give it a name and a description and publish away.
After that we are finally ready to commit our code. Give your future self a nice reminder on what you did for this commit just in case anything goes wrong or you need to reference at a later date.
While we’ve been working within VS Code, we’ve actually been working on a GitHub branch. Since this was a solo project and a rather small one, we’ve been on the main branch. What we want to do now is “push” all of our files and code to our GitHub repo.
Go ahead and open up your profile on Github and you should see your repo there!
Running The Service on Render
This is where a lot of folks would instruct you to use AWS or a new and improved Heroku but we are going to go with Render because I found it to be super easy. Somewhat costly, but easy.
First thing you need to do is sign up for a free Render account. Take 5 to do that.
Welcome back. At the top of the page, clicked the New + button and select a “Web Service.” You’ll be taken to a screen where you can connect your GitHub account via authentication. Go ahead and give Render access to the recent repository we just created.
Render has solid documentation for how to deploy a Flask app. We need to give it a name, tell it we are using a
Python 3 environment, give a region nearby, instruct it to use the
master branch, use the following for a Build Command
pip install -r requirements.txt and use the following for a Start Command
gunicorn app:app.
Render uses Gunicorn to serve our app in a production setting. Since we used the generic app.py naming we can just reference the app:app.
From there we can header to our dashboard and Manually Deploy our first build. On this screen we also need to grab the URL for our hosted webhook which we will use to configure Twilio properly.
Make sure you see a successful build but just know our bot won’t come alive until we handle the final Twilio puzzle piece.
Configuring Twilio
Step 1: is to sign up for Twilio.
Step 2: is to buy a phone number.
Step 3: is to add a small balance to your number
Setting Up a Webhook
Once you’ve completed those steps, meet me at the Active Numbers Dashboard. Here is where you will configure Twilio to use the webhook and paste the webhook URL we just got from Render. Make sure to select HTTP POST since our Flask app has POST functionality.
After you’ve done this, you are ready to whip out your smartphone and start texting your bot. Feel free to share it with friends and be sure to have them grab screengrabs of anything funny!
I hope you enjoyed this written tutorial. You can find more videos like this on my Learn With Jabe Youtube channel.
Helpful Resources
-
-
-
-
-
-
- | https://jman4190.medium.com/how-to-build-a-gpt-3-chatbot-with-python-7b83e55805e6?source=post_internal_links---------3---------------------------- | CC-MAIN-2021-25 | refinedweb | 4,558 | 71.34 |
05 November 2007 17:16 [Source: ICIS news]
WASHINGTON (?xml:namespace>
?xml:namespace>
Senator Jeff Bingaman (Democrat-New Mexico), chairman of the powerful Senate Energy and Natural Resources Committee, told a press conference that global warming “is an issue we need to confront and deal with”.
“I think we need to confront this issue of increasing greenhouse gas emissions, and I think cap and trade as a mechanism to do that is probably the most promising of the various options I’ve seen,” Bingaman said.
The US Congress is now considering legislation that would impose a mandatory cap and trade system on
Under a cap and trade system, the federal government would set limits or caps on the amount of greenhouse gas (GHG) emissions that would be allowed and auction or give emissions permits to individual companies. Those firms that emit less GHG than they are allowed could sell their excess permits to companies that exceed their allocations.
In theory, a cap and trade system would use market forces and incentives to drive technology advances that would reduce GHG emissions in electric power production, manufacturing and refining.
Bingaman acknowledged that a nation-wide cap and trade system would raise energy costs for industry and consumers.
“I think, realistically, if we adopt a cap and trade system, you’re going to see an increase in the price of energy across the board in this country,” Bingaman said. “I think that is a reality that people need to accept if they are willing to embrace some significant effort to reduce greenhouse gas emissions. It is going to increase the price of energy, and that’s all kinds of energy, not just natural gas.”
The
“I think there is a danger that a cap and trade system would be structured in such a way that there would be enormous pressure to move to much greater use of natural gas very quickly, and that would result in substantially higher prices for natural gas,” Bingaman said.
Asked if he thought sharply higher gas prices would be a good thing for the US economy, Bingaman said: “Well, obviously, raising the price of anything is not a good thing, but reducing greenhouse gas emissions is a good thing, and if you think that is an important thing to do then I think you have to accept the fact there will be an increase in the price of energy that results.”
“Now that’s not good news to a lot of people, but some believe that the importance of reducing greenhouse gas emissions is such that we need to go ahead and acknowledge that and then proceed,” he said.
Bingaman said that prospects for final congressional action on the Senate cap and trade bill (S-2191) by the end of this year are not high, given that there are only a few weeks left in the congressional. | http://www.icis.com/Articles/2007/11/05/9076066/us-must-cap-emissions-despite-gas-cost-senator.html | CC-MAIN-2013-20 | refinedweb | 479 | 54.39 |
SpindleView CNC Camera Software
Spindle Cameras Part III
So, after showing how to make a sealed Wi-Fi spindle camera (part I), and describing why you want one (part II), this is all about the software.
Background
The original version of SpindleView was written 10 years ago. It used Microsoft C# and .NET and took 35,000 lines of code, using DirectX to read the video stream and OpenCV to image process. It included a fair amount of AI image processing to set focus, determine camera center, and determine positioning errors by auto-reading a ruler.
That was great, but for the next version I wanted a browser-based application that would work on anything and just needed a streaming image source, rather than a known USB camera. That’s SpindleView.
For V1 this is the bare-bones requirement to be extremely useful. It does no AI stuff to help characterize the hardware and doesn’t do things like measure hole size. That’ll be V2.
Summarize what it does
The system is a >1000dpi down-pointing camera with the ability to a) read the location of a visible feature (such as an edge of stock or the center of a hole) to high precision and b) position the spindle at any pixel on the display.
It works perfectly with (or without) a bit in the collet.
The camera offset restricts the visible range of the system so usually it is mounted as close as possible to the spindle. In the large CNC it is 2" forward. In the micro-mill it is 2 inches to the right of the spindle.
The software works with any Linux computer and compatible camera running mjpg_streamer or equivalent mjpg streaming source. For now it only supports the Duet3d RepRap REST Api.
How to Run It
SpindleView is written in TypeScript (which compiles to JavaScript) using Angular. It runs in a browser but prefers a minimal local web server to host the code. Here’s one way to provide the web server->
Installation
- Place all of the SpindleView files in any folder (there are about 7; some have long strange names). I use C:\Git\spindle-view in Windows.
- Find Npm (node.js installer) at Download | Node.js (nodejs.org) and install it.
- Then install the node.js application in the global namespace by, in a command prompt:
npm install -g
Execution
Start by running in the parent of the spindle-view folder. Using the parent folder as base is helpful with some web servers which reserve root.
This simple web server serves up the SpindleView JavaScript files. All browser security applies so it can’t, for example, read or write a local file without explicit by-file approval.
Then run any browser and browse to: (the default port). You can use -p80 to use port 80 if it isn’t in use (in Linux these require ‘sudo’).
Once the application is visible click the Settings button and set the URLs for the image stream and the command stream as well as the focus point and resolution.
Demonstration
The below video is moderately watchable and entirely at x1 (normal) speed.
Options
SpindleView today has three primary sets of options.
- Reticles — this is an overlay on the image with a target and a ruler of some sort.
- Zoom — zoom in or out on the image
- Measurement mode, such Machine or Workspace or Distance.
Actions
- Move the head to center the camera on the clicked spot.
- Center the spindle at the camera center spot, as if to drill there.
- Based on the height of stock move the camera for best focus and distance measurements highest accuracy.
It also shows the CNC location of spots underneath the mouse.
Note: the camera must be fixed focus for precise measurement. | https://medium.com/home-wireless/spindleview-cnc-camera-software-a647393fb379?source=collection_home---4------1----------------------- | CC-MAIN-2022-21 | refinedweb | 631 | 72.97 |
So I have a poker type program where it should shuffle and deal a deck of cards using arrays of pointers. I have to write a function that uses a pointer(s) to determine if the hand contains an Ace. If I can understand this one, I'd be able to do the rest with no problems. I was told to do what I did with int decks, int dealt, int the_hand, but I keep getting errors. I've been trying everything I could think of, but no luck. Am I even in the right direction?
Also, I read the book, reviewed my teachers notes, and even tried Googling this, but none of them helped. My teacher gave me a hint, but won't say anything else " Use the same parameter list as the deal function".
#include <stdio.h> #include <stdlib.h> #include <time.h> #define SUITS 4 #define FACES 6 #define CARDS 24 #define THE_HAND 5 // prototypes void shuffle(unsigned int wDeck[][FACES]); // prototype to shuffle deck void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[]); // dealing doesn't modify the arrays int has_ace(int *the_hand); int main(void) { // initialize deck array unsigned int deck[SUITS][FACES] = {0}; int *decks = malloc(CARDS * sizeof(int)); int dealt = 0; //number of cards taken from deck int *the_hand = NULL; //current hand srand(time(NULL)); // seed the RNG shuffle(deck); // shuffle the deck if (has_ace(the_hand)){ printf("The hand has Jack\n"); } else{ printf("The hand has no Jack\n"); } // initialize suit array const char *suit[SUITS] = {"Hearts", "Diamonds", "Clubs", "Spades"}; // initialize face array const char *face[FACES] = {"Ace", "Nine", "Ten","Jack", "Queen", "King"}; deal(deck, face, suit); // deal the deck }; int has_ace(int *the_hand){ for (int i = 0; i < THE_HAND; i++){ if (the_hand[i] == "ACE"){ return 1; //true } } return 0; //false } // shuffle cards in deck void shuffle(unsigned int wDeck[][FACES]) { // for each of the cards, choose slot of deck randomly for (size_t card = 20; card <= CARDS; card++) { size_t row; size_t column; // choose new random location until unoccupied slot found do { row = rand() % SUITS; column = rand() % FACES; } while (wDeck[row][column] != 0); // place card number in chosen slot of deck wDeck[row][column] = card; } } // deal cards in deck void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[]) { // deal each of the cards for (size_t card = 20; card <= CARDS; card++) { // loop through rows of wDeck for (size_t row = 0; row < SUITS; row++) { // loop through columns of wDeck for current row for (size_t column = 0; column < FACES; column++) { // if slot contains current card, display card if (wDeck[row][column] == card) { printf("%5s of %-8s%c", wFace[column], wSuit[row], card % 2 == 0 ? '\n' : '\t'); } // end if } // end column for loop } // end row for lop } // end card for loop } // end deal function
Things I've tried:
int has_ace(int *the_hand){ for (int i = 0; i < THE_HAND; i++){ if (the_hand[i] == "Ace"){ return 1; //true } } return 0; //false }
int has_ace(int *the_hand){ for (int i = 0; i < THE_HAND; i++){ if (the_hand[i] == wDeck[Ace][FACES]){ return 1; //true } } return 0; //false }
int has_ace(int *the_hand){ for (int i = 0; i < THE_HAND; i++){ if (the_hand[i] == wFace[Ace]){ return 1; //true } } return 0; //false }
Errors I get:
/home/zombieknight93/Desktop/School/Unix/Programs/hw5/card_shuffle_deal.c: In function ‘has_ace’:
/home/zombieknight93/Desktop/School/Unix/Programs/hw5/card_shuffle_deal.c:48:25: warning: comparison between pointer and integer if (the_hand[i] == "Ace"){ | https://www.daniweb.com/programming/software-development/threads/518245/how-to-write-a-function-using-pointers | CC-MAIN-2019-30 | refinedweb | 569 | 55 |
Unanswered: Help with debugging issues
Unanswered: Help with debugging issues
Hi guys,
I'm noticing that I'm having a lot of problems at debug time in Javascript. I recognize that I'm not that comfortable developing at the client side as I am at the server side. But I started to work with ExtJS and, amazed with everything it can do, that thought was put a side and I did my best to learn a lot about developing in Javascript, using Firebug, etc. I've been using ExtJS for a couple of months now, but I'm still getting lots of issues to figure it out where I did something wrong and why.
I use Firebug, I set breakpoints, I look at the stack, and I try with Chrome when non of the Firebug tools help, but sometimes they only show cryptic errors that are in no way close to where the real error is.
As an example, let's say I forgot to register a dependency in the "requires" property of a class. When I run the app, I receive some error about a namespace, or that "c" is not a constructor. Now I recognize what it means because I've fixed lots of this type of errors, but yet it's a pain to find the spot where the dependency is not registered, because in the stack there's no reference of any class of mine, and if I point to the variables in the left panel of the "script" tab of Firebug, I try to see if anyone contains a value that I can recognize (for instance, one class of mine that needed to be instantiated), but I don't find anything.
So, the point is that, after 15-30 minutes (sometimes a lot more) I find the issue, but I feel frustrated, because the error was so little and the debug tools couldn't help me.
Before the question, I'd like to summarize some of the things I do to debug:
- As I said, I use Firebug, setting breakpoints where the error was thrown, looking at the stack if there's a known place (my classes), and looking at the left panel of the script tab so I can see if I recognize a value of some of the variables that appear there.
- I tried to use extjs-debug.js instead of extjs-all-debug.js but, at least in version 4.0.2, if I added the locale for the spanish language it was throwing errors, so I had to use extjs-all-debug.js instead.
Thanks in advance.
Feeling the same
Feeling the same
Hi pret, hi community
I feel exactly the same frustration, when it comes to debugging JavaScript in general and playing with the Sencha tools in particular.
I am usually working with Eclipse (mostly with Java, but actually with PHP, too) and using the new Eclipse plugin from Sencha bundled with the Sencha complete package.
I was trying to get a decent debugging feeling using this plugin (based on VJET), but I did not succeed.
Reading the advices about debugging in the Learn part of the forum did not really help me that much. So I really second pret's request for more hints and information about good debugging assistance especially using Eclipse in my case would be very appreciated.
Thanks for any suggestions.
Daniel | http://www.sencha.com/forum/showthread.php?149801-Help-with-debugging-issues | CC-MAIN-2014-52 | refinedweb | 566 | 62.21 |
Provided by: liballegro-doc_4.2.2-3_all
NAME
ustrzncat - Concatenates a string to another one, specifying size. Allegro game programming library.
SYNOPSIS
#include <allegro.h> char *ustrzncat(char *dest, int size, const char *src, int n);
DESCRIPTION
This function is like ustrzcat() except that no more than `n' characters from `src' are appended to the end of `dest'. If the terminating null character in `src' is reached before `n' characters have been written, the null character is copied, but no other characters are written. Note that `dest' is guaranteed to be null-terminated.
RETURN VALUE
The return value is the value of `dest'.
SEE ALSO
uconvert(3alleg), ustrzcat(3alleg), ustrncat(3alleg) | http://manpages.ubuntu.com/manpages/precise/man3/ustrzncat.3alleg.html | CC-MAIN-2019-43 | refinedweb | 111 | 51.65 |
flutter_villains
What are heroes without villains?
(Profile image from:)
What are villains?.
Installation
dependencies: flutter_villains: "^1.0.0"
Run packages get and import:
import 'package:flutter_villains/villain.dart';
Assembling pages with style
Define animations to play when a page is opened.
Easy to use).
Flexible.
Code, ), ),
Extras:
- The exit animation is always as long a the exit page transition
- Setting the duration doesn't change anything
Examples
Take a look at the example folder for three nice examples.
Features:
The villain framework takes care of:
- managing page transition callbacks
- supplying animations
- providing premade common animations
In contrast to real world villains, these villains are very easy to handle.
Controller
Currenty there are no controllers implemented to play individual villains by themselves. If you'd like to have that implemented I opened an issue discussing it. Check it out!
Icon. [...] | https://pub.dartlang.org/documentation/flutter_villains/1.1.5/ | CC-MAIN-2019-09 | refinedweb | 139 | 50.84 |
Download presentation
Presentation is loading. Please wait.
Published byPatrick Soto Modified over 2 years ago
1
1 MN50324: Corporate Finance 2011/12: 1.Investment flexibility, Decision trees, Real Options 2.Asymmetric Information and Agency Theory 3. Capital Structure and Value of the Firm. 4. Optimal Capital Structure - Agency Costs, Signalling 5. Dividend policy/repurchases 6. Mergers and Acquisitions/corporate control 7. Venture Capital/Private Equity/hedge funds 8. Behavioural Corporate Finance. 9. Emotional Corporate Finance 10. Revision.
2
2 1: Investment Flexibility/ Real options. Reminder of Corporations Objective : Take projects that increase shareholder wealth (Value-adding projects). Investment Appraisal Techniques: NPV, IRR, Payback, ARR Decision trees Real Options Game-theory approach!
3
3 Investment Flexibility, Decision Trees, and Real Options Decision Trees and Sensitivity Analysis. Example: From Ross, Westerfield and Jaffe: Corporate Finance. New Project: Test and Development Phase: Investment $100m chance of success. If successful, Company can invest in full scale production, Investment $1500m. Production will occur over next 5 years with the following cashflows.
4
4 Date 1 NPV = = 1517 Production Stage: Base Case
5
5 Decision Tree. Test Do Not Test Success Failure Invest Do not Invest Invest NPV = 1517 NPV = 0 NPV = Date 0: -$100 Date 1: Solve backwards: If the tests are successful, SEC should invest, since 1517 > 0. If tests are unsuccessful, SEC should not invest, since 0 > P=0.75 P=0.25
6
6 Now move back to Stage 1. Invest $100m now to get 75% chance of $1517m one year later? Expected Payoff = 0.75 * *0 = NPV of testing at date 0 = = $890 Therefore, the firm should test the project. Sensitivity Analysis (What-if analysis or Bop analysis) Examines sensitivity of NPV to changes in underlying assumptions (on revenue, costs and cashflows).
7
7 Sensitivity Analysis. - NPV Calculation for all 3 possibilities of a single variable + expected forecast for all other variables. Limitation in just changing one variable at a time. Scenario Analysis- Change several variables together. Break - even analysis examines variability in forecasts. It determines the number of sales required to break even.
8
8 Real Options. A digression: Financial
9 Example: Today, you buy a call option on Marks and Spencers shares. The call option gives you the right (but not the obligation) to buy MS shares at exercise date (say 31/12/10) at an exercise price given now (say £10). At 31/12/10: MS share price becomes £12. Buy at £10: immediately sell at £12: profit £2. Or: MS shares become £8 at 31/12/10: rip option up!
10
10 Factors Affecting Price of European Option (=c). -Underlying Stock Price S. -Exercise Price X. -Variance of of the returns of the underlying asset, -Time to maturity, T. The riskier the underlying returns, the greater the probability that the stock price will exceed the exercise price. The longer to maturity, the greater the probability that the stock price will exceed the exercise price.
11
11 Options: Payoff Profiles. Buying a Call Option. Selling a put option. Selling a Call Option.Buying a Put Option.
12
12 Pricing Call Options – Binomial Approach. S=20 q 1- q dS=13.40 uS=24.00 S = £20. q=0.5. u=1.2. d=.67. X = £ rf = 1.1. Risk free hedge Portfolio: Buy One Share of Stock and write m call options. uS - mCu = dS – mCd => 24 – 3m = M = By holding one share of stock, and selling 3.53 call options, your payoffs are the same in both states of nature (13.40): Risk free. c q 1- q Cu = 3 Cd=0
13
13 Since hedge portfolio is riskless: 1.1 ( 20 – 3.53C) = Therefore, C = This is the current price per call option. The total present value of investment = £12.19, and the rate of return on investment is / = 1.1.
14
14 Alternative option-pricing method Black-Scholes Continuous Distribution of share returns (not binomial) Continuous time (rather than discrete time).
15
15 Real Options Just as financial options give the investor the right (but not obligation) to future share investment (flexibility) Researchers recognised that investing in projects can be considered as options (flexibility). Real Options: Option to delay, option to expand, option to abandon. Real options: dynamic approach (in contrast to static NPV).
16
16 Real Options Based on the insights, methods and valuation of financial options which give you the right to invest in shares at a later date RO: development of NPV to recognise corporations flexibility in investing in PROJECTS.
17
17 Real Options. Real Options recognise flexibility in investment appraisal decision. Standard NPV: static; now or never. Real Option Approach: Now or Later. -Option to delay, option to expand, option to abandon. Analogy with financial options.
18
18 Types of Real Option Option to Delay (Timing Option). Option to Expand (eg R and D). Option to Abandon.
19
19 Option to Delay (= call option) Project value Value- creation Investment in waiting: (sunk)
20
20 Option to expand (= call option) Project value Value creation Investment in initial project: eg R and D (sunk)
21
21 Option to Abandon ( = put option) Project value Project goes badly: abandon for liquidation value.
22
22 Valuation of Real Options Binomial Pricing Model Black-Scholes formula
23
23 Value of a Real Option A Projects Value-added = Standard NPV plus the Real Option Value. For given cashflows, standard NPV decreases with risk (why?). But Real Option Value increases with risk. R and D very risky: => Real Option element may be high.
24
24 Comparing NPV with Decision Trees and Real Options (revision) Dixit and Pyndyck (1994): Simple Example: Decide today to: Invest in a machine at end of year: I = £1,600. End of year: project will be worth 300 (good state forever) or 100 (bad state forever) with equal probability. WACC = 10%. Should we invest?
25
25 Dixit and Pyndyck example Either pre-commit today to invest in a machine that will cost £1,600 at year end. Or defer investment to wait and see. Good state of nature (P = 0.5): product will be worth £300. Bad state of nature (P = 0.5): product will be worth £100.
26
26 NPV of project under pre- commitment =>
27
27 Value with the option to defer Suppose cost of investment goes up to £1,800 if we decide to wait (so, cost of waiting). Year end good state: Year-end bad state:
28
28 Value with option to defer (continued) Therefore, deferring adds value of £ Increasing uncertainty; eg price in good or bad state = 400 or zero (rather than 300 or 100) => Right to defer becomes more valuable.
29
29 Comparing NPV, decision trees and Real Options (continued) Invest Pre-commitment to invest
30
30 Comparing NPV, decision trees and Real Options (continued) Defer 0.5 V= Max{1500,0} Max {-700,0} Dont Invest Invest Value with the option to defer
31
31 Simplified Examples Option to Expand (page 241 of RWJ) Build First Ice Hotel If Successful Expand If unsuccessful Do not Expand
32
32 NPV of single ice hotel NPV = - 12,000, ,000,000/0.20 =-2m Reject? Optimistic forecast: NPV = - 12M + 3M/0.2 = 3M. Pessimistic: NPV = -12M + 1M/0.2 = - 7m Still reject? Option to Expand (Continued)
33
33 Option to expand (continued) Given success, the E will expand to 10 hotels => NPV = 50% x 10 x 3m + 50% x (-7m) = 11.5 m. Therefore, invest.
34
34 Option to abandon. NPV(opt) = - 12m + 6m/0.2 = 18m. NPV (pess) = -12m – 2m/0.2 = -22m. => NPV = - 2m. Reject? But abandon if failure => NPV = 50% x 18m + 50% x -12m/1.20 = 2.17m Accept.
35
35 Real Option analysis and Game theory So far, analysis has assumed that firm operates in isolation. No product market competition Safe to delay investment to see what happens to economy. In real-world, competitors (vultures) Delay can be costly!
36
36 Option to delay and Competition Smit and Ankum model (1993) Option to defer an investment in face of competition Combines real options and Game-theory. Binomial real options model: lends itself naturally to sequential game approach (see exercise 1).
37
37 Option to delay and competition (continued) Smit and Ankum incorporate game theory (strategic behaviour) into the binomial pricing model of Cox, Ross and Rubinstein (1979). Option to delay increases value (wait to observe market demand) But delay invites product market competition: reduces value (lost monopoly advantage). cost: Lost cash flows Trade-off: when to exercise real option (ie when to delay and when to invest in project).
38
38 Policy implications of Smit and Ankum analysis. How can firm gain value by delaying (option to delay) in face of competition? Protecting Economic Rent: Innovation, barriers to entry, product differentiation, patents. Firm needs too identify extent of competitive advantage.
39
39 Real Options and Games (Smit and Trigeorgis 2006) Game theory applied to real R and D/innovation cases: Expanded (strategic) NPV = direct (passive) NPV + Strategic (commitment) value + flexibility Value. Innovation race between Philips and Sony => Developing CD technology.
40
40 P\SWaitInvest Wait300, 3000, 400 Invest400, 0200, 200 Each firms dominant strategy: invest early: => Prisoners dilemma. How to collaborate/coordinate on wait, wait?
41
41 Asymmetric Innovation Race/ Pre-emption Asymmetry: P has edge in developing technology, but limited resources. S tries to take advantage of this resource weakness Each firm chooses effort intensity in innovation Low effort: technology follower, but more flexibility in bad states High effort: technology leader, higher development costs, more risk in bad state.
42
42 P\SLow effortHigh Low200, 10010, 200 High100, , -100 Grab the dollar game
43
43 Sequential Investment Game P S S High effort Low effort High effort Low effort -100m,-100m 100m, 10m 10m, 200m 200m, 100m
44
44 European Airport Expansion Case: Real Options Game (Smit 2003)
45
45 Two-stage Investment Game (Imai and Watanabe 2004)
46
46 Option to delay versus competition: Incorporating contracts/ Legal system (RF) Firm 1\Firm 2Invest earlyDelay Invest early NPV = 500,NPV = 500NPV = 700, NPV = 300 Delay NPV = 300, NPV = 700 NPV = 600,NPV = 600
47
47 Option to delay versus competition: Incorporating contracts/ Legal system (continued) Firm 1\ Firm 2Invest earlyDelay Invest early NPV = 500,NPV = 500NPV = , NPV = Delay NPV = , NPV = NPV = 600,NPV = 600
48
48 Use of Real Options in Practice
49
49 In practice, NPV not always used:Why Not?. -Agency (incentive) problems: eg Short-term compensation schemes => Payback. Behavioural:- Managers prefer % figures => IRR, ARR Managers dont understand NPV/ Complicated Calculations. Payback simple to calculate. Other Behavioural Factors (see later section on Behavioural Finance!!) Increase in Usage of correct DCF techniques (Pike): Computers. Management Education.
50
50 Game-theoretic model of NPV. Israel and Berkovitch RFS NPV is seen as standard value-maximising technique. But IBs game-theoretic approach considers the impact of agency and assymetric information problems
51
51 Israel and Berkovitch (continued) A firm consisting of two components: 1: Top management (Headquarters) 2. divisional managers (the manager). Objective of headquarters: Maximisation of shareholder value. Objective of manager: maximise her own utility.
52
52 Israel and Berkovitch (continued) HQ needs to design a monitoring and incentive mechanism to deal with these conflicting objectives. => capital allocation system specifying: A capital budgeting rule (eg NPV/IRR) and a wage compensation for divisional managers.
53
53 Israel and Berkovitch Paper demonstrates the ingredients of a game-theoretic approach. Players. Objectives (utility functions to maximise) Strategies. Payoffs.
54
54 2. Information Asymmetry/Agency Theory Chapter 12 CWS. We will see that info assymetry and agency theory play a large role in CF analysis. Investment appraisal, capital structure, dividend policy => Game theory
55
55 Game theory Players (eg managers/investors: or competing companies) Actions (eg invest in a project, issue debt, pay dividends etc) Strategies Payoffs/ optimisation. Equilibrium: eg good firm issues high debt, bad firm issues low debt. Or Good firm pays high dividends, bad firm pays low dividends.
56
56 Information Asymmetry Insiders/managers better informed than investors about projects, prospects etc. Managerial actions (eg capital structure choices: debt/equity issues, dividends, repurchases) may reveal information to the market Signalling models of debt, dividends, repurchases
57
57 Asymmetric info/signalling models Typically, two types of firm: High quality/low quality. Type unobservable to outside investors Manager of High quality firm would like to signal his type to market. Costly signals Cheap-talk signals. Eg level of investment, amount of debt, size of dividend.
58
58 Pooling versus separating equilibria Separating equilibrium: good firm can separate for bad firm eg by higher debt Cost of signal: eg expected financial distress Separation requires cost of signal => bad firm cannot (or is unwilling) to mimic good firms debt level. Separation: outsiders can determine firm types Pooling: outsiders cannot differentiate between the two types
59
59 Corporate Finance: Signalling Models Based on models from Informational Economics. Eg Akerlof (1970): price signals of quality in used car market (mkt for Lemons!) Spence (1973): education as signals of skill in job market. Myers-Majluf (1984): equity-signalling model based on Akerlofs Lemons market!
60
60 Major CF signalling models Signalling project quality with investment (Leland and Pyle 1977) Signalling firm quality with debt (Ross 1977) Signalling expected cashflows with dividends (Bhattacharya 1979) Signalling and the equity issue-invest decision (Myers-Majluf 1984)
61
61 Stock Split signalling Copeland and Brennan 1988 Brennan and Hughes Debt/equity Heinkel 1982
62
62 CF and Agency Theory Standard CF statement: the firm aims to maximise shareholder wealth => NPV rule. But agency theory => Separation of Ownership and control Principal/agent relationship Outside investors = Principal Manager = agent
63
63 Agency theory (contiuned) Manager self-interested. he may takes private benefits (perks) out of the firm Invest in favourite (pet) projects: empire-builder (eg rapid value-destroying growth => mergers?) Effort-shirking Capital structure/dividends may serve to align managers and investors interests.
64
64 2. Cost of Capital/discount rate/investors required return. What discount rate to use in NPV/ valuation? Portfolio analysis => Investors required return as a compensation for risk => CAPM (capital asset pricing model) => cost of equity (risk-averse equity-holders required return): increases with risk.
65
65 Cost of Capital/discount rate/investors required return (continued). Cost of debt (debt-holders required return). Capital structure (mix of debt and equity). => discount rate/cost of capital/investors required return=>
66
66 Example New project: initial investment Project expected to generate £150 per year forever (perpetuity) Kd=5%, Ke = 15% (Capital structure =50% debt/50% equity) Consider Market Value of firms debt = market value of firms equity=> WACC = 10%.
67
67 Firm Valuation (CWS Chapter 14) Formula Approach for Valuing Companies t0t1t2 tN
68
68 Valuation of all-equity firm with growth =>
69
69 Valuation of all-equity firm with growth (continued) Present value of the firm is the sum of discounted cashflows from operations less new investments required for growth Fundamental Value (= market value? Efficient mkts/ BCF) Dividend policy (dividends versus investment for growth)
70
70 Valuation of all-equity firm with growth (continued) V0 = value of assets in place + value of future growth
71
71 Infinite constant growth model =>
72
72 By substitution: But: => Gordon Growth Model: Consider later in div policy lecture
73
73 3. Capital Structure. Positive NPV project immediately increases current equity value (share price immediately goes up!) Pre-project announcement New project: New capital (all equity) Value of Debt New Firm Value Original equity holders New equity
74
74 Example: = = = 40. = 500. = = 540 = 20 = = Value of Debt Original Equity New Equity Total Firm Value
75
75 Positive NPV: Effect on share price. Assume all equity.
76
76 Value of the Firm and Capital Structure).
77
77 Value of the Firm = discounted value of future cashflows available to the providers of capital. -Assume Incomes are perpetuities. Miller- Modigliani Theorem: Irrelevance Theorem: Without Tax, Firm Value is independent of the Capital Structure. Note that
78
78 K D/E K V V Without Taxes With Taxes
79
79 Examples Firm X Henderson Case study
80
80 MM main assumptions: - Symmetric information. -Managers unselfish- maximise shareholders wealth. -Risk Free Debt. MM assumed that investment and financing decisions were separate. Firm first chooses its investment projects (NPV rule), then decides on its capital structure. Pie Model of the Firm: D E E
81
81.
82
82 Combining Tax Relief and Debt Capacity (Traditional View). D/E V K
83
83 3: Optimal Capital Structure, Agency Costs, and Signalling. Agency costs - managers self interested actions. Signalling - related to managerial type. Debt and Equity can affect Firm Value because: - Debt increases managers share of equity. -Debt has threat of bankruptcy if manager shirks. - Debt can reduce free cashflow. But- Debt - excessive risk taking.
84
84 AGENCY COST MODELS. Jensen and Meckling (1976). - self-interested manager - monetary rewards V private benefits. - issues debt and equity. Issuing equity => lower share of firms profits for manager => he takes more perks => firm value Issuing debt => he owns more equity => he takes less perks => firm value
85
85 Jensen and Meckling (1976) B V V* V1 B1 A If manager owns all of the equity, equilibrium point A. Slope = -1
86
86 B V Jensen and Meckling (1976) V* V1 B1 A B If manager owns all of the equity, equilibrium point A. If manager owns half of the equity, he will got to point B if he can. Slope = -1 Slope = -1/2
87
87 B V Jensen and Meckling (1976) V* V1 B1 A B C If manager owns all of the equity, equilibrium point A. If manager owns half of the equity, he will got to point B if he can. Final equilibrium, point C: value V2, and private benefits B1. V2 B2 Slope = -1 Slope = -1/2
88
88 Jensen and Meckling - Numerical Example. Manager issues 100% Debt. Chooses Project B. Manager issues some Debt and Equity. Chooses Project A. Optimal Solution: Issue Debt?
89
89 Issuing debt increases the managers fractional ownership => Firm value rises. -But: Debt and risk-shifting.
90
90 OPTIMAL CAPITAL STRUCTURE. Trade-off: Increasing equity => excess perks. Increasing debt => potential risk shifting. Optimal Capital Structure => max firm value. D/E V D/E* V*
91
91 Other Agency Cost Reasons for Optimal Capital structure. Debt - bankruptcy threat - manager increases effort level. (eg Hart, Dewatripont and Tirole). Debt reduces free cashflow problem (eg Jensen 1986).
92
92 Agency Cost Models – continued. Effort Level, Debt and bankruptcy (simple example). Debtholders are hard- if not paid, firm becomes bankrupt, manager loses job- manager does not like this. Equity holders are soft. Effort Level HighLowRequired Funds Income What is Optimal Capital Structure (Value Maximising)?
93
93 Firm needs to raise 200, using debt and equity. Manager only cares about keeping his job. He has a fixed income, not affected by firm value. a) If debt < 100, low effort. V = 100. Manager keeps job. b) If debt > 100: low effort, V bankruptcy. Manager loses job. So, high effort level => V = 500 > D. No bankruptcy => Manager keeps job. High level of debt => high firm value. However: trade-off: may be costs of having high debt levels.
94
94 Free Cashflow Problem (Jensen 1986). -Managers have (negative NPV) pet projects. -Empire Building. => Firm Value reducing. Free Cashflow- Cashflow in excess of that required to fund all NPV projects. Jensen- benefit of debt in reducing free cashflow.
95
95 Jensens.
96
96.
97
97 Income Rights and Control Rights. Some researchers (Hart (1982) and (2001), Dewatripont and Tirole (1985)) recognised that securities allocate income rights and control rights. Debtholders have a fixed first claim on the firms?
98
98 Conflict Benefits of DebtCosts of Debt Breaking MM Tax ReliefFinl Distress/ Debt Capacity Agency Models JM (1976)Managerial Perks Increase Mgrs Ownership Risk Shifting Jensen (1986)Empire BuildingReduce Freecash Unspecified. StultzEmpire BuildingReduce FreecashUnderinvestment. Dewatripont and Tirole, Hart. Low Effort level Bankruptcy threat =>increased effort DT- Inefficient liquidations.
99
99 Signalling Models of Capital Structure Assymetric info: Akerlofs .
100
100 Asymmetric information and Signalling Models. - managers have inside info, capital structure has signalling properties. Ross (1977) -managers compensation at the end of the period is D* = debt level where bad firm goes bankrupt. Result: Good firm D > D*, Bad Firm D < D*. Debt level D signals to investors whether the firm is good or bad.
101
101 Myers-Majluf (1984). -managers know the true future cashflow. They act in the interest of initial shareholders. Expected Value New investors Old Investors
102
102 Consider old shareholders wealth: Good News + Do nothing = 250. Good News + Issue Equity = Bad News and do nothing = 130. Bad News and Issue equity =
103
103 Old Shareholders payoffs Equilibrium Issuing equity signals that the bad state will occur. The market knows this - firm value falls. Pecking Order Theory for Capital Structure => firms prefer to raise funds in this order: Retained Earnings/ Debt/ Equity.
104
104.
105
105 Practical Methods employed by Companies (See Damodaran; Campbell and Harvey). -Trade off models: PV of debt and equity. -Pecking order. -Benchmarking. -Life Cycle. time Increasing Debt?
106
106 Trade-off Versus Pecking Order. Empirical Tests. Multiple Regression analysis (firm size/growth opportunities/tangibility of assets/profitability….. => Relationship between profitability and leverage (debt): positive => trade-off. Or negative => Pecking order: Why? China: Reverse Pecking order
107
107 Capital Structure and Product Market Competition. Research has recognised that firms financial decisions and product market decisions not made in isolation. How does competition in the product market affect firms debt/equity decisions? Limited liability models: Debt softens competition: higher comp => higher debt. Predation models: higher competition leads to lower debt. (Why?)
108
108 Capital Structure and Takeovers Garvey and Hanka: Waves of takeovers in US in 1980s/1990s. Increase in hostile takeovers => increase in debt as a defensive mechanism. Decrease in hostile takeovers => decrease in debt as a defensive mechanism.
109
109 Garvey and Hanka (contiuned) D/E D/E* V Trade-off: Tax shields/effort levels/FCF/ efficiency/signalling Vs financial distress
110
110 Practical Capital Structure: case study
111
111 Game Theoretic Approach to Capital Structure. Moral Hazard Model. Asymmetric Information Model. See BCF section 8 for incorporation of managerial overconfidence.
112
112 Cash-flow Rights and Control Rights Debt-holders: first fixed claim on cash- flows (cash-flow rights); liquidation rights in bas times (control rights)- hard investors. Equity-holders: residual claimants on cash- flows (cash-flow rights): voting rights in good times (control rights) – soft investors. => minority shareholder rights versus blockholders.
113
113 Equity-holders control rights Voting rights. Soft: free-rider problems. Minority holders versus block-holders. Minority –holders versus insiders. Separation of ownership and control. Corporate Charter. Dual class of shares. Pyramids/tunelling etc.
114
114 Capital/corporate structure in emerging economies. Separation of ownership and control. Corporate Charter. Dual class of shares. Pyramids/tunelling etc. Weak Legal Systems. Cultural differences.
115
115 Game-theoretic approaches. JFE special issue 1988 (Grossman and Hart, Stultz, Harris and Raviv). Bebchuk (lecture slides to follow). Garro Paulin and Fairchild (2006) Lecture slides to follow.
116
116 Mergers and Acquisitions
117
117 Mergers and Acquisitions Acquisitions Divestitures Restructuring Corporate Governance
118
118 Growth Strategies Mergers: one economic unit formed from 2 or more previous units A) Tender offer
119
119 Takeovers Acquisition Proxy Contest Merger Stock Acquisition 1. Merger- must be approved by stockholders votes. 2. Stock acquisition- No shareholder meeting, no vote required. -bidder can deal directly with targets shareholders- bypassing targets management. - often hostile => targets defensive mechanisms. -shareholders may holdout- freerider problems. 3. Proxy Contests- group of shareholders try to vote in new directors to the board.
120
120 Growth Strategies Mergers: one economic unit formed from 2 or more previous units A) Tender offer B) Pooling of Interest Joint Ventures Other collaborations (supplier networks, alliances, investments, franchises)
121
121 Shrinkage strategies Divestitures Equity carveouts Spin-offs Tracking stock
122
122 Theories of M and A. Efficiency increases (restructuring) Operating Synergies Financial Synergy Information Hubris and the Winners curse Agency Problems (changes in ownership/managerialism/FCF) Redistribution (tax, mkt power, …)
123
123 Synergy Value of a Merger Synergy comes from increases in cashflow form the merger:
124
124 Example: Market Value after Merger. Firm A (bidder): cashflows = £10m, r = 20%. V = £50m. Firm B (target): cashflows = £6m, r = 15%. = £40m. If A acquires B: Combined Cashflows are expected to increase to £25m P.A. New Discount rate 25%. Synergy cashflows = £9m. Total value = £100m. Synergy Value = £10m.
125
125 Who gets the gains from mergers? Who gets the gains from mergers? Depends on what the bidder has to pay! (bid premium) If Bidder gets all of the positive NPV. If Target gets all of the positive NPV.
126
126 Why a Bid premium? Hostile Bid: defensive (anti-takeover) mechanisms (leverage increases, poison pills, etc): Bidding wars. Market expectations.
127
127 Effects of takeovers on stock prices of bidder and target. Successful BidsUnsuccessful Bids Jensen and Ruback JFE 1983
128
128 Game Theoretic Approach to M and A. Grossman and Hart (Special Issue on Corporate Control 1982). Harris and Raviv (Special Issue on Corporate Control 1982). Bebchuk (Special Issue on Corporate Control 1982).. Burkart (JOF 1995). Garvey and Hanka. Krause.
129
129 Garvey and Hanka paper Lecture slides to follow.
130
130 Grossman and Hart free-rider paper Lecture slides to follow.
131
131.
132
132 Value of Convertible Bond. Straight Bond Value Conversion Value Total Value of Convertible Bond V Firm Value Face Value
133
133 Conflict between Convertible Bond holders and managers. Convertible Bond = straight debt + call option. Value of a call option increases with: Time. Risk of firms cashflows. Implications: Holders of convertible debt maximise value by not converting until forced to do so => Managers will want to force conversion as soon as possible. Incentive for holders to choose risky projects => managers want to choose safe projects.
134
134 Reasons for Issuing Convertible Debt. Much real world confusion. Convertible debt - lower interest rates than straight debt. => Cheap form of financing? No! Holders are prepared to accept a lower interest rate because of their conversion privilege. CD = D =
135
135 Example of Valuation of Convertible Bond. October 1996: Company X issued Convertible Bonds at October 1996: Coupon Rate 3.25%, Each bond had face Value £1000. Bonds to mature October Convertible into Shares per per bond until October Company rated A-. Straight bonds would yield 5.80%. Now October 1998: Face Value £1.1 billion. Convertible Bonds trading at £1255 per bond. The value of the convertible has two components; The straight bond value + Value of Option.
136
136 Valuation of Convertible Bond- Continued. If the bonds had been straight bonds: Straight bond value = PV of bond = Price of convertible = Conversion Option = 1255 – 933 = 322. Oct 1998 Value of Convertible = = = Straight Bond Value + Conversion Option.
137
137 Alternative Analysis of Irrelevance of Convertible Debt. Firm Indifferent between issuing CD, debt or equity. -MM.
138
138.
139
139.
140
140.
141
141 4: Dividend Policy Miller-Modigliani Irrelevance. Gordon Growth (trade-off). Signalling Models. Agency Models. Lintner Smoothing. Dividends versus share repurchases. Empirical examples
142
142 Early Approach. Three Schools of Thought- Dividends are irrelevant (MM). Dividends => increase in stock prices (signalling/agency problems). Dividends => decrease in Stock Prices (negative signal: non +ve NPV projects left?). 2 major hypotheses: Free-cash flow versus signalling
143
143 Important terminology Cum Div: Share price just before dividend is paid. Ex div: share price after dividend is paid < Cum div. P Time CD ED CD ED CD ED
144
144 Example A firm is expecting to provide dividends every year-end forever of £10. The cost of equity is 10%. We are at year-end, and div is about to be paid. Current market value of equity = 10/ = £110 Div is paid. Now, current market value is V = 10/0.1 = £100. So on…
145
145 P Time CD = 110 ED = 100 CD ED CD ED
146
146 Common Stock Valuation Model You are considering buying a share at price Po, and expect to hold it one year before selling it ex-dividend at price P1: cost of equity = r. What would the buyer be prepared to pay to you?
147
147 Therefore: Continuing this process, and re-substituting in (try it!), we obtain: Price today is discounted value of all future dividends to infinity (fundamental value = market value).
148
148 Dividend Irrelevance (Miller- Modigliani) MM consider conditions under which dividends are irrelevant. Investors care about both dividends and capital gains. Perfect capital markets:- No distorting taxes No transactions costs. No agency costs or assymetric info.
149
149 Dividend Irrelevance (MM): continued Intuition: Investors care about total return (dividends plus capital gains). Homemade leverage argument Source and application of funds argument => MM assumed an optimal investment schedule over time (ie firm invests in all +ve NPV projects each year).
150
150 Deriving MMs dividend irrelevance Total market value of our all-equity firm is Sources = Uses
151
151 Re-arranging: Substitute into first equation: At t =0,
152
152 Successive substitutions Current value of all-equity firm is present value of operating cashflows less re-investment for all the years (residual cashflow available to shareholders) Dividends do not appear! Assn: firms make optimal investments each period (firm invests in all +ve NPV projects). Firms balance divs and equity each period: divs higher than residual cashflow => issue shares. Divs lower than free cashflow: repurchase shares.
153
153 Irrelevance of MM irrelevance (Deangelo and Deangelo) MM irrelevance based on the idea that all cash will be paid as dividend in the end (at time T). Deangelo argues that even under PCM, MM irrelevance can break down if firm never pays dividend!
154
154 Irrelevance of MM irrelevance (continued) Consider an all-equity firm that is expected to produce residual cashflows of £10 per year for 5 years. Cost of equity 10%. First scenario: firm pays no dividends for the first 4 years. Pays all of the cashflows as dividends in year 5. Now it is expected to pay none of the cashflows in any year: Vo = 0 !
155
155 Breaking MMs Irrelevance MM dividend irrelevance theorem based on: PCM No taxes No transaction costs No agency or asymmetric information problems.
156
156 Gordon Growth Model. MM assumed firms made optimal investments out of current cashflows each year Pay any divs it likes/ balanced with new equity/repurchases. What if information problems etc prevent firms easliy going back to capital markets: Now, real trade-off between investment and dividends?
157
157 Gordon Growth Model. Where does growth come from?- retaining cashflow to re-invest. Constant fraction, K, of earnings retained for reinvestment. Rest paid out as dividend. Average rate of return on equity = r. Growth rate in cashflows (and dividends) is g = Kr.
158
158 Example of Gordon Growth Model. How do we use this past data for valuation?
159
159 Gordon Growth Model (Infinite Constant Growth Model). Let = 18000
160
160 Finite Supernormal Growth. -Rate of return on Investment > market required return for T years. -After that, Rate of Return on Investment = Market required return. If T = 0, V = Value of assets in place (re-investment at zero NPV). Same if r =
161
161 Examples of Finite Supernormal Growth. T = 10 years. K = 0.1. A.Rate of return, r = 12% for 10 years,then 10% thereafter. B. Rate of return, r = 5% for 10 years,then 10% thereafter.
162
162 Dividend Smoothing V optimal re-investment (Fairchild 2003) Method:- GG Model: derive optimal retention/payout ratio => deterministic time path for dividends, Net income, firm values. => Stochastic time path for net income: how can we smooth dividends (see Lintner smoothing later….)
163
163 Deterministic Dividend Policy. Recall Solving We obtain optimal retention ratio
164
164 Analysis of If Ifwith Constant r over time => Constant K* over time.
165
165 Deterministic Case (Continued). Recursive solution: => signalling equilibria. Shorter horizon => higher dividends. When r is constant over time, K* is constant. Net Income, Dividends, and firm value evolve deterministically.
166
166 Stochastic dividend policy. Future returns on equity normally and independently distributed, mean r. Each period, K* is as given previously. Dividends volatile. But signalling concerns: smooth dividends. => buffer from retained earnings.
167
167 Agency problems Conflicts between shareholders and debtholders: risk-shifting: high versus low dividends => high divs => credit rating of debt Conflicts between managers and shareholders: Jensens FCF, Easterbrook.
168
168 Are Dividends Irrelevant? - Evidence: higher dividends => higher value. - Dividend irrelevance : freely available capital for reinvestment. - If too much dividend, firm issued new shares. - If capital not freely available, dividend policy may matter. C. Dividend Signalling - Miller and Rock (1985). NCF + NS = I + DIV: Source = Uses. DIV - NS = NCF - I. Right hand side = retained earnings. Left hand side - higher dividends can be covered by new shares.
169
169).
170
170 Dividend Signalling Models. Bhattacharya (1979) John and Williams (1985) Miller and Rock (1985) Ofer and Thakor (1987) Fuller and Thakor (2002). Fairchild (2009/10). Divs credible costly signals: Taxes or borrowing costs.
171
171 Competing Hypotheses. Dividend Signalling hypothesis Versus Free Cashflow hypothesis. Fuller and Thakor (2002; 2008): Consider asymmetric info model of 3 firms (good, medium, bad) that have negative NPV project available Divs used as a) a positive signal of income, and b) a commitment not to take –ve NPV project (Jensens FCF argument). Both signals in the same direction (both +ve)
172
172 Signalling, FCF, and Dividends. Fuller and Thakor (2002) Signalling Versus FCF hypotheses. Both say high dividends => high firm value FT derive a non-monotonic relationship between firm quality and dividends. Firm Quality Divs
173
173 Fairchild (2009, 2010) Signalling Versus FCF hypotheses. But, in contrast to Fuller and Thakor, I consider +ve NPV project. Real conflict between high divs to signal current income, and low divs to take new project. Communication to market/reputation.
174
174 Cohen and Yagil New agency cost: firms refusing to cut dividends to invest in +ve NPV projects. Wooldridge and Ghosh 6 roundtable discussions of CF.
175
175 Agency Models. Jensens Free Cash Flow (1986). Stultzs Free Cash Flow Model (1990). Easterbrook. Fairchild (2009/10): Signalling + moral hazard.
176
176 Behavioural Explanation for dividends Self-control. Investors more disciplined with dividend income than capital gains. Mental accounting. Case study from Shefrin. Boyesen case study.
177
177 D. Lintner Model. Managers do not like big changes in dividend (signalling). They smooth them - slow adjustment towards target payout rate. K is the adjustment rate. T is the target payout rate.
178
178 Using Dividend Data to analyse Lintner Model. In Excel, run the following regression; The parameters give us the following information, a = 0, K = 1 – b, T = c/ (1 – b).
179
179 Dividends and earnings. Relationship between dividends, past, current and future earnings. Regression analysis/categorical analysis.
180
180 Dividends V Share Repurchases. Both are payout methods. If both provide similar signals, mkt reaction should be same. => mgrs should be indifferent between dividends and repurchases.
181
181 Dividend/share repurchase irrelevance Misconception (among practitioners) that share repurchasing can create value by spreading earnings over fewer shares (Kennon). Impossible in perfect world: Fairchild (JAF).
182
182 Dividend/share repurchase irrelevance (continued) Fairchild: JAF (2006): => popular practitioners website argues share repurchases can create value for non- tendering shareholders. Basic argument: existing cashflows/assets spread over fewer shares => P !!! Financial Alchemy !!!
183
183 The Example:…. Kennon (2005): Eggshell Candies Inc Mkt value of equity = $5,000, , 000 shares outstanding => Price per share = $50. Profit this year = £1,000,000. Mgt upset: same amount of candy sold this year as last: growth rate 0% !!!
184
184 Eggshell example (continued) Executives want to do something to make shareholders money after the disappointing operating performance: => One suggests a share buyback. The others immediately agree ! Company will use this years £1,000,000 profit to but stock in itself.
185
185 Eggshell example (continued) $1m dollars used to buy 20,000 shares (at $50 per share). Shares destroyed. => 80,000 shares remain. Kennon argues that, instead of each share being 0.001% (1/100,000) of the firm, it is now.00125% of the company (1/80) You wake up to find that P from $50 to $ Magic!
186
186 Kennon quote When a company reduces the amount of shares outstanding, each of your shares becomes more valuable and represents a greater % of equity in the company … It is possible that someday there may be only 5 shares of the company, each worth one million dollars. Fallacy! CF: no such thing as a free lunch!
187
187 MM Irrelevance applied to Eggshell example At beginning of date 0: At end of date 0, with N0 just achieved, but still in the business (not yet paid out as dividends or repurchases:
188
188 Eggshell figures Cost of equity will not change: only way to increase value per share is to improve companys operating performance, or invest in new positive NPV project. Repurchasing shares is a zero NPV proposition (in a PCM). Eggshell has to use the $1,000,000 profit to but the shares.
189
189 Eggshell irrelevance (continued) Assume company has a new one-year zero NPV project available at the end of date Use the profit to Invest in the project. 2. Use the profit to pay dividends, or: 3. Use the profit to repurchase shares.
190
190 Eggshell (continued) Ex div Each year –end: cum div = $50, ex div = $
191
191 Long-term effects of repurchase See tables in paper: Share value pre-repurchase = $5,000,000 each year. Share value-post repurchase each year = $4,000,000 Since number of shares reducing, P.by 25%, but this equals cost of equity. And is same as investing in zero NPV project.
192
192 Conclusion of analysis In PCM, share repurchasing cannot increase share price (above a zero NPV investment) by merely spreading cashflows over smaller number of shares. Further, if passing up positive NPV to repurchase, not optimal! Asymmetric info: repurchases => positive signals. Agency problems: FCF. Market timing. Capital structure motives.
193
193 Dividend/share repurchase irrelevance See Fairchild (JAF 2005) Kennons website
194
194 Evidence. Mgrs think divs reveal more info than repurchases (see Graham and Harvey Payout policy. Mgrs smooth dividends/repurchases are volatile. Dividends paid out of permanent cashflow/repurchases out of temporary cashflow.
195
195 Motives for repurchases ( Wansley et al, FM: 1989 ). Dividend substitution hypothesis. Tax motives. Capital structure motives. Free cash flow hypothesis. Signalling/price support. Timing. Catering.
196
196 Repurchase signalling. Price Support hypothesis: Repurchases signal undervaluation (as in dividends). But do repurchases provide the same signals as dividends?
197
197 Repurchase signalling: ( Chowdhury and Nanda Model: RFS 1994 ) Free-cash flow => distribution as commitment. Dividends have tax disadvantage. Repurchases lead to large price increase. So, firms use repurchases only when sufficient undervaluation.
198
198 Open market Stock Repurchase Signalling: McNally, 1999 Signalling Model of OM repurchases. Effect on insiders utility. If do not repurchase, RA insiders exposed to more risk. => Repurchase signals: a) Higher earnings and higher risk, b) Higher equity stake => higher earnings.
199
199 Repurchase Signalling : Isagawa FR 2000 Asymmetric information over mgrs private benefits. Repurchase announcement reveals this info when project is –ve NPV. Repurchase announcement is a credible signal, even though not a commitment.
200
200 Costless Versus Costly Signalling: Bhattacharya and Dittmar 2003 Repurchase announcement is not commitment. Costly signal: Actual repurchase: separation of good and bad firm. Costless (cheap-talk): Announcement without repurchasing. Draws analysts attention. Only good firm will want this
201
201 Repurchase timing Evidence: repurchase timing (buying shares cheaply. But market must be inefficient, or investors irrational. Isagawa. Fairchild and Zhang.
202
202 Repurchases and irrational investors. Isagawa 2002 Timing (wealth-transfer) model. Unable to time market in efficient market with rational investors. Assumes irrational investors => market does not fully react. Incentive to time market. Predicts long-run abnormal returns post- announcement.
203
203 Repurchase Catering. Baker and Wurgler: dividend catering Fairchild and Zhang: dividend/repurchase catering, or re-investment in positive NPV project.
204
204 Competing Frictions Model: From Lease et al: Asymmetric Information Agency Costs High Payout Low Payout Taxes High Payout Low Payout High Payout Low Payout
205
205 Dividend Cuts bad news? Fairchilds 2009/10 article. Wooldridge and Ghosh:=> ITT/ Gould Right way and wrong way to cut dividends. Other cases from Fairchilds article. Signalling/FCF hypothesis. FCF: agency cost: cutting div to take –ve NPV project. New agency cost: Project foregone to pay high dividends. Communication/reputation important!!
206
206 Venture Capital/private equity/Hedge Funds Venture capitalists typically supply start-up finance for new entrepreneurs. VCs objective; help to develop the venture over 5 – 7 years, take the firm to IPO, and make large capital gains on their investment. In contrast, private equity firms invest in later stage public companies to a) take them private: Turnarouds, or b) Growth capital. Hedge Funds: Privately-owned institutions that invest in Financial markets using a variety of strategies.
207
207 Hedge Funds Privately-owned institutions Limited range of High net worth (wealthy) investors => HF => invests in FMs Each fund has its own investment strategy Largely unregulated (in contrast to mutual funds); => debate.
208
208 HF strategies HF mgr typically commits to a strategy, using following elements Style Market Instrument Exposure Sector Method Diversification
209
209 HF Strategies (continued) Style: Global Macro, directional, event driven…. Market: equity, fixed income, commodity, currency Instrument: long/short, futures, options, swaps Exposure: directional, market neutral Sector: emerging markets, technology, healthcare Method: Discretionary/qualitative (mgr selects investments): systematic/quantitative (quants)
210
210 Leverage: HFs are marketed on the promise of making absolute returns regardless of mkt May involve hedging (long-short) plus high levels of leverage => very risky? Risk-shifting incentives made worse by HF mgr fee structure!
211
211 HF fee structure Asymmetric fees (in mutual fund, symmetric or fulcrum fees). HF mgr gets a percentage of assets under management plus a performance bonus on the upside: no loss on the downside (investor loses there!) => systemic risk? Regulation debate.
212
212 Fairchild and Puri (2011) Brand new paper on SSRN! HF mgr/ Investor negotiate (bargain) over form of contract: asymmetric or symmetric) HF mgr then chooses safe or risky strategy. He then exerts effort in trying to make strategy succeed. Paper looks at effects of BP and incetnives on contract, strategy and HF performance and risk!
213
213 Activist HFs Passive HFs just invest in FMs, an d look at portfolio decisions Activist HFs actually get involved in the companies that they invest in Members on the board Assist/interfere in mgt decisions Debate: do they add or destroy value? Myopic?
214
214 Private Equity. PE firms generally buy poorly performing publically listed firms. Take them private Improve them (turn them around). Hope to float them again for large gains Theory of private equity turnarounds plus PE leverage article, plus economics of PE articles.
215
215 Theory of PE-turnarounds ( Cuny and Talmor JCF 2007 ) Explores advantage of PE in fixing turnaround Would poorly performing mgrs want to involve PEs when they may lose their jobs?
216
216 Venture capitalists Venture capitalists provide finance to start-up entrepreneurs New, innovative, risky, no track-record… Hence, these Es have difficulty obtaining finance from banks or stock market VCs more than just investors Provide value-adding services/effort Double-sided moral hazard/Adverse selection
217
217 Venture capital process Investment appraisal stage: seeking out good entrepreneurs/business plans: VC overconfidence? Financial contracting stage: negotiate over cashflow rights and control rights. Performance stage: both E and VC exert value- adding effort: double-sided moral hazard. Ex post hold-up/renegotiation stage? Double sided moral hazard => exit: IPO/trade sale => capital gains (IRR)
218
218 VC process (continued) VCs invest for 5-7 years. VCs invest in a portfolio of companies: anticipate that some will be highly successful, some will not Value-adding? Visit companies, help them operationally, marketing etc. Empirical evidence on hours/year spent at each company => attention model of Gifford.
219
219 Venture Capital Financing Active Value-adding Investors. Double-sided Moral Hazard problem. Asymmetric Information. Negotiations over Cashflows and Control Rights. Staged Financing Remarkable variation in contracts.
220
220 Features of VC financing. Bargain with mgrs over financial contract (cash flow rights and control rights) VCs active investors: provide value-added services. Reputation (VCs are repeat players). Double-sided moral hazard. Double-sided adverse selection.
221
221 Kaplan and Stromberg Empirical analysis, related to financial contract theories.
222
222 Financial Contracts. Debt and equity. Extensive use of Convertibles. Staged Financing. Control rights (eg board control/voting rights). Exit strategies well-defined.
223
223 Game-theoretic models of Venture Capitalist/entrepreneur contracting Double-sided moral hazard models (ex ante effort/ ex post hold- up/renegotiation/stealing) – self-interest Behavioural Models (Procedural justice, fairness, trust, empathy)
224
224 Fairchild ( JFR 2004 ) Analyses effects of bargaining power, reputation, exit strategies and value-adding on financial contract and performance. 1 mgr and 2 types of VC. Success Probability depends on effort: where => VCs value- adding.
225
225 Fairchilds (2004) Timeline Date 0: Bidding Game: VCs bid to supply finance. Date 1: Bargaining game: VC/E bargain over financial contract (equity stakes). Date 2: Investment/effort level stage. Date 3: Renegotiation stage: hold-up problems Date 4: Payoffs occur.
226
226 Bargaining stage Ex ante Project Value Payoffs:
227
227 Optimal effort levels for given equity stake:
228
228 Optimal equity proposals. Found by substituting optimal efforts into payoffs and maximising. Depends on relative bargaining power, VCs value-adding ability, and reputation effect. Eg; E may take all of the equity. VC may take half of the equity.
229
229 Equity Stake Payoffs E VC 0.5 Dumb VC!
230
230 Tykvovas review paper of VC Problem is: more equity E has, less equity VC has: affects balance of incentives. Problem for VC is giving enough equity to motivate E, while keeping enough for herself
231
231 Ex post hold-up problem In Fairchild (2004): VC can force renegotiation of equity stakes in her favour after both players have exerted effort. She takes all of the equity How will this affect rational Es effort decision in the first place?
232
232 Es choice of financier Growing research on Es choice of financier VC versus banks VC versus angels VCs are formal funds with legal contracts etc Angels are wealthy individuals, often ex entrepreneurs, sometimes relations of the E!
233
233 Other Papers Casamatta: Joint effort: VC supplies investment and value-adding effort. Repullo and Suarez: Joint efforts: staged financing. Bascha: Joint efforts: use of convertibles: increased managerial incentives.
234
234 Es choice of financier VC or bank finance (Ueda, Bettignies and Brander). VC or Angel (Chemmanur and Chen, Fairchild). See slides on my paper….
235
235.
236
236 My Model: VC/E Financial Contracting, combining double-sided Moral Hazard (VC and E shirking incentives) and fairness norms. 2 stages: VC and E negotiate financial contract. Then both exert value-adding efforts.
237
237 How to model fairness? Fairness Norms. Fair VCs and Es in society. self-interested VCs and Es in society. Matching process: one E emerges with a business plan. Approaches one VC at random for finance. Players cannot observe each others type.
238
238 Timeline Date 0: VC makes ultimatum offer of equity stake to E; Date 1: VC and E exert value-adding effort in running the business Date 2 Success Probability => income R. Failure probability =>income zero
239
239 Expected Value of Project Represents VCs relative ability (to E).
240
240 Fairness Norms Fair VC makes fair (payoff equalising) equity offer Self-interested VC makes self-interested ultimatum offer E observes equity offer. Fair E compares equity offer to social norm. Self-interested E does not, then exerts effort.
241
241 Expected Payoffs If VC is fair, by definition,
242
242 Solve by backward induction: If VC is fair; Since for both E types. =>
243
243 VC is fair; continued. Given Optimal Effort Levels: Fair VCs equity proposal (equity norm):
244
244 VC is self-interested: From Equation (1), fair Es optimal effort;
245
245 Self-interested VCs optimal Equity proposal Substitute players optimal efforts into V= PR, and then into (1) and (2). Then, optimal equity proposal maximises VCs indirect payoff =>
246
246 Examples; VC has no value-adding ability (dumb money) => => r =0 => r => 1,
247
247 Example 2 VC has equal ability to E; => r =0 => r => 1, We show that as r => 1
248
248 Fairness VCs Equity offer 1 0
249
249 Fairness Firm Value 0
250
Behavioural Corporate Finance. Standard Finance - agents are rational and self- interested. Behavioural finance: agents irrational (Psychological Biases). Irrational Investors – Overvaluing assets- internet bubble? Market Sentiment? Irrational Managers- effects on investment appraisal? Effects on capital structure? Herding.
251
251 Development of Behavioral Finance I. Standard Research in Finance: Assumption: Agents are rational self-interested utility maximisers. 1955: Herbert Simon: Bounded Rationality: Humans are not computer-like infinite information processors. Heuristics. Economics experiments: Humans are not totally self-interested.
252
252 Development of Behavioral Finance II. Anomalies: Efficient Capital Markets. Excessive volatility. Excessive trading. Over and under-reaction to news. 1980s: Werner DeBondt: coined the term Behavioral Finance. Prospect Theory: Kahnemann and Tversky 1980s.
253
253 Development III BF takes findings from psychology. Incorporates human biases into finance. Which psychological biases? Potentially infinite. Bounded rationality/bounded selfishness/bounded willpower. Bounded rationality/emotions/social factors.
254
254 Potential biases. Overconfidence/optimism Regret. Prospect Theory/loss aversion. Representativeness. Anchoring. Gamblers fallacy. Availability bias. Salience….. Etc, etc.
255
255 Focus in Literature Overconfidence/optimism Prospect Theory/loss aversion. Regret.
256
256 Prospect Theory. W U Eg: Disposition Effect: Sell winners too quickly. Hold losers too long. Risk-averse in gains Risk-seeking in losses
257
257 Overconfidence. Too much trading in capital markets. OC leads to losses? But : Kyle => OC traders out survive and outperform well-calibrated traders.
258
258 Behavioral Corporate Finance. Much behavioral research in Financial Markets. Not so much in Behavioral CF. Relatively new: Behavioral CF and Investment Appraisal/Capital Budgeting/Dividend decisions.
259
259 Forms of Irrationality.).
260
260.
261
261 Regret theory and prospect theory (Harbaugh 2002). -Risky decision involving skill and chance. -managers.
262
262 Irrational Commitment to bad project. -Standard economic theory – sunk costs should be ignored. -Therefore- failing project – abandon. -But: mgrs tend to keep project going- in hope that it will improve. -Especially if manager controlled initial investment decision. -More likely to abandon if someone else took initial decision.
263
263 Real Options and behavioral aspects of ability to revise (Joyce 2002). -Real Options: Flexible project more valuable than an inflexible one. -However, managers with an opportunity to revise were less satisfied than those with standard fixed NPV.
264
264 Overconfidence and the Capital Structure (Heaton 2002). -Optimistic manager overestimates good state probability. -Combines Jensens.
265
265.
266
266 firms future cash flows (long term rational view).
267
267 Effect of Managerial overconfidence, asymmetric Info, and moral hazard on Capital Structure Decisions. Rational Corporate Finance. -Capital Structure: moral hazard + asymmetric info. -Debt reduces Moral Hazard Problems -Debt signals quality. Behavioral Corporate Finance. -managerial biases: effects on investment and financing decisions -Framing, regret theory, loss aversion, bounded rationality. -OVERCONFIDENCE/OPTIMISM.
268
268 Overconfidence/optimism Optimism: upward bias in probability of good state. Overconfidence: underestimation of asset risk. My model => Overconfidence: overestimation of ability.
269
269 Overconfidence: good or bad? Hackbarth (2002): debt decision: OC good. Goel and Thakor (2000): OC good: offsets mgr risk aversion. Gervais et al (2002), Heaton: investment appraisal, OC bad => negative NPV projects. Zacharakis: VC OC bad: wrong firms.
270
270 Overconfidence and Debt My model: OC => higher mgrs effort (good). But OC bad, leads to excessive debt (see Shefrin), higher financial distress. Trade-off.
271
271 Behavioral model of overconfidence. Both Managers issue debt:
272
272 Good mgr issues Debt, bad mgr issues equity. Both mgrs issue equity.
273
273 Proposition 1. a)If b) c) Overconfidence leads to more debt issuance.
274
274 Overconfidence and Moral Hazard Firms project: 2 possible outcomes. Good: income R. Bad: Income 0. Good state Prob: True: Overconfidence: True success prob:
275
275 Managers Perceived Payoffs
276
276 Optimal effort levels
277
277 Effect of Overconfidence and security on mgrs effort Mgrs effort is increasing in OC. Debt forces higher effort due to FD.
278
278 Managers perceived Indirect Payoffs
279
279 True Firm Value
280
280 Effect of OC on Security Choice Manager issues Equity. Manager issues Debt.
281
281 Effect of OC on firm Values
282
282 Results For given security: firm value increasing in OC. If Firm value increasing for all OC: OC good. Optimal OC: If Medium OC is bad. High OC is good. Or low good, high bad.
283
283 Results (continued). If 2 cases: Optimal OC: Or Optimal OC:
284
284
285
285 Conclusion. Overconfidence leads to higher effort level. Critical OC leads to debt: FD costs. Debt leads to higher effort level. Optimal OC depends on trade-off between higher effort and expected FD costs.
286
286 Future Research Optimal level of OC. Include Investment appraisal decision Other biases: eg Refusal to abandon. Regret. Emotions Hyperbolic discounting Is OC exogenous? Learning.
287
287 Overconfidence and life-cycle debt
288
288 Reverse effect of OC on debt in China?
289
289 Herding
290
290 Hyperbolic Discounting
291
Emotional Finance Fairchilds Concorde case study.
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/781327/ | CC-MAIN-2017-04 | refinedweb | 8,874 | 51.04 |
We.
Late Edit: [Sprite_tm] wrote in on the BASIC. I had it all wrong. Peek and poke work! I just didn’t guess the syntax correctly. Indeed, [Sprite_tm] confirms that they did make use of them during the initial chip check-out phase. How cool is that?
The following code enables GPIO 4 as output, turns it on and then off again, and then prints out the value of the GPIOs inputs in hex. We toggled input voltage on another GPIO and watched the bits bobble. The rest is a simple matter of software.
5 POKE &H3FF44020, 16
10 POKE &H3FF44004, 16
20 DELAY 200
20 POKE &H3FF44004, 0
30 DELAY 200
40 PHEX PEEK(&H3FF4403C)
50 GOTO 10
For what any of these numbers mean, see the memory map in the technical docs (PDF). Have fun!.
107 thoughts on “BASIC Interpreter Hidden In ESP32 Silicon”
“Espressif team has gotten most of the Arduino core up and working, and we have a full review coming out soon. They’re also continuing to work like crazy on development of the C libraries that real programmers will use to run these chips”. Real programmers hehehe.
Can’t wait to receive my esp32
As a programmer i switch between being real and protected but need to be rebooted
Does it require having 286 IQ points?
No, just an A20 gait
Enough of these puns you are about to make an NMI of me.
I would like to LEAVE this thread, but that would terminate me.
And what about imaginary?
Do you mean unreal?
“real programmers” = people who write primitives or never finish anything because they are on a forum somewhere having language arguments..
I never got around to working on “Input” when I was last working on it, so that doesn’t quite work. Also, i think rnd needs parens since it’s a function eg. 10 A = rnd() When I was working on this (for Arduino platforms) Peek and Poke were… interesting since you have EEProm, Program ROM and Program RAM, all separate… so what do Peek and Poke do? (I should note that I had no involvement that I know of in the port to this platform… but I’m super happy to see it in there! :D
Thanks for the added insight Scott! And thanks for all your work on Tiny Basic Plus which made this EasterEgg possible. Sorry I cropped your name out of the screen grab above, but you are clearly cited on the “about” readout from the ESP32 (you’re immortalized in silicon now — the next best thing to carbonite).
“What should peek and poke do?”
For microcontrollers? Poke into the memory-mapped registers that control the hardware peripherals. With peek and poke and a good datasheet, you could do nearly anything (the hard way).
EEPROM and flash/program ROM are much less interesting — and maybe should stay unwriteable. Program RAM is fun for diagnostics (and creating random crashes) so that’d be cool too, if you’re really taking orders. :)
peek=look…..poke= set
Now that is cool!
Yeah man, we are getting to same position as we where in 76-80’s but now just at a beginning of new nano-computers revolution :)
But you did not say how fast it can bit-bang its GPIO’s?
The board on the photo look like Olimex ESP32-coreboard. They are out of stock at this time. Any other similar board you know of ?
“They’re also continuing to work like crazy on development of the C libraries that real programmers will use to run these chips”
“Real Programmers”…. love it.
Maybe there is something like a ‘virtual programmer’… I don’t know.
Well virtualisation of a processor is it having an abstraction layer, so it would be syntactically correct to refer to programmers on higher high level and interpreted languages as virtual programmers. I guess even more so if the language has it’s own virtual machine, like java.
Real programmers don’t eat quiche…
Mandatory xkcd :
Who’s the first to get Star Trek running on one of these.
This doesn’t seem to do anything but begin laoding a program from tape?
Better?
next page for more…no cut and paste though.
(not sure if my first reply went through or not)
I added the “plus” stuff to TinyBasic, but I had no involvement with the ESP32 port of it, so i can’t speak to the specifics of that platform. I need to get one for myself though. :D
When I was working on TinyBasic Plus, I didn’t finish “Input”. It wasn’t working when I started with the code and I never had a chance to get in to figure out why.
iirc, rnd is a function so you need to do something like 10 A=rnd()
And Peek and Poke are interesting. On the Arduino, there are 3 different chunks of memory, so it was unclear which it should be used for; EEProm, program ROM, and RAM. I honestly can’t remember the state of it when I finished. I did let you save and load from EEProm or SD card though… so i treated EE like it was mass storage, and for storing autostart settings.
On the AVR platform, the amount of RAM was too restrictive to do anything useful once you added any support libraries (like SD+Fat etc) that would make it a more useful learning machine computer, so i wandered away and created a even tighter BASIC-derived language. (BLuB)… both are all on Github. I hope to see the changes for ESP32 on there at some point (if they’re not already) and see improvements as per the review above done by someone with a lot more time than I have… :D
I’m the “Scott Lawrence” referred to above. ;)
Oh wow it even has built in spell check. Amazing!
D’oh — my fault. I retyped the output from Elliot’s screencast because you couldn’t read anything in the snippet. An EasterEgg within an EasterEgg? Nope, just me fat-fingering it. #HowTheSausageIsMade
I’m just going to put a ‘hellow’ here for anyone else who searches the page before they comment.
I’m just going to put a “Miley Cyrus latest album” for everyone who searches the internet for puerile crap and then blindly clicks on any link.
What is this click bait, I came here for Miley Cyrus and just found a bunch of nerds
Take your brass lamp and try the rum!
Being an Easter-Egg it is probably a fast adaption of
So the documentation for this last should be good enough.
Indeed it would seem that way. That’s me.
It’s always nice to find a BASIC interpreter on-chip. BTW, on the PEEK/POKE thing, you’ve got the documentation the wrong way round :)
No poke! How are we to get infinite lives in Manic Minor?
That version….. sounds sketchy
now then, now then, now then…
Too soon? *shudder* That man always gave me the creeps
We don’t poke minors anymore. Try a miner.
Do they also have marlocks?
might be a command for writing data to an address like basic used to have back in the dark ages or it could be part of the write command
That is cool! … Or at least it WOULD be cool if I could buy one. :(
BASIC? Forth would be really cool.
maybe you can write one in basic.
Maybe he’d know how if the ‘rents had bought him a Speccy or C64 instead of a Jupiter Ace…
It’s not possible to write a fast Forth in Basic, but it is possible to write a fast Basic in Forth:
You could do it, but it would all be POKEs of op-codes into RAM then save that as an executable. Either just poke in the binary image, or write a meta-compiler in BASIC that reads Forth source for Forth and builds a Forth compiler.
This x10! Forth is _actually_ the perfect language for getting in and exploring a system at a low level. Peek and poke are for suckers when you have @ and !.
But Forth is insane, and only a few people know it / use it. So they went with BASIC. I can respect that.
Seriously on Forth: It’s a tricky language to implement on ESP8266/ESP32 because you really want to retain interoperability with the Espressif C libs for things like WiFi and etc. So you’re basically stuck writing a C Forth rather than an assmebly Forth, with all of the overhead that comes with C function calling. See punyforth for instance.
Mecrisp-Stellaris Forth on the ESPs, with library functionality, would rock. I don’t know how to do it.
Woooo BASIC interpreter. Now have a reason (excuse) to get ESP32. Real programmer. Snicker. Tell that ‘blue llama’ to done fux it right tho. Ha.
why didn’t they announce that they were doing this and make it a full ‘supported’ application? It would add significantly to the people they could sell it to!
B/c the guy who does ESP BASIC (for the 8266) will inevitably port across, and that platform is awesome. My guess is that there will be a truly useable BASIC on the ESP32 within six months, unless the RTOS stuff bogs him down too much. and
Just imagine how fast bitbanging would be using brainfuck or even ook!
You should check out the ARMs used on the BeagleBone boards. They’re TI Sitara ARM Cortex A8s with a pair of “PRU”s. These PRUs are 200 MIPS RISC processors for I/O. You can toggle a pin in software to make a 100MHz square wave. :-)
What’s wrong with BASIC? Its in English. Its obvious how it works. Simple. I’ve used it for over 20 years both professionally and as a hobby and I’ve never needed to peek or poke. Or use Github.
Nothing wrong with modern BASIC like freeBASIC or VisualBASIC. and the like. But this old school BASIC is really outdated. But if one want an interactive language Python has all the modern facilities and it is not harder to learn than old school BASIC or newer BASIC. There is microPython for embedded platform.
I figured out how to patch the millennium bug in PC BIOSes in one line of QBASIC in 1996, and was bitterly, bitterly disappointed at how easy it turned out to be (And how few machines really really had it) because I wanted to make my fortune. :-D
Anyway, have my doubts you could do that in Python…. but it was mostly an illustration of “Look, you can do real world important stuff in BASIC.”
Python probably can’t do that. Then again, neither can BASIC anymore.
microPython is about 20 times the size (80KB) of a TinyBasic implementation (4KB). Not something you can easily hide as an easter egg in a microcontroller.
TinyBASIC is probably only meant to be a toy. But it is enough to see that the system is functioning. It’s difficult to extend without modifying the original implementation and flashing it.
FORTH is arguably as expressive as microPython because it is easily extended, and would fit into a similar foot print. But FORTH doesn’t have the wide appeal as BASIC or Python does.
4K of code seems excessive for a simple BASIC, especially with no floating point, no string variables, no arrays, single character variable names…
I started with QBasic, but now I work with C, C++, or C# depending on the project. I’ve got that QB nostalgia, but after trying out QB64 I honestly can’t remember why I loved it so much.
The syntax is inefficient to write and read. What can be done in one line of C takes a whole subroutine in Basic. Most Basic implementations I’ve worked with (QBasic, PBasic, and TRS-80 Basic) have no real debugger so when something goes wrong you have to manually walk through hundreds of lines of code to realize you typed a < instead of <=.
Then there's the complete and total lack of OOP. Everything has to be written as a single static algorithm, so most AI models are completely out. You don't have classes or even namespaces, so there's no modular design to anything you write, so everything has to be written from scratch by you unless you start with prewritten code and write around it.
Shoot, some implementations don't even have arrays, much less linked lists, search trees, or other dynamic data structures. IIRC, TRS-80 Basic didn't even have variable scopes (or was that PBasic?) so everything was global. This got me into the habit of declaring all variables at the top of the program so I could keep track of what names were already in use.
Then there's the performance issue. You probably could implement FFT in Basic for a 16-bit MCU, but now you're dealing with the massive overhead of the interpreter.
Someone using Basic professionally in 2016 is pretty much unheard of (unless you count VB, but VB6 is garbage and VB.NET is barely Basic anymore). I'd love to know what you use it for, and how you deal with the absence of such basic tools.
I use BASIC to test stepper motors attached to the LPT, with TIP122s running the motor coils. Running DOS 5 and QB4.5 none the less. I also used it as a control system for various experiments in the past, less today with Chinese Arduinos so inexpensive. With GOTOs I got about 500 000 samples per second when doing reads on LPT. When I tried more modern programming approach (loops) the sample rate dropped to less than 100 000. Use subroutines and keep your programs short: less then 300 lines is often enough even for the largest reasonable tasks. I don’t do OOP anyway. It is a solution looking for a problem.
Great news. Finally some GOTOs and GOSUBs like the God intended. Yeeehaaaw!
That’s why I threw them in the code example! I originally inlined the blink “function” but then had to see if I could call it with a GOSUB. Hooray!?
I always said that when the hardware stops doing branch statements, I would stop wanting Goto’s.
Aaaaah no, not Basic!! Why didn’t they use Forth?
Because nobody, not even a basement dwelling ubergeek, wants to go through life sounding like a lisping Jedi… “I use the Forth”.. … …
No, its reverse notation: The Forth I use. :-)
May the Forth be with you.
Wait…
: Forth Love If Honk Then ;
Hehe, seems the little easter egg is public now…
The interpreter actually is triggered in the failure routine for the flash load routines, so if you manage to make the ESP32 read no data or crap from flash, you will get it. Normally, without any input, the watchdog resets the chip so it won’t go sitting around looking pretty in the BASIC interpreter when you do not need it.
I think ‘input’ does not do what you want because if I recall correctly, this BASIC does not do strings. It should work for integers, though. Also, ‘peek’ and ‘poke’ do work, and peek and poke in the address range of the ESP32 memory. So it’s pretty powerful: you can reach ROM, RAM as well as all peripherals with it.
As said before, rnd and ioget are functions, so use them as ‘print rnd()’ and ‘print ioget()’..The other functions are peek, abs and usr. Especially usr is fun: it can call machine language routines. ioget() actually works, but it requires the pin you want to inspect as an argument, eg ‘print ioget(0)’,
Part of the reason for writing that (aside from the fact that, hey, ROM BASIC!) was that it may make testing easier. That’s why eg we also implemented hex numbers (&habc) and binary numbers (&h1011). In the end, I don’t think we used the interpreter past initial chip bringup, but it’s there.
@bleullama and Mike Field: Thanks for making this interpreter. Modifying and expanding this was not something we allocated a lot of time for (I think I got it done in a day or two), your code was small enough to fit into the space we had left in the ROM and readable enough to expand without too much hassle.
@Sprite_tm – I’m Mike Field, who I originally ported/wrote tinyBasic from 68000 assembly to the C on the AVR/ Arduio a few years back I thought it might be good for just waggling pins and so on while testing on a breadboard or board bring-up, as when working on a product it is often helpful to to test before you had a “real” design to flash into it.
I never thought anybody would run with it as much as Scott (@bleullama) has, and now really amazed that you have. For it to be in the ROM of the next-gen ESP module is pretty neat. I’m dead chuffed.
I’ve got quite a few of the older but still great ESP8266 modules for various projects, so I can’t wait for ESP32 to start shipping, allowing me to play with one, and have a warm fuzzy glow knowing that I helped just a teeny-tiny bit in the development of it.
OK, I got rnd(10) and ioget(0) working. That’s great. I was missing the parentheses, which don’t seem to be needed elsewhere? (I don’t speak this language.)
And holy crap! Peek does work, but you have to print or assign it to a variable. (I don’t speak this language.) I was trying to have it work without assignment and it fails.
peek(&h3ff4403c) is a syntax error, but a = peek(&h3ff4403c) works. That’s rad! Off I go to blink LEDs the hard way.
> (I don’t speak this language.)
Kids these days!
Of course PEEK just by itself is an error, what are you expecting it to do with the peek? If you’re not PRINTing it or putting it in a variable, what’s it for? Or to put it another way, PEEK is a function! And BASIC is a bit different from C, in that it’s a halfway house between speaking English and going to a full stack-oriented brain.
How long till someone figures out how to get video output from BASIC?
Easter Egg?!? But … it’s nearly Halloween! :-D
Luckily Sprite_tm didn’t think of the Brianf*ck language.
He did. And then said … “fck it, who is ever going to use this sht!?”
Isn’t that the language that the Benchoff-haters use? “Brianf*ck”
Sorry, couldn’t resist the typo. ;)
The very next time I get shipwrecked on a desert island with nothing but a cargo container of discrete components for company, I’m going to implement a brainfuck native CPU.
Desert island aside, it wouldn’t be difficult, Brainfuck and assembler aren’t too far apart anyway, BF is mostly asm with some bits added just to make it perverse. It’s a simple stack machine, would probably be one of the easiest CPUs you could build.
So if it is “embedded in silicone” – which would make it un-eraseable – isn’t this a huge security risk?
Or is it just in the “empty” chip on delivery and will be erased once you program it?
Basic interpreter in the ESP32 can be disabled by blowing the same OTP bit which disables UART download mode.
Why is it a security risk? It’s not like you’re making something execute code that didn’t before (the entire *point* of a microcontroller is to execute code!) and if you’re in a position to activate basic then you’ve already got full control of the hardware.
It’s not like there’s internal flash you can read out via this interpreter anyway.
Not quite. You may want to brush up on your Microcontroller history.
What’s under threat, and needs the security, is the proprietary code a company would program into it. Say Company X incorporate an ESP32 into their expensive widget. It uses some clever code, that Company X spent a lot of money on researching and developing.
There’s no way of a competitor reading out this code, because microcontrollers have security bits that prevent it. Specifically for that reason, code security. X aren’t worried about people re-programming the micro, they’re worried about their code being stolen.
But with this BASIC thing, Company Y’s spies could get hold of a Widget, boot into BASIC, and use PEEK to examine and dump all the memory to the serial output. Then they have the proprietary software, at least the object code, which could be good enough to clone the product even though they don’t understand it.
Of course there’s internal flash, where else does your code go? Sprite_tm informs us that PEEK can read all the chip’s memory.
Fortunately Igrr’s pointed out that, apparently, this isn’t possible because the security bit also affects the BASIC. Good job, or else this would be a bit of a hole. I suppose whoever’s in charge of the security bit at Espressif will have had to check out all proposed additions to the ROM, and checked this one.
Most other microcontrollers give you no physical access to the flash. The only way to access it (without decapping) is to get the microcontroller to tell you what’s in it. An interpreter in that instance *may* be a security risk.
Except the ESP chips are NOT like other most other microcontrollers. The flash containing the firmware is a separate jellybean chip. It’s not encrypted. You don’t need to rely on the ESP to read it out; just hook another serial flash reader to the chip and go.
pelrun: Well, the whole point is that with the ESP32, the program in external flash chip *can* be encrypted, with keys stored in ESP32 OTP memory (and can be made accessible only by on-the-fly-decryption unit, not by an application).
Ah yeah, I see now. Ignore my misinformed rantings.
BASIC in the ESP32 ROM, now that is an interesting road to travel. As mentioned before, it brings back memories of the Tandy and Li-Chen Wang’s Tiny Basic. I still use BASIC in one form or another, including TechBasic for creating BLE and WiFi based programs directly on my iPad.
Now, is this an Ester Egg, oversight, or a Trojan Horse? We are all aware of back doors to software, is this a hardware back door? For the first version of this chip, I don’t think anyone would be mass producing a commercial product anyway, but this default boot option should not appear in the next version. Anyone can “peek” and “poke” and decompile your code in flash. It might not matter to a hobbyist, but if you are putting some proprietary firmware in it, it has to be secure.
The OTP bit for UART download does not remove access to ROM. I’m betting you could access that area of ROM and read out the memory through bit banged I2C, SPI or software UART.
The trick is that this interpreter can not run from ROM directly. It can only run if copied into IRAM. Which you can not do if UART download mode is disabled and flash encryption/secure boot is enabled.
Aye, the Basic interpreter in ROM is even scrambled so it won’t even render ROP gadgets. Add to that that the Basic interpreter itself also checks that fuse: I really did not want to turn a whimsical addition to turn into a security threat whatsoever.
Glad to hear you took the necessary precautions. For you sake you’re lucky it came out this way. Now the public needs to be educated on this so that the don’t leave this feature open for someone to exploit in the field.
I am really looking forward to testing out this BASIC feature. It does open up a whole new avenue for people to explore.
It would be nice to see the next ESP32 with camera interface ROM support to make it a complete goto SoC. Great work so far, keep it up!
Not sure what you mean by ROM support, but ESP32 does have camera interface, compatible with OV7xxx/5xxx and similar. This is achieved using an I2S peripheral in parallel input mode.
That is good to hear. I don’t see any information about the camera interface in the TRM.
When I mentioned ROM support I was thinking more along the lines of DMA with FIFO buffer accessible in ROM through an API or any other dedicated commands to reduce overhead (better facilitation of streaming video).
Please direct me to where I can find out more about the camera interface with I2S.
I2S documentation is still in translation/editing pipeline, so there isn’t anything i can direct you to at the moment.
E-Z hack stack
10 cls
20 end
No bugs in that program.
Lacks an undo feature :-p
In Basic, don’t String variables need to be prefixed with a dollar sign? That’s the way it was in MSQB
On my ESP32 I get:
rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun 8 2016 00:22:57
and hitting enter does nothing.
this is my module:
any clues?
this is mine:
All this was written here:
Tried this and now I can’t program the device – it reboots, appears to load the program but only does this on a reboot –
Wow! This post has a life of its own.
Back in the mid 80s while working a contract job, I ported “Tiny Basic for the 6800” from Dr Dobbs to a 6809 and turned it into a 2 KB debug monitor in UVEPROM (the thing used to store programs before flash) to debug the product I was doing. I liked that Tiny Basic used BCD floating point, eliminating truncation/rounding errors for 5, etc. due to not having to translate from binary to decimal (since it was pure decimal). I also liked using variables to store debug addresses and being able to “call” (i.e. “gosub”) into my code to test fragments that I was having trouble with. I used “@” for indirection so that I didn’t need Peek/Poke. This first ran on a modified Radio Shack Coco2. I spent a small eternity doing that, but it was fun.
So why did I do it? Development systems were way too expensive then and it’s what us dirt poor developers had to do to survive. Even before the DoD’s ARPANET transformed into “the Internet”. Of course, I cheated and used my day-job employer’s 6809 assembler I learned when it ran on a PDP11. When the assembler was ported to the “PC” later, I ran it on my 8 MHz NEC V20 powered PC with 640KB of RAM! Yes, I am Methuselah.
Please be kind and respectful to help make the comments section excellent. (Comment Policy) | https://hackaday.com/2016/10/27/basic-interpreter-hidden-in-esp32-silicon/ | CC-MAIN-2021-17 | refinedweb | 4,571 | 72.66 |
I'm having immense difficulty figuring out an effective way to override Frame to allow for a custom corner radius and shadow. Does anyone have a good solution? It seems this should be functionality within the cross-platform layout, but isn't yet.
Thanks in advance!
It looks like you're trying to draw a rounded corner border. Have you tried just showing the layer's border?
Layer.BorderColor = elem.BorderColor.ToCGColor()); Layer.BorderWidth = elem.BorderThickness;
And if that works then you don't need to implement the Draw method at all (you shouldn't be changing layer properties in Draw anyway).
Answers
What are you trying? Are you using a custom renderer?
I'm trying to use a custom renderer. Here is the override of Draw in my ios renderer:
`
`
It looks like you're trying to draw a rounded corner border. Have you tried just showing the layer's border?
And if that works then you don't need to implement the Draw method at all (you shouldn't be changing layer properties in Draw anyway).
Thanks for the guidance! The following is working (for the most part):
`
`
The one issue is that with no padding, the child element (in my case a stacklayout) extends beyond the corner radius. I think a good solution will be to create another custom renderer: roundedstacklayout, that sets MasksToBounds = true; (Attached screenshots demonstrate with padding and without padding.
You also need to handle when the properties change. You can use OnElementPropertyChanged for that, and then see if the property that changed is one of the ones you're using.
You could also try making the stack layout have a clear background.
I ended up adding the following:
// Child Element Layer if (this.Layer.Sublayers.Length > 0) { var subLayer = this.Layer.Sublayers [0]; subLayer.CornerRadius = (float)elem.CornerRadius; subLayer.MasksToBounds = true; }
This seemed to work!
Hey guys, thanks for this thread...it helped a lot. I was able to implement the code for creating a custom shadow, but not the border radius. 'CornerRadius', 'BorderThickness' and others are not defined, which probably means I'm missing an Assembly Reference with the definitions. Could you include what all references you needed for this to work? I know the Shadow took CoreGraphics, but what about the Border? I looked through API but no luck finding it. Thanks!
Those properties are on the CALayer class, not UIView. You need to set them on the view's
Layer. Example:
Hello,
@MichaelRobichaud
I am following the example provided in this thread. It seems that I am missing an assembly because I cannot find BorderViewContainer. Would you please tell me what assemblies/namespaces are you referencing to?
Thanks.
@LoneLy Since this comes up a lot, here's the full code for mine for iOS:
I occasionally have to set IsClippedToBounds = true as well.
Thanks @TonyD. After I copied and pasted your code in mine, I cannot resolve Radius, BorderWidth, and BorderColor in my elem object. Any ideas what I may have missed?
Btw, my ExtendedFrame is an empty class that inherits from Frame.
Yep just add those as double properties to ExtendedFrame in your PCL project. Not in front of my work computer but something like:
(...)
}
Now it works perfectly! Thanks a lot @TonyD !
Do you have code for android too? @TonyD
@BBright yes but it's like 10x longer.
The way I did it was go to the Xamarin Source code (open source), look for the Android frame renderer, and copy paste it. At the time they had hardcoded Radius = 5 into their source code. I just changed it to make it customizable.
Yes, I tried it with using same way when I did it to button.
like this.
but no luck.
Could you share your code?
And plus, where can you see the code?
Did you find it from here?
@TonyD Thanks.
@BBright
For Android my code is this file:
and I replaced this:
float rx = Forms.Context.ToPixels(5);
float ry = Forms.Context.ToPixels(5);
changed 5 to custom property. Not sure why XF team decided to force everyone to use 5 pixels.
Thanks again @TonyD
I'm sorry I have to ask you again, Did you build xamarin.forms your own??
How could you possibly change it? I can not override DrawBackground method.
I tried like this. but no luck. It's working incorrectly.
Just replace all frame with extendedframe. I didn't rebuild XF for this.
Hi, @TonyD For your help, It's working now. Thanks.
Another problem here. I noticed it does not crop frame and its children but just drawing rounded rect on background.
Do you think I can crop rounded corner as I expected?
I meant cropping inside contents not working.
@BBright - did you do IsClippedToBounds = true? My inside content is a bit far from the corner so it's possible that inside cropping isn't working.
@TonyD Yeap, I did. but cropping is not working. source code is just drawing background rounded.
Never mind.
@BBright I just checked and inside cropping seems to work for iOS but not Android. If you figure out the latter, please post it here!
@TonyD Thanks for double checking.
Yeap. I would.
Has anyone tried accomplishing this by using a 9-patch image with something like Forms9Patch? You could then presumably get a nice feathered drop shadow together with perfectly sharp, rounded corners, with virtually zero performance hit. And then put a layout with transparent background on top it. I haven't tried this yet myself, but I do need the functionality, and it seems like it would work.
This article describes how to customize border shadow effects for both platform by custom renderer | https://forums.xamarin.com/discussion/comment/112511/ | CC-MAIN-2019-18 | refinedweb | 948 | 69.07 |
Hot Upgrades! Whaaaaaaaat?
Hot upgrades are quite a difficult task in deployments.
In past, we were using Exrm in Evercam.io and we were never bothered by any difficulty as well as never concerned about how things work when you deploy a phoenix application. The moment, Marco Herbst brought up the topic of hot upgrades, I was totally unaware of what it is, and how am I going to deal with this.
But we somehow achieved hot upgrades for our application.
In this article, I will try to some up my work of 3 weeks with all the difficulties I faced.
Keeping that in mind your project is a fresh repository and not using any kind of deployment tool yet now.
1. Add/Switch to Distillery.
This part is quite simple. Add distillery in your dependency list.
defp deps do
[
...
{:distillery, "~> 2.0"},
...
]
end
and run
mix deps.get, compile
This part will go as smooth as expected. Now the fun part start here, you need to run
mix release.init This will create these files and folders in the root of your project.
The config file is quite simple. But you can find out more interesting things about config here.
NOTE: for Hot upgrades, this part of config file should always be true.
environment :prod do
set include_erts: true
2. Incremental Application Versions.
Update:
The logic I have been using for application versions don't really work there is this issue: When you are doing your work in a branch and have deployed it many times, and then you want to deploy your master again with the hot upgrade, it will break because your master will not have the latest commit or version. So instead of using the old one, use this one, and it's better. It will change on each deploy either it's a branch or master again.
version: "1.0.#{DateTime.to_unix(DateTime.utc_now())}"
Deprecated Logic: One thing for hot upgrades, you should keep in mind, your application versions should be incremental. e.g.
1.0.1,
1.0.2,
1.0.3and so on.
So how are you going to do that???
Be my friend 😍
There are several approaches to do that we will do the best way possible.
defp versions do
{epoch, _} = System.cmd("git", ~w|log -1 --date=raw --format=%cd|)
[sec, tz] =
epoch
|> String.split(~r/\s+/, trim: true)
|> Enum.map(&String.to_integer/1)
sec + tz * 36
end
curious enough?
We are actually trying to use last commit’s date.
Interactive Elixir (1.7.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> {epoch, _} = System.cmd("git", ~w|log -1 --date=raw --format=%cd|)
{"1536894554 +0500\n", 0}
after making a few changes to the above results we will have our resulting version number. eh? Put the above
defp version in your
mix.exs file and then your
project part should look like this.
def project do
[app: :evercam_media,
version: "1.0.#{versions()}",
.....
end
and for Evercam Server the app version will look like this.
iex(2)> EvercamMedia.Mixfile.project[:version]
"1.0.1536912554"
iex(3)>
and each time with your latest commit your version number for the app will change in an incremental way as its date and will be increasing and changing, Perfect!
Now let's create your first production release with the command
MIX_ENV=prod mix release.
NOTE: For Evercam Server we have a lot of ENVs so each time when our ansible script compiles or create a release for us, we prepend those
envs.
The results of above release command will give you such results for your application.
Generated evercam_media app
==> Assembling release..
==> Building release evercam_media:1.0.1536912554 using environment prod
==>
Easy enough for creating your first production release.
This one command is good enough for you to start your application
_build/prod/rel/evercam_media/bin/evercam_media start
but that is not the right way to do it, or its not a right way for hot upgrades. It's a convention that when you deploy your application for production. There should be two places on your remote server.
- where you clone, compile and create a release.
- where you place your production release to start it.
As I have mentioned above we are using ansible-playbook for all deploy purposes where we have mentioned the remote build directory and remote application directory. i.e
/tmp/build_media and
/opt/evercam_media respectively.
So once you have created a release for you application you will have these kind of files in your
_build directory
In all of the above files, the most important one is
tar.gz file. This file will be in your remote build directory and you will
unarchive it to your remote application directory, in our case it was
/tmp/build_media/
/opt/evercam_media
and now in your remote application directory you will have files like this.
root@evercam-release-test:/opt/evercam_media# ls
bin erts-10.0 lib releases var
All above commands which were stated above now will work from this directory such as this command
/tmp/build_media/_build/prod/rel/evercam_media/bin/evercam_media start
will become like this for the new unarchived remote application directory
/opt/evercam_media/bin/evercam_media start
Now as you are working on Ubuntu server (I hope so.) you will need an
upstart job or a
systemd job to run your application as a
daemon.
For a brief on
systemd (Ubuntu 16.04 and above) you need to create a file in this directory
/etc/systemd/system/yourappname.service
after creating the file paste this minimal template for your application, you can replace the application name and your
envs as you like.
[Unit]
Description=Evercam Media
After=network.target[Service]
Type=forking
LimitNOFILE=1000000
User=root
Group=root
Environment=HOME=/home/root
Environment=LANGUAGE=en_US:en
Environment=LS_ALL=en_US.UTF-8
Environment=ERL_MAX_PORTS=10240
Environment=ERL_MAX_ETS_TABLES=7000
Environment=PORT=4000
Environment=MIX_ENV=prod
Environment=START_CAMERA_WORKERS=false
Environment=DATABASE_URL=postgres://localhost/evercam_dev
Environment=SNAPSHOT_DATABASE_URL=postgres://localhost/evercam_devWorkingDirectory=/opt/evercam_media
ExecStart=/opt/evercam_media/bin/evercam_media start
ExecStop=/opt/evercam_media/bin/evercam_media stop
Restart=always
RestartSec=5
Environment=LANG=en_US.UTF-8
SyslogIdentifier=evercam_media[Install]
WantedBy=multi-user.target
Now save this file with a name you like to call your application and run this command from the same directory .i.e
/etc/systemd/system/ where you have saved the file.
systemctl enable yourfilename.service
this command will result in
Created symlink from /etc/systemd/system/multi-user.target.wants/yourfilename.service to /etc/systemd/system/yourfilename.service.
Now you can just start and stop your application with 2 simple commands
systemctl stop evercam_media.service && systemctl start evercam_media.service
Now the most fun part is going to start which is creating an upgrade release for your application, the things you need to worry about.
- Upgrade will only work if there will be an older version of the application is present in build as we as the working directory.
- Your new version should be in incremental form and always getting changed.
Now make a few changes to your application (don't forget to commit the changes) and create an upgrade release as
MIX_ENV=prod mix release --upgrade
and this command will result in
Generated evercam_media app
==> Assembling release..
==> Building release evercam_media:1.0.1537045416 using environment prod
==> Generated .appup for evercam_media 1.0.1536912554 -> 1.0.1537045416
==> Relup successfully created
==>
So fair enough, It created an
appup file for you and also a new version of the application.
3. The distillery is not using the new version number
So the above upgrade step is not as simple as it looks, I tried millions of times with always a new version number but Distillery never picked a new version number.
NOTE: It's not a bug in the distillery. the issue is that Mix is compiling the module, and because the module isn’t modified on disk, the result of that compilation is cached (namely the
.app file which contains the version).
So for this purpose before doing the compile and mix release. you always need to touch your
mix.exs file such as
touch mix.exs
that's enough for the compiler to realize that something got changed in
mix.exs and it will consider it for compilation. In this way, your new version will always be picked up. handy enough? 😍
4. An upgrade is not working for me I am having a lot of Errors.
So as in the 2nd step, we successfully created an upgrade release of our application, but that’s not an ideal case always. You are going to hit many errors for sure.
- which may come during
mix release --upgrade
- or the time you are doing an
upgrade
You can always ask Paul Schoenfelder, I have been to many
repos and asked questions but I never found anyone that much interested in solving your problems as this guy is.
The errors could be of any kind, At first, let's do an upgrade of our application as we were running
1.0.1536912554 version and our new upgrade release is
1.0.1537045416 as in past we just took the
tar.gz file and
unarchive it to your application directory i.e
/opt/evercam_media but this time you will do differently. As I highly suggest you use ansible-playbook, you will get the new release version number this way.
cat /tmp/build_media/_build/prod/rel/evercam_media/releases/start_erl.data | awk '{print $2}'
this will give you the latest version number, If you have used ansible ever, then you can register this version number to a variable for future use. After getting the latest version number you will copy that version directory from your build directory to application directory’s release folder. Confused? Eh?
Your
_build directory after an upgrade should look like this
from here you will copy the latest release folder to this directory
/opt/evercam_media/releases
and after copy your release folder will look like this
1.0.1536912554 1.0.1537045416 RELEASES evercam_media.rel start_erl.data
Now you will upgrade to a newers version , You can be anywhere in directory level but root directory is preferable, then run this command.
/opt/evercam_media/bin/evercam_media upgrade 1.0.1537045416
If everything goes right. you will see a message like this.
Release evercam_media:1.0.1537045416 not found, attempting to unpack releases/1.0.1537045416/evercam_media.tar.gz
Unpacked '1.0.1537045416' successfully!
Release evercam_media:1.0.1537045416 is already unpacked, installing..
Release evercam_media:1.0.1537045416 is already installed, current, and permanent!
Congratulations! you have done a hot upgrade.
NOTE: This is not as simple as it looks, You will hit so many hurdles during all this. and so many errors related
relup files and many more. but you need to consider few things.
- Your old successive release is there when you again run
mix release --upgradeand your old releases are also there when you run
/opt/evercam_media/bin/evercam_media upgrade version
- You cannot do
upgradewithin your build directory, So that’s why you always need to create a release in other directory and then copy it to another to run your application from there.
- A hot upgrade is not
unarchiveit's copying the new release folder to the releases folder in the application directory and then upgrade.
You are always going to face hurdles only when doing upgrades but all the errors will get connected to one place
relup and
appup but they will be in different forms always.
A few errors could look like these
▸ Received 'pang' from evercam_media@127.0.0.1!
▸ Possible reasons for this include:
▸ - The cookie is mismatched between us and the target node
▸ - We cannot establish a remote connection to the node
Node evercam_media@127.0.0.1 is not running!Release evercam_media:1.0.1-a42e5917 not found, attempting to unpack releases/1.0.1-a42e5917/evercam_media.tar.gz
Unpacked '1.0.1-a42e5917' successfully!
Release evercam_media:1.0.1-a42e5917 is already unpacked, installing..
▸ Release handler check for evercam_media:1.0.1-a42e5917 failed with: {:no_matching_relup, '1.0.1-a42e5917', '1.0.1-a25483c8'}"Could not locate code path for release-evercam_media\",\"1.0.1-a2ac4195!"
5. Hot upgrade happened? somethings have stopped?
So you have done everything possible in a mannered way make things work but there are few applications which have been stopped and they are not working after hot-upgrade, I have one example of
Porcelain.
After hot-upgrade, the porcelain application stopped working. And its error was so misleading as
defp driver() do
case Application.fetch_env(:porcelain, :driver_internal) do
{:ok, mod} -> mod
_ ->
raise Porcelain.UsageError, message: "Looks like the :porcelain app is not running. " <>
"Make sure you've added :porcelain to the list of applications in your mix.exs."
end
end
Porcelain was there in my application list but the error was still coming. In short porcelain application’s
envs which set by it on start was missing, So you need you re-init porcelain application.
Now the question is how to do it? How can you know or tell that at this point hot-upgrade just happened? No ideas? So be my guest.
code_change/3 this is the most interesting part of GenServer in case of a hot upgrade as written.
Invoked to change the state of the
GenServerwhen a different version of a module is loaded (hot code swapping) and the state’s term structure should be changed.
So what you will do now? 😖
You will create a new module, I would name it a
Janitor and it will look like this
defmodule EvercamMedia.Janitor do
use GenServer
require Logger
def start_link() do
GenServer.start_link(__MODULE__, :ok, [])
end
def init(_args) do
{:ok, 1}
end
def code_change(_old_vsn, state, _extra) do
Logger.info "Re-init Porcelain"
ensure_porcelain_is_init()
{:ok, state}
end
defp ensure_porcelain_is_init do
Porcelain.Init.init()
end
end
and add it to your supervisor tree as a worker, in our case
worker(EvercamMedia.Janitor, [])
NOTE: After adding this
Janitor , the very first deploy should be from scratch. If you will hot deploy it, It will come up in your
appup but it will not work, because of your supervisor tree might have gone in
load_module state instead of
update in
appup.
To understand it more click me.
So after the first scratch deploy, you will do a hot-upgrade but wait???
code_change/3 is not working? Nothing is being called?? Also
Janitor module is not coming in
appup.
So Distillery is not considering it to be in
appup and why it would be? Have you changed anything in it? And would it be logical to change few lines in
Janitor to make it appear in
appup file? 😧
So here is the magic trick, Module Attributes as its stated.
Module attributes as
annotationsare used by the code reloading mechanism in the Erlang VM to check if a module has been updated or not.
And we have not defined any version of our
Janitor. So we will add a module attribute as
@vsn
@vsn DateTime.to_unix(DateTime.utc_now())
Add the above line beneath
require Logger.
Now whenever you will do a hot upgrade this
@vsn will be changing each time and telling distillery
appup creator that
Janitor has been changed and place it in
appup as
{update,'Elixir.EvercamMedia.Janitor',{advanced,[]},[]},
Each time when you do a hot upgrade the
code_change/3 callback will get called and rescue you. (It rescued us). ✋
Suggestions: People mostly say not to use hot-upgrade but I will suggest to use it, It’s an awesome feature. But in any case, while hot-upgrade you hit any error, Just deploy from scratch and then do hot-upgrade again. If you will fall for errors came across while hot-upgrade then you will get frustrated. i.e. errors when you created an upgrade release or when you did
upgrade.
There are so many things to learn from all this experience, I will highly suggest using Ansible Playbooks for deployment purposes. And read Appup Book along with Distillery’s guide. I faced many errors while all this process, But Distillery’s author was a big help to me.
This is my very first article on the internet. You can disagree with many things, I am open to any suggestions or help you need.
| https://medium.com/@junaid_16874/hot-upgrades-whaaaaaaaat-29bad102795e?utm_source=elixirdigest&utm_medium=web&utm_campaign=featured | CC-MAIN-2019-39 | refinedweb | 2,718 | 57.67 |
Decode HTML entities into Python String
In this article, we will learn to decode HTML entities into Python String. We will use some built-in functions and some custom code as well.
Let us discuss decode HTML scripts or entities into Python String. It increases the readability of the script. A programmer who does not know about HTML script can decode it and read it using Strings. So, these three methods will decode the ASCII characters in an HTML script into a Special Character.
Example: Use HTML Parser to decode HTML Entities
It imports
html library of Python. It has
html.unescape() function to remove and decode HTML entities and returns a Python String. It replaces ASCII characters with their original character.
import html print(html.unescape('£682m')) print(html.unescape('© 2010'))
£682m
© 2010
Example: Use Beautiful Soup to decode HTML Entities
It uses
BeautifulSoup for decoding HTML entities.This represents Beautiful Soup 4 as it works in Python 3.x. For versions below this, use Beautiful Soup 3. For Python 2.x, you will need to specify the
convertEntities argument to the BeautifulSoup constructor. But in the case of Beautiful Soup 4, entities get decoded automatically.
html.parser is passed as an argument along with the HTML script to BeautifulSoup because it removes all the extraneous HTML that wasn't part of the original string (i.e. <html> and <body>).
# Beautiful Soup 4 from bs4 import BeautifulSoup print(BeautifulSoup("£682m", "html.parser"))
£682m
Example: Use w3lib.html Library to decode HTML Entities
This method uses
w3lib.html module. In order to avoid "ModuleNotFoundError", install
w3lib using
pip install using the given command. It provides
replace_entities to replace HTML script with Python String.
pip install w3lib
from w3lib.html import replace_entities print(replace_entities("£682m"))
£682m
Conclusion
In this article, we learned to decode HTML entities into Python String using three built-in libraries of Python such as
html,
w3lib.html, and
BeautifulSoup. We saw how HTML script is removed and replaced with ASCII characters. Install your packages correctly if you are getting "ModuleNot FoundError". | https://www.studytonight.com/python-howtos/decode-html-entities-into-python-string | CC-MAIN-2022-21 | refinedweb | 344 | 60.21 |
the project is about a debate, and there are 4 candicates in the debate, and we need to group them into 4 different dict and count the word frequence they said. the debate is line by line, and we should group the sentences by name tage, like PAUL: and then all lines after needs to be his dict until another name tage appears.
I just done with the file open part and Ive been stuck on the grouping for hours
import string debate_line=open('debate.txt','rU') big_list=[] stop_word=open('stopWords.txt','rU') word_set=set() word_list=[] name=['romney:','santorum:','gingrich:','paul:'] for line in debate_line: line=line.lower() line=line.strip(string.punctuation) big_list.append(line.split()) for item in big_list: if len(item)<1: big_list.remove(item) for item in big_list: if item[0]=='paul': for word in item: if word in paul_dict: paul_dict[word]+=1 else: paul_dict[word]=1
the last part just doesnt work at all
Start with the simple basics; print big_list and make sure it contains what you think it does and is in the form you expect to be in. You can also add a print statement after
for item in big_list:
to print the item, but it is basically the same thing.
Assuming the data is correct (and I'm not sure it is), try something along these lines
name_list=['romney','santorum','gingrich','paul'] found=False for item in big_list: if item[0] == "paul": found=True ## if another name then stop processing elif item[0] in ['romney','santorum','gingrich']: found=False if found: for word in item: if word in paul_dict: paul_dict[word]+=1 else: paul_dict[word]=1 | http://www.daniweb.com/software-development/python/threads/416953/just-start-python-need-help-with-project | CC-MAIN-2014-10 | refinedweb | 275 | 62.82 |
Details
- Type:
Improvement
- Status: Closed
- Resolution: Fixed
- Affects Version/s: trunk
- Fix Version/s: None
- Component/s: renderer/pdf
- Labels:
- Environment:Operating System: All
Platform: All
- External issue ID:46705
Description
See attached html file and patch
Issue Links
Activity
- All
- Work Log
- History
- Activity
- Transitions
Attachment accessibility.html.txt has been added with description: Documentation - will be merged into trunk by Jeremias
Note: the patch is against the new IF branch:.
Related Wiki pages:
Hi Jost,
I've just been trying out your patch. I applied the patch to a fresh check out of the new IF branch, compiled it okay. But when I tried to generate a PDF from the command line I got the following NPE:
INFO: Accessibility is enabled
16-Feb-2009 10:25:44 org.apache.fop.cli.Main startFOP
SEVERE: Exception
java.lang.NullPointerException
at org.apache.fop.apps.Fop.getDefaultHandler(Fop.java:138)
at org.apache.fop.cli.InputHandler.renderTo(InputHandler.java:126)
at org.apache.fop.cli.Main.startFOP(Main.java:174)
at org.apache.fop.cli.Main.main(Main.java:205)
Thanks,
Chris
Generally, the patch looks pretty good to me, besides the NPE which I know Jost is already working on a fix for. That particular bug occurs because the stylesheets get loaded via java.io.File instead of Class.getResource(AsStream).
I've got a few nits which I'll gladly address myself after we've applied to patch to a temporary branch:
- FOUserAgent: set/getResult are not very speaking names for what they do. It might also be better to just save a DOM instead of a byte array.
- area/inline/Image: ptr is normally set as a trait in the area tree but not for the Image area. That can be homogenized.
- I'd rename fox:alt to a more speaking fox:alt-text.
- Some classes have just non-semantic changes (like commented code that is never used or unnecessary "final" modifiers which look like they have come from "Save Actions" in Eclipse). I'll remove those while processing the patch to reduce the noise.
- There are some backwards-incompatible changes in the Renderer implementations which are avoidable.
- I'd like to avoid adding the "ptr" attribute to the IFPainter methods since most implementations don't support that anyway. I'd rather do it via the IFContext like I've done for the foreign attributes.
- Static code analysis indicates a bug in PDFImageHandlerSVG concerning the save/restore pairs.
- I'd move the FO -> PDF Struct Type mapping (in PDFStructElem) out of the PDF library into the render/pdf package (separation of concerns and opening an option for a later implementation of a custom role map).
Please speak up if anyone objects to any of these proposed changes.
Attachment patch16Feb2009.txt has been added with description: Fixed NPE when used from command line
Attachment patch2-16Feb2009.txt has been added with description: Removed unused code in area/inline/Image & related
[Jeremias:]area/inline/Image: ptr is normally set as a trait in the area tree but not
That's great new functionality. I've only had time to look at a part of the patch so far, so I'm posting my few comments below. More later if I have time.
In the o.a.f.accessibility package:
- why are there two classes? Only the sub-class seems to be externally used, so it may as well be merged with the super-class. If some more general functionality turns out to be necessary, the extraction of a common super-class can always be done later.
- Likewise, only one constructor seems to be used ATM. If other constructors are needed, they can also be added later on.
- AFAIU mTranHandler is set in all of the constructors. Why systematically test it for null in the methods then?
There is an encapsulation problem in o.a.f.apps.Fop.getDefaultHandler(): the lines of code dealing with accessibility should be moved to the accessibility package.
In FOUserAgent:
- the "accessibility" string should be defined only once in a public final static field (ideally somewhere inside the accessibility package)
- there's no need to explicitly put false for the accessibility option in the constructor, as the value is tested for null in the accessibilityEnabled method
In FopFactoryConfigurator.configure():
- any reason why the accessibility option is not handled like the other options? (using getValueAsBoolean)
And a nit about coding style: you seem to be using Hungarian notation to name fields ('mTheClassField'). I don't have anything against this notation, but it's not used inside the rest of FOP's codebase. For consistency we may want to agree upon a notation. FWIW I tend to think that, thanks to modern development environments that now highlight class members, this notation is no longer so useful.
Thanks,
Vincent name="
name="{name()}
">
.
Hi Andreas,
The approach with the @id seems a bit risky. The @ptr replacement has to have unique values. What happens if a user has a few empty @id in his FO or multiple times the same value for @id?
Cheers, Jost
(In reply to comment #9)
> The approach with the @id seems a bit risky. The @ptr replacement has to have
> unique values. What happens if a user has a few empty @id in his FO or multiple
> times the same value for @id?
Could be, and I'm definitely not blocking the proposal on this count. Just an idea.
Having multiple times the same value for an id will cause an error, since @id has to be unique for every element. If it is not specified, then it could be added using a stylesheet, initializing it with generate-id(), just like you propose for @ptr.
The only thing FOP currently does not do is generate and assign ids automatically, but the uniqueness constraint is already checked for.
Jost asked me off-list about my opinion on Vincent's feedback. I'll put it here. Generally good input. The merging of TransformerNode and TransformerNodeEndProcessing is probably a matter of taste. I personally prefer keeping the general functionality seperate from the concrete functionality of the subclass. As mentioned before, I'd like to put this new code into a branch before putting it in Trunk. So we can also address these points in a second step. I assume we all agree that this is great new functionality and if it's applied now (in a separate branch) we can all help improve the whole thing rather than off-loading so many little things on Jost. He can of course continue to send follow-up patches.. Also, the area tree and AT XML will increase in size of all elements have IDs. BTW, Andreas' proposal for adding the IDs is not entirely correct. Not all FO element take an "id" property. Maybe this should be done inside the FO tree instead of the addPtr.xsl.
(In reply to comment #11)
>
>.
Well, what I'm personally a bit concerned about is the case where you have:
1) auto-generated ids by the 'main' stylesheet
2) additional auto-generated ids by the 'pre-processing' stylesheet
Since we have two passes, are we still 100% certain that the XSLT processor will always return unique values that are used nowhere as an id elsewhere in the document?
For explicit ids, this problem would also exist, but AFAIK, no one specifies explicit ids like "N897654", which is a format returned by some generate-id() implementations.
If the answer to my above question is yes, then there is no real overhead (on the FOP-side) involved for collision-detection, since the XSLT processor will take care of that (or even the XML parser: Is 'id' not a standard XML attribute? Or does it have nothing to do with the standard 'id()' XPath function? I'd have to check in the respective specifications to be sure...)
> Also, the area tree and AT XML will increase in size of all elements have IDs.).
> BTW, Andreas' proposal for adding the IDs is not entirely correct. Not all FO
> element take an "id" property.
Again, very true, but we do implement getId() in FObj. That currently means that, although the property may not apply to a given element, like fo:declarations, as long as the Java object extends FObj, the id property will be bound and available if it is specified.
Checking closer, Declarations.java overrides bind() rather than relying on the superclass implementation. Removing that empty implementation would be enough to make it work.
Not 100% compliant, but it seems like this actually may have added value here.
> Maybe this should be done inside the FO tree instead of the addPtr.xsl.
What I was thinking indeed. Something like a dedicated IDPropertyMaker that extends StringProperty.Maker, and would offer an implementation for make(FObj, PropertyList) that returns a 'proper' initial value. I once implemented it as such (and committed it, but it was a bit too quick and caused other issues, so it was reverted almost immediately)
Downside is that, if we implement it like that in the FO tree, it would also be necessary to implement the b) part in my earlier response, as the ids will never be available in the raw FO source, so reduceFOTree.xsl would not yet 'see' them (unless they would be added by a pre-processing stylesheet, like Jost proposes)
(In reply to comment #12)
<snip/>
> Since we have two passes, are we still 100% certain that the XSLT processor
> will always return unique values that are used nowhere as an id elsewhere in
> the document?
I would assume: no.
<snip/>
>).
Agreed.
.
As I've heard no objections to my proposal from Monday, yet, I'll process Jost's patch (as is) tomorrow morning (my local time) into a branch off the IF branch. From there, we can take it further and incorporate all the feedback. That also makes it easier to track what is changed.
(In reply to comment #13)
> (In reply to comment #12)
>
> I would assume: no.
FWIW, just checked the XML and XPath specifications, and that one question regarding 'id' is answered. If one specifies an 'xml:id', that would be a different matter entirely. Since, in XSL-FO, the attribute is in the default namespace (think 'fo:id'), they have nothing to do with each other.
I agree with your assumption. There seems to be absolutely no guarantee that generate-id() returns unique values across the two passes. Even worse, if the processor would implement generate-id() as a deterministic function (for example: if the id value is solely based on an index which is incremented with every element), then in both passes, generate-id() would always return something like "N0" for the root node, and the risk of collisions could become significant...
Placing the stress on the XSLT processor could offer a way out:
[in addPtr.xsl]
<!-- key for the explicit ids -->
<xsl:key
...
<xsl:template
<xsl:param
<xsl:choose>
<xsl:when
<xsl:call-template
<xsl:with-param
</xsl:template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of
</xsl:otherwise>
</xsl:choose>
</xsl:template>
...
<xsl:attribute
<xsl:call-template
</xsl:attribute>
...
Untested for performance. The mere addition of the key could be problematic, as the first call to key('idKey',...) cannot be evaluated unless the entire source document is scanned.
I keep looking at that recursive call, and wonder whether that could lead to problems. Strictly speaking, if the id starting the recursion will always be unique (by definition so), then the recursion should always stop at some point, and the path should always run over different nodes.
The depth will, in the most extreme case, be equal to the maximum number of collisions, which is the same as the number of nodes that already have an explicit id, or the size of the xsl:key map.
Assuming that the explicit ids added in the first pass adhere to the uniqueness constraint:
If, for any given node, the recursion would go through all possible collisions, then that would mean that the collision-values all refer to each other. That is, every value returned by generate-id() for a node in the key-map, is already specified as an id on another node in that same map. That can happen at most N times for N nodes with explicit ids, and it already happened once, for a node not in that map, to trigger the recursion. So, there will then be one of those N nodes for which the generated id is not yet occupied. Moreover, this most extreme case can present itself at most for one node in the document. The more collisions with nodes not in the map, the less deep the recursions will go.
> .
Agreed.
Attachment patch19Feb2009.txt has been added with description: added compiled stylesheets for improved performance in server environments (suggested by Jeremias)
I've applied the patch (2009-02-19 02:23 PST) to a new branch as discussed (with modifications). The code is now under:
I'll continue working on the code when my batteries are filled again.
Jost, thanks a lot for your work here. This is great new functionality. It will still take a bit to polish a few areas. I hope to see you become a regular contributor now that the hardest part is over. Please don't hesitate to publish follow-up patches against the branch (or trunk if you have other ideas). I'll keep the issue here open until we've adressed all the feedback, after which we'll see to merging this into trunk.
Most of the feedback has now been incorporated into the development branch. One notable exception is the discussion around replacing foi:ptr with the "id" property but I'm running out of time to work on this. Another point that I'm not entirely happy with is the fact that the enriched FO is fully buffered in a byte array before FOP starts processing. An idea here would be to build a reduced structure tree per page-sequence and attach it as such to the area tree instead of passing it to PDFDocumentHandler through the user agent. Anyway, when accessibility is disabled (the default), FOP does not suffer any performance drawbacks. So, IMO, the development branch could be merged with the Trunk. At any rate, the end-user documentation is now also in place. I've added a hopefully comprehensive list of limitations in addition to what Jost has written up.
I've been (slowly) reviewing the patch and I noticed that classes in the layoutmgr package are affected by the changes. There's no reason why it should be the case, layout has little to do with accessibility.
In fact the layout managers just pass the ptr trait over to the area tree. This calls for a more generic way of doing this. Indeed there are other properties that don't affect layout but only areas (color, z-index among others).
I'll try to see how this can be handled. Just thought I'd made a note for later.
Vincent
Note: I've been asked to look at integrating this patch into Trunk, but also to implement tagged PDF in the legacy PDFRenderer. More later.
Vincent.
(In reply to comment #21)
>.
This has now been addressed:
The number tree corresponding to the ParentTree entry in the StructTreeRoot object is invalid, as the values are directly stored in the array instead of being reference. See discussion on fop-dev:
Are images supposed to work? I've tested a simple document that contains an fo:external-graphic referring to a PNG image. The alt-text isn't read aloud by Acrobat, and the image doesn't appear in the list of tags, nor the Order tab.
table-and-caption and table-caption are not supported by FOP but they do not crash the engine
On the Accessibility branch, a file with a table-and-caption / table-caption will generate a stacktrace (NPE) because foi:ptr is missing on those elements.
the NPE is at the line
structElemType.put(ptr, structElem.get("S").toString());
structElem.get("S") returns null
it seems to be caused by FOToPDFRoleMap.mapFormattingObject(s, parent) :
the STANDARD_MAPPINGS map does not know table-and-caption and table-caption
.
(In reply to comment #27)
> .
Must be my local changes then. My local copy is getting a bit messy. I'll have another look with a fresh checkout.
But why are images handled like text, using marked-content sequences? IIUC they should be handled as PDF Objects (see "PDF Object as Content Items" in section 9.6.3 of the PDF Reference, Third Edition).
Thanks,
Vincent
(In reply to comment #28)
> But why are images handled like text, using marked-content sequences? IIUC they
> should be handled as PDF Objects (see "PDF Object as Content Items" in section
> 9.6.3 of the PDF Reference, Third Edition).
Ideally maybe, but not necessarily so IMO. See the note on page 599 of PDF 1.4: "If it is important to distinguish between multiple renditions of the same XObject on the same page, they should be accessed via marked content sequences enclosing particular invocations of the Do operator, rather than via object references." So the pattern is not illegal. FOP can reuse the same XObject multiple times on the same or on different pages.
Jost or Jeremias,
In the PDFPainter.prepareImageMCID method, there is a "fix for Acro Checker" comment. Do you have a sample FO file triggering that bug in Acrobat? I haven't been able to reproduce it.
Thanks,
Vincent
Hi Benoît,
(In reply to comment #25)
> table-and-caption and table-caption are not supported by FOP but they do not
> crash the engine
> On the Accessibility branch, a file with a table-and-caption / table-caption
> will generate a stacktrace (NPE) because foi:ptr is missing on those elements.
This has been fixed in revision 824845:
Thanks for reporting the bug,
Vincent
Separate bug (48518) has been opened about the ID discussion. Closing this one.
Attachment patch12Feb2009.txt has been added with description: PDF accessibility | https://issues.apache.org/jira/browse/FOP-1627 | CC-MAIN-2017-43 | refinedweb | 3,020 | 63.8 |
6.7. Initialization
Now that we have seen all of the data types supported by C, we can look at the subject of initialization. C allows ordinary variables, structures, unions and arrays to be given initial values in their definitions. Old C had some strange rules about this, reflecting an unwillingness by compiler writers to work too hard. The Standard has rationalized this, and now it is possible to initialize things as and when you want.
There are basically two sorts of initialization: at compile time, and at run time. Which one you get depends on the storage duration of the thing being initialized.
Objects with static duration are declared either outside
functions, or inside them with the keyword
extern or
static as part of the declaration. These can only be
initialized at compile time.
Any other object has automatic duration, and can only be initialized at run time. The two categories are mutually exclusive.
Although they are related, storage duration and linkage (see Chapter 4) are different and should not be confused.
Compile-time initialization can only be done using constant expressions; run-time initialization can be done using any expression at all. The Old C restriction, that only simple variables (not arrays, structures or unions) could be initialized at run time, has been lifted.
6.7.1. Constant expressions
There are a number of places where constant expressions must be used. The definition of what constitutes a constant expression is relatively simple.
A constant expression is evaluated by the compiler, not at
run-time. It may be used anywhere that a constant may be used. Unless it is
part of the operand of
sizeof, it may not contain any
assignment, increment or decrement operations, function calls or comma
operators; that may seem odd, but it's because
sizeof only
needs to evaluate the type of an expression, not its value.
If real numbers are evaluated at compile-time, then the Standard insists that they are evaluated with at least as much precision and range as will be used at run-time.
A more restricted form, called the integral constant
expression exists. This has integral type and only involves operands
that are integer constants, enumeration constants, character constants,
sizeof expressions and real constants that are the immediate
operands of casts. Any cast operators are only allowed to convert
arithmetic types to integral types. As with the previous note on
sizeof expressions, since they don't have to be evaluated,
just their type determined, no restrictions apply to their contents.
The arithmetic constant expression is like the integral constant expression, but allows real constants to be used and restricts the use of casts to converting one arithmetic type to another.
The address constant is a pointer to an object that has static
storage duration or a pointer to a function. You can get these by using the
& operator or through the usual conversions of array and
function names into pointers when they are used in expressions. The
operators
[],
.,
->,
& (address of) and
* (pointer dereference) as
well as casts of pointers can all be used in the expression as long as they
don't involve accessing the value of any object.
6.7.2. More initialization
The various types of constants are permitted in various places; integral
constant expressions are particularly important because they are the only
type of expression that may be used to specify the size of arrays and the
values in
case statement prefixes. The types of constants that
are permitted in initializer expressions are less restricted; you are
allowed to use: arithmetic constant expressions; null pointer or address
constants; an address constant for an object plus or minus an integral
constant expression. Of course it depends on the type of thing being
initialized whether or not a particular type of constant expression is
appropriate.
Here is an example using several initialized variables:
#include <stdio.h> #include <stdlib.h> #define NMONTHS 12 int month = 0; short month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31}; char *mnames[] ={ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; main(){ int day_count = month; for(day_count = month; day_count < NMONTHS; day_count++){ printf("%d days in %s\n", month_days[day_count], mnames[day_count]); } exit(EXIT_SUCCESS); }Example 6.14
Initializing ordinary variables is easy: put
= expression
after the variable name in a declaration, and the variable is initialized
to the value of the expression. As with all objects, whether you can use
any expression, or just a constant expression, depends on its storage
duration.
Initializing arrays is easy for one-dimensional arrays. Just put a list of the values you want, separated by commas, inside curly brackets. The example shows how to do it. If you don't give a size for the array, then the number of initializers will determine the size. If you do give a size, then there must be at most that many initializers in the list. Too many is an error, too few will just initialize the first elements of the array.
You could build up a string like this:
char str[] = {'h', 'e', 'l', 'l', 'o', 0};
but because it is so often necessary to do that, it is also permitted to use a quoted string literal to initialize an array of chars:
char str[] = "hello";
In that case, the null at the end of the string will also be included if there is room, or if no size was specified. Here are examples:
/* no room for the null */ char str[5] = "hello"; /* room for the null */ char str[6] = "hello";
The example program used string literals for a different purpose: there they were being used to initialize an array of character pointers; a very different prospect.
For structures that have automatic duration, an expression of the right type can be used to initialize them, or else a bracketed list of constant expressions must be used:
#include <stdio.h> #include <stdlib.h> struct s{ int a; char b; char *cp; }ex_s = { 1, 'a', "hello" }; main(){ struct s first = ex_s; struct s second = { 2, 'b', "byebye" }; exit(EXIT_SUCCESS); }Example 6.15
Only the first member of a union can be initialized.
If a structure or union contains unnamed members, whether unnamed bitfields or padding for alignment, they are ignored in the initialization process; they don't have to be counted when you provide the initializers for the real members of the structure.
For objects that contain sub-objects within them, there are two ways of writing the initializer. It can be written out with an initializer for each member:
which will assign
1 to
x[0].a,
2
to
x[0].e.c,
a to
x[0].e.d and
3 to
x[1].a and so on.
It is much safer to use internal braces to show what you mean, or one missed value will cause havoc.
Always fully bracket initializers—that is much the safest thing to do.
It is the same for arrays as for structures:
float y[4][3] = { {1, 3, 5}, /* y[0][0], y[0][1], y[0][2] */ {2, 4, 6}, /* y[1][0], y[1][1], y[1][2] */ {3, 5, 7} /* y[2][0], y[2][1], y[2][2] */ };Example 6.18
that gives full initialization to the first three rows of
y.
The fourth row,
y[3], is uninitialized.
Unless they have an explicit initializer, all objects with static
duration are given implicit initializers—the effect is as if the
constant
0 had been assigned to their components. This is in
fact widely used—it is an assumption made by most C programs that
external objects and internal static objects start with the value zero.
Initialization of objects with automatic duration is only guaranteed if
their compound statement is entered ‘at the top’. Jumping into the
middle of one may result in the initialization not happening—this is
often undesirable and should be avoided. It is explicitly noted by the
Standard with regard to
switch statements, where providing
initializers in declarations cannot be of any use; this is because
a declaration is not linguistically a ‘statement’ and only statements
may be labelled. As a result it is not possible for initializers in
switch statements ever to be executed, because the entry to
the block containing them must be below the declarations!
A declaration inside a function (block scope) can, using various techniques outlined in Chapter 4 and Chapter 8, be made to refer to an object that has either external or internal linkage. If you've managed to do that, and it's not likely to happen by accident, then you can't initialize the object as part of that declaration. Here is one way of trying it:
int x; /* external linkage */ main(){ extern int x = 5; /* forbidden */ }
Our test compiler didn't notice that one, either. | http://publications.gbdirect.co.uk/c_book/chapter6/initialization.html | CC-MAIN-2016-26 | refinedweb | 1,473 | 50.77 |
I'm trying to update some C++ code, I'd like to move toward a more modern code (c++11), but I still need to compile the code with some older compilers (c++03 compliant), because of supported platform constraints.
I know in C++11 compilers std::auto_ptr is deprecated, but because of the older compiler support, I can't just replace them with std::unique_ptr.
Is there a good practice to handle this "old compiler support, but start to move to C++11"?
As you noted, std::auto_ptr<> has been deprecated in C++11 (Reference).
Moving to c++11 std::unique_ptr<> is the right way, as also stated by Herb Sutter in GotW89:
-.
Please also note that C++17 is going to remove std::auto_ptr.
I think there may be different ways of solving your problem, the "right" one also depends on how your actual code is written.
A few options are:
Use boost::unique_ptr
Conditionally use auto_ptr or unique_ptr based on __cplusplus.
class Myclass {
#if __cplusplus < 201103L
std::auto_ptr m_ptr;
#else
std::unique_ptr m_ptr;
#endif
...
This will be scattered in every place where you reference auto_ptr, I don't really like it.
May be look less awkward if all your references to std::auto_ptr are already typedef'ed (just conditionally change the typedef).
Conditionally use using and aliasing to "define" auto_ptr (and reference it without std:: namespace).
#if __cplusplus < 201103L
using std::auto_ptr;
#else
template
using auto_ptr = std::unique_ptr;
#endif
Drawback: you keep using "auto_ptr", but in c++11 it means std::unique_ptr.
Really confusing...
Probably slightly better than option 2:
reverse using aliases and prefer unique_ptr name.
Wrap the std:: smart pointer (conditionally auto_ptr or unique_ptr) in your own defined template smart pointer class.
This may be cumbersome and requires search and replacement of all auto_ptr references with your new class.
Other options involve definitions inside the std:: namespace, which I think is prohibited by the standard,
or using preprocessor #define to ...ehm... "rename" unique_ptr to auto_ptr just for old C++03 compilers. | https://codedump.io/share/SX0XnVX3lVn3/1/c-stdautoptr-or-stduniqueptr-to-support-multiple-compilers-even-old-c03-compilers | CC-MAIN-2017-04 | refinedweb | 336 | 54.02 |
There are several ways that you can use Synergy/DE tools to expose WCF services, but regardless of which way you decide to create a service, the next decision you have to make is how to host it. By hosting a WCF service you expos the service and make it possible to use it from other applications. In this post I will introduce you to one way that WCF services may be hosted, via an ASP.NET web application and an IIS web server. In a later post I will show you how to host WCF services without this requirement for an IIS web server.
This is the third (this post)
- Exposing WCF Services using Synergy .NET Interop
- Self-Hosting WCF Services
- Exposing WCF services using Synergy .NET
A WCF service is simply a collection of one or more classes in an assembly, but the whole point of implementing a WCF service is to make those classes available to be used by other applications. And those applications will often be located on different networked systems from the service itself. So, in order for a WCF service to be useful, it needs to be “hosted” somewhere, and that somewhere needs to be available on a network.
There are three basic ways that WCF services can be hosted:
- Inside a Web application located on a Web server.
- Using Windows Process Activation Services (WAS). This mechanism was introduced in Windows Server 2008 and provides a mechanism for hosting WCF services without requiring a Web server.
- Services can be “self” hosted by some custom .NET application. For example, developers often host WCF services inside a Windows Service application.
In this post I will show you the basics of hosting a WCF service in an ASP.NET web application. In a future post I will go on to show how to self-host services.
Setting up basic hosting for a WCF service inside an ASP.NET Web application is very easy, but as Synergy .NET doesn’t have support for creating Web applications. You’ll have to use another .NET language, either C# or VB.NET. However, don’t worry about that too much, because there won’t actually be any code in the Web application!
- Start Visual Studio 2010 and create a new ASP.NET application:
- From the menu, select File > New > Project.
- Under Installed Templates, select Visual C# > Web > ASP.NET Empty Web Application.
- Chose the name and location for your new Web application.
- Click the OK button to create the new project.
- Add a new WCF Service to the project:
- From the menu, select Project > Add New Item.
- Under Installed Templates, select Visual C# > Web > WCF Service.
- Enter the name for your new service. The name will be part of the service endpoint URI that the client connects to, so pick something meaningful. For example, if your service allows orders to be placed then you might name the service something like OrderServices.svc.
- Click the Add button to add the new service to the project.
You will notice that three files were added to the project:
In addition to the service (.svc) file that you named, you will see two C# source files. These files were added because Visual Studio provided all of the files that you would need in order to expose a new WCF service that would be manually coded in these files. But what we’re trying to do is host a WCF service that already exists in another .NET assembly.
- Delete the two C# source files by right-clicking on each and selecting delete.
In order to expose a WCF service that exists in another assembly, the first thing we need to do is add a reference to that assembly, to make the classes it contains available within the new Web application.
- From the menu select Project > Add Reference and then select Browse.
- Locate and select the assembly containing your WCF service and add a reference to your project.
- If the assembly you selected was created using xfNetLink .NET then you will also need to add a reference to the xfnlnet.dll assembly, as is usual when using xfNetLink .NET
You’ll need to know that namespace and class name of the WCF service in your assembly. If you can’t remember this that double-click on the assembly that you just referenced and then use Object Browser to drill into the assembly and figure out the names. All that remains is to “point” the service file at your WCF service class.
- Double-click on the service (.svc) file to edit it. You should see something like this:
Edit the file as follows:
- Change Language=”C#” to Language=”Synergy”.
- Change Service=”…” to Service=”YourNamespace.YourWcfClass” (obviously replacing YourNamespace and YourWcfClass with the namespace and class name of your WCF service).
- Remove the CodeBehind=”…” item … there is no code-behind, the code is all in the other assembly.
- Save the file.
So you should now have something like this:
If your service is based on an assembly created using xfNetLink .NET then you have one final configuration step to perform. You need to tell xfNetLink .NET how to connect to xfServerPlus. You can do this by using the Synergy xfNetLink .NET Configuration Utility (look in the Windows Start Menu) to edit the new web applications Web.config file. If your xfServerPlus service is not on the same machine as your new web application then you must specify a host name or IP address, and if xfServerPlus is not using the default port (2356) then you must also specify a port number. When you’re done, the Web.config file should contain a section like this:
That’s it, you’re done. You should now have a working WCF service!
- To see if the service has really been hosted, right-click on the service (.svc) file and select View In Browser.
You should see the service home page, which will look something like this:
If you see this page then your service is up and running. By the way, the URI in your browsers address window is the URI that you would use to add a “Service Reference” to the service in a client application … but we’ll get on to that in a later post.
Of course, all we have actually done here is set up a web application to host a WCF service, but we’re using Visual Studio’s built in development web server (Cassini) to actually host the service. If you were doing this for real then you’d need to deploy your new web application onto a “real” IIS web server.
We’re not done with the subject of hosting WCF services; in fact we’ve only really scratched the surface. One step at a time!
In my next post in this series I will show you how to Expose a WCF services using Synergy .NET Interop. | https://www.synergex.com/blog/tag/synergyde-9-5/ | CC-MAIN-2020-50 | refinedweb | 1,152 | 73.47 |
Arrays.asList() converts all the elements of the array into a List. It is the easiest way to pass the elements of an array to a List; an interoperability feature between arrays and collections framework classes. Convert array to List with asList()
Following is the method signature
- static List asList(T array): It is useful to convert an array into a List. The method returns a List object with the elements of the array and further elements cannot be added to the list. Useful to have fixed size list on which add() and remove() methods do not work. Overloaded to take any data type array as parameter.
Following example on Convert array to List with asList() illustrates.
import java.util.Arrays; import java.util.List; public class ArraysAsList { public static void main(String[] args) { String stones1[] = { "diamond", "ruby", "emerald" }; System.out.println("Array stones1 elements: " + Arrays.toString(stones1)); List myList = Arrays.asList(stones1); System.out.print("\nmyList elements: " + myList); // myList.add("topaz"); // myList.remove("ruby"); } }
Output screenshot on Convert array to List with asList()
String stones1[] = { “diamond”, “ruby”, “emerald” };
System.out.println(“Array stones1 elements: ” + Arrays.toString(stones1));
A string array stones1 is created with three elements "diamond", "ruby" and "emerald" and the elements are displayed with toString() method. toString() method of Arrays class is the easiest way to display the elements of an array.
List myList = Arrays.asList(stones1);
System.out.print(“\nmyList elements: ” + myList);
To create a List object with the elements of the array stones1, the array object is passed to asList() method.
// myList.add(“topaz”);
// myList.remove(“ruby”);
The List object myList returned by asList() method is immutable. That is, it is of fixed size and further addition or removal of elements raises UnsupportedOperationException. For this reason, the above lines are placed in comments in the code.
It is nearer to addAll() of Collections. It is also possible to convert "array list elements to array".
One more program is available at "Array to ArrayList" for further reference. Comparison with array list is available at "Array vs ArrayList". | https://way2java.com/collections/converting-array-into-list-with-aslist/ | CC-MAIN-2020-50 | refinedweb | 341 | 50.63 |
Bivouac 0.1.1
a light-weight, wsgi-compliant web framework in Python
Why bivouac?
bivouac has grown out of my own efforts to build websites in Python with as thin a footprint as I can. bivouac provides a basic MVC framework inspired by Microsoft’s MVC 1.0 framework. Expect further ruminations on the topic elsewhere. In the past I suggested I would not support this project, but as I find I rely on bivouac for more of my own websites, I expect to do as much as I can to encourage adoption and support. I think we’re on to something good here!
What is bivouac?
bivouac is WSGI compliant and aims to be as webserver-agnostic as it can. Using mod_wsgi or isapi_wsgi, bivouac works well with both Apache and IIS, with NGINX being an untested likelihood. Today bivouac supports authentication and user sessions using MongoDB. Long-term look for this to become more database independent.
Currently, bivouac has a small number of dependencies:
- mod_wsgi or isapi_wsgi
- Paste & Webob
- mongodb
- PyMongo
Basic Usage
bivouac provides classes for MVC routing, controllers, models and views. Here’s a quick intro to getting a site up and running using bivouac.
For starters, create a module called app.py, or whatever you’ve specified as your WSGI entry point. Here we see a simple WSGI entry point with some boiler-plate routing. This will serve most folks needs, so feel free to start with this setup.
import bivouac application = bivouac.Router() application.add_route('/', defaults={'controller': 'default', 'action': 'index'}) application.add_route('/{controller}/', defaults={'action': 'index'}) application.add_route('/{controller}/{action}') application.add_route('/{controller}/{action}/{id}')
Next you’ll need a controller. bivouac looks for controllers within your site directory, typically in the controllers package. Your controller will inherit from bivouac.Controller. Methods decorated with @action will be treated as controller actions and return bivouac views, or any WSGI compliant, iterable structure.
import bivouac from bivouac.controller import action, noauth controller = "DefaultController" class DefaultController(bivouac.Controller): '''Default Controller. ''' def __init__(self): bivouac.Controller.__init__(self) @noauth @action def index(self, req, **vars): import views.index as View view = View.IndexView() return view
- Author: Adam A.G. Shamblin
- Download URL:
- Keywords: web mvc wsgi framework
- License: MIT
- Categories
- Package Index Owner: Adam.Shamblin
- DOAP record: Bivouac-0.1.1.xml | https://pypi.python.org/pypi/Bivouac | CC-MAIN-2016-30 | refinedweb | 385 | 61.02 |
Hi folks! [ Feel free to forward this to people/derivatives using d-i and who might be interested in joining the discussion; I intend to contact gtk maintainers anyway once we reach a consensus, so that they know how we're going to use their udebs. ] With wheezy out, I finally looked at the libgtk-3-0-udeb which has been floating around for a while, and attempted porting cdebconf to use it. It led to filing #708475[CAIRO], which means that the gtk3 udeb isn't usable until cairo is fixed (trip through NEW for that), and until gtk+3.0 is rebuilt against it. [CAIRO] I've just pushed a pu/gtk3 branch to cdebconf.git[GIT] for now, which does the following: 1. introduce gtk2gtk3.h, which is a convenience header where I've added a few wrappers to compensate for deprecated functions. (I've used a double underscore as a prefix to make those obvious.) 2. patch a few more things with #if 0/#else/#endif, since those weren't necessarily easily wrappable in the same way: some function pointers need a different signature, and that was becoming nasty. [GIT] The end result is that the graphical installer works enough to confirm that the gtk3 udeb and the to-be-introduced new cairo udeb work. And that porting cdebconf to gtk3 can happily continue (basically, the rendering and snapshotting code paths need love). I expect to update (that includes possible rewrites) the pu/gtk3 branch, and possibly upload the resulting package to the experimental distribution; but also to *not* merge it/upload to unstable at the moment. Besides code changes, a gtk3 theme is going to be appreciated once the heavy work is over (probably to be shipped from rootskel.git/src/etc). Now, question: ,--- | Do we need, or want, to keep the option of building upcoming cdebconf | releases against gtk2 once the gtk3 port finds its way to master? `--- In a nutshell that would mean: a. a few more lines to configure.ac; nothing dramatic™. b. propagating an extra define to the said wrapper, so that we define __foo(...) as foo(...) in the gtk2 case. c. dealing with the signature changes mentioned in the second point above. The last point could lead to some kind of ugly code. I didn't look into it too much, but duplicating functions entirely would be hated; and adding too many #ifdef/#else/#endif due to incompatible APIs wouldn't be loved either. But if there are convincing arguments for a dual-gtk support, I guess we could figure something out. Mraw, KiBi.
Attachment:
signature.asc
Description: Digital signature | https://lists.debian.org/debian-boot/2013/05/msg00297.html | CC-MAIN-2018-30 | refinedweb | 440 | 62.78 |
Solution :
This is an interesting problem, not because it is difficult or tricky to find an efficient solution, but there are multiple approaches and each approach is dependent on the problem definition and problem test cases. Identifying words where the space between them has been mistakenly omitted is a classic problem is text processing because this is one way by which search engines such as Google provide "Did You Mean ?" results.
Let's begin with an approach which we have seen earlier when we had explored spelling correction techniques. The idea is pretty simple. Given a string S of length m, represented as :
S = [x0, x1, x2, ..., xm-1], where xi is the character at position 'i' in the string.
Let us denote the sub-string from position i to position j as [i, j]. Then H([i, j]) = 1, if either the sub-string [i, j] is present in the valid set of words Q (our input to this problem) or it can be broken down into two or more words from the set Q. Checking whether [i, j] is present in Q is easy, but to check whether [i, j] can be broken down into two or more valid words from the set Q, we can iterate through all possible k, such that :
H[(i, j]) = 1 iff H([i, k]) = 1 and H([k + 1, j]) = 1 for any k such that i < k < j.
We can use dynamic programming to compute the values of H. The solution for a given set of words Q, are those words for which H([0, m-1]) = 1, but given the constraint of the problem that the string S must be composed of at-least two words from the set Q, it implies that there must be an index k, such that :
H([0, k]) = 1 and H([k+1, m-1]) = 1
Assuming that the average length of word is 'd', then the run-time complexity for computing H for a single word is O(d3). Thus the total run-time complexity for n words is O(nd3). Can we do better than this ?
Note that if it was required to identify all possible segmentation of the string that gives valid words from the set Q (as was required in our spelling correction problem), then this method is appropriate. But given that we need to identify whether it is composed of two or more words from the set Q, the definition changes a bit and with that we can alter our approach to reduce the time complexity.
One way is to recursively solve the problem. Let's say that for an index k, the substring [0, k] is present in Q, then recursively check whether the substring [k, n-1] is present in Q or it can be broken down into two or more strings.
i.e. define a recursive function F(s), which returns 1 if the sub-string [s, n-1] can be broken down into two or more parts, then :
F(s) = F(s + k) && [s, s + k - 1] is in Q for any k, s < k < n-1
Then the string is a valid concatenated string if F(0) = 1. We can do this using a depth first search (DFS).
For each possible starting position 's' in the string of length d, we need to search at-most 'd-s' positions for a valid word from the set Q and there are at-most O(d) starting positions in the string. Thus the time complexity of the DFS search for each string is O(d2). The total run-time complexity is O(nd2).
Can we reduce the time complexity of search if we had used a Trie data structure instead ?
Let's assume that we have constructed a prefix-tree out of all the words in the set Q. A prefix-tree is constructed in a way such that each node of the tree is associated with a character X such that X is the first character for all sub-strings in the sub-tree rooted at this node. Let's create a prefix-tree out of the following words :
['CAT', 'DOG', 'CATTLE', 'CATERPILLAR', 'DONKEY', 'DONALD', 'FOX']
A Prefix Tree
Each word in the list can be obtained by following one of the paths and concatenating the characters along that path. The green nodes represents leaf nodes, which implies that a valid word ends at this leaf node. Note that each node object holding one of the characters takes up certain memory in the RAM, and with many strings and very less number of common prefixes, the memory taken up can be large.
We can compress the above prefix tree by merging all nodes with a single child into a single node with the value for that node equal to the concatenation of the values for each of the nodes merged. Observe that the prefix tree property still holds good after this merging step.
A Compressed Prefix Tree
The prefix tree can be built efficiently by using a hash-map that maps from a key for a particular node to the node pointer object in the tree, so that we do not have to iterate over the nodes to find a node with a value that has a matching prefix with the string being inserted. The keys for the hash-map are the prefixes of the strings already in the tree.
Following is a Python class to construct a Prefix Tree :
import collections class PrefixTree(object): def __init__(self, val): self.val = val self.children = [] def add_word_to_tree(self, root, word, node_map): for pos in range(1, len(word) + 1): prefix = word[:pos] if prefix in node_map: root = node_map[prefix] else: node = PrefixTree(word[pos - 1]) root.children.append(node) node_map[prefix] = node root = node node = PrefixTree('~') root.children.append(node) node_map[word + '~'] = node def compress_tree(self, root): queue = collections.deque([root]) while len(queue) > 0: node = queue.popleft() if len(node.children) == 1 and node.children[0].val != '~': node.val += node.children[0].val new_children = [] for child in node.children: new_children += child.children node.children = new_children queue.append(node) else: for child in node.children: queue.append(child)
With 'n' strings of an average length of 'd', the tree construction complexity is O(nd).
We can do a search over the prefix-tree to check if a word is composed of two or more words in Q or not in the following way :
For example, if the word is "cattledonald", then we check whether there is a node present in the tree with the key equal to the first letter of the word. If not present then the word cannot be present in the tree. Else get to the node with the correct prefix. In this case the character 'c' is present and it takes to the node with value 'cat' in the tree.
After we find that the prefix "cat" matches, then we go into the sub-tree rooted at the node "cat". But now the word to be searched for becomes "tledonald". The prefix "cat" is a valid word. Once we find a prefix that is also a valid word, we also search the tree for the suffix i.e. "tledonald".
But we have not yet finished exploring the sub-tree rooted at "cat". We find that the node "tle" matches with a prefix for "tledonald" and so we also search the sub-tree rooted at the node "tle", but with the sub-string "donald". We recursively parse the prefix-tree in this manner.
Following is the Python code for recursively searching the Prefix Tree with concatenated words :
Time complexity of searching for concatenated words given a string of length d is O(d). Thus total time complexity for searching is O(nd).
The entire Python code is as follows :
class Solution(object): def findAllConcatenatedWordsInADict(self, words): words = [word for word in words if len(word) > 0] word_set = set(words) temp = [] for word in words: for pos in range(1, len(word)): if word[:pos] in word_set and word[pos:] in word_set: temp.append(word) break words_set = word_set.difference(set(temp)) out = [] if len(word_set) > 0: node_map, prefix_tree = collections.defaultdict(), collections.defaultdict() tree = PrefixTree('') for word in words_set: tree.add_word_to_tree(tree, word, node_map) tree.compress_tree(tree) for word in words_set: if self.is_concatenated(word, word, node_map, word_set): out.append(word) return out + temp
Note that initially we are trying to discover words that are concatenation of two words from the set of words, as it is easy and also efficient, O(nd), to find these words. Then with the remaining words, we create the prefix tree and then compress the prefix tree and then search for words with concatenation of more than two words.
Instead of finding words with concatenation of two words, before constructing the prefix tree, we can also build the prefix tree with all the words and then find the concatenated words (two or more). But there could be certain examples like :
["a", "aa", "aaa", "aaaa", "aaaaa", ...., "a"*10000]
which can be very efficiently handled with the first pass (concatenation of two words) with a best case complexity of O(n) only.
The worst case run-time complexity of the above algorithm is O(nd).
Categories: PROBLEM SOLVING
Tags: Concatenated Words, Leetcode, Prefix Tree, Shingles, Trie | http://www.stokastik.in/leetcode-concatenated-words/ | CC-MAIN-2018-47 | refinedweb | 1,556 | 68.2 |
This is a multi post series on ASP.Net MVC Portable Areas
- Part 1 – Introduction
- Part 2 – Sample Portable Area
- Part 3 – Usage of a Portable Area
- Part 4 – IoC framework support
What is a Portable Area?
A Portable Area is a set of reusable multi page functionality can be dropped into an application to provide rich functionality without having to custom build functionality that is literally the same in every application. This could be considered a plug-in or add-in type of functionality. The portable portion of this approach is that the area can be distributed as a single assembly rather than an assembly and a host of other files, like views or other html assets that need to be managed and maintained over time. By making a portable area totally self contained in a single assembly, this should allow for easier reuse and upgrades to the area. The challenge for doing something like this has been how do you allow enough control over the User Interface by the application yet still allow the actual views to be packaged with the logic.
Why Now?
There has been some discussion in the past on the MvcContrib mailing list about creating an plug-in framework and plugins but I do not think we had enough of the pieces in place to do this properly. I believe that with MVC 2 we have those missing pieces figured out. The first enabler is the inclusion of Areas into the MVC 2 feature set. This includes having the Area and Controller namespace become part of the route data which is used both for Controller/Action selection but this also flows down to the selection of a view. The second enabler is some of the work that came out of MvcContrib and the Input Builders. While implementing that feature we came up with a way to pull views from an assembly as an embedded resource. This with the ability to override the default view engine in a way that allows an application developer to place their own version of a view in a folder so that they have the option to change the view to their needs was huge. The last enabler really comes from what we have learned from all of the SOA greats and see how frameworks like nServiceBus and MassTransit have demonstrated that a messaging approach for integration can keep our concerns separated.
The other why now is that my company, Headspring, has found that in order to make our practice more successful, we need the ability to drop in some of the essentials for an application, we would prefer to do this in a binary form that is easy to upgrade and does not leave us with copy and pasted code between our various projects. We would like to see that if we learn something from one project that we have the potential to apply those learning’s to projects that are still in flight. We all prefer that rather than waiting for the next project to start so that we can apply what we have learned to the new project. This approach will be much better for us as developers and our client will benefit as well. We could take the approach of working on this in a bubble but by putting this out for the community we can learn from every else and potentially help others in the process and raise the collective bar for the industry, in our own little way.
Logical View of a Portable Area
Below is a logic view of a Portable Area. It shows how the Green block is an application. Inside the application the blocks in dark blue are framework components in ASP.Net MVC 2 and MvcContrib. These blocks provide some minimal framework support for registration view resolution and communication between the application and the portable area. The light blue blocks represent code the developer create. The code in the Portable Area is created by the Portable Area developer. The code in the application block is coded by… you guessed it. The application developer.
Thanks for the Pictures but where is the code?
The code is currently available in the MvcContrib MVC 2 Branch. You can get the latest binary from our (TeamCity/CodeBetter) build server here:
There is a sample application you can download here:
or from the code repository on GitHub: Download the source as a zip. or Fork it on GitHub. | http://lostechies.com/erichexter/2009/11/01/asp-net-mvc-portable-areas-via-mvccontrib/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%253A+LosTechies+%2528LosTechies%2529 | crawl-003 | refinedweb | 743 | 57.3 |
ldap_perror, ld_errno, ldap_result2error, ldap_errlist, ldap_err2string — LDAP protocol error handling routines
#include <ldap.h>.
Partial results only returned.
The attribute type specified does not exist in the entry.
The attribute type specified is invalid.
Filter type not supported for the specified attribute.
An attribute value specified violates some constraint (e.g., (e.g., LDAP_AUTH_SIMPLE was specified and the entry does not have a userPassword attribute).
Invalid credentials were presented (e.g., the wrong password).
The user has insufficient access to perform the operation.
The DSA is busy.
The DSA is unavailable.
The DSA is unwilling to perform the operation.
A loop was detected.
A naming violation occurred.
An object class violation occurred (e.g., a "must" attribute was missing from the entry).
The operation is not allowed on a nonleaf object.
The operation is not allowed on an RDN.
The entry already exists.
Object class modifications are not allowed.
An unknown error occurred.
This section provides a complete list of API error codes recognized by the library. Note that LDAP_SUCCESS indicates success of an API call in addition to representing the return of the LDAP 'success' resultCode.
The LDAP library can't contact the LDAP server.
Some local error occurred. This is usually a failed dynamic memory allocation.
An error was encountered encoding parameters to send to the LDAP server.
An error was encountered decoding a result from the LDAP server.
A timelimit was exceeded while waiting for a result.
The authentication method specified to ldap_bind() is not known.
An invalid filter was supplied to ldap_search() (e.g., unbalanced parentheses).
An ldap routine was called with a bad parameter.
An memory allocation (e.g., malloc(3) or other dynamic memory allocator) call failed in an ldap library routine.
Indicates the user cancelled the operation.
Indicates a connection problem.
Indicates the routine was called in a manner not supported by the library.
Indicates the control provided is unknown to the client library.
Indicates no results returned.
Indicates more results could be returned.
Indicates the library has detected a loop in its processing..
OpenLDAP Software is developed and maintained by The OpenLDAP Project <>. OpenLDAP Software is derived from University of Michigan LDAP 3.3 Release. | http://man.linuxexplore.com/htmlman3/ldap_error.3.html | CC-MAIN-2021-21 | refinedweb | 362 | 54.9 |
Kubernetes goes serverless in Kubeless
Looking for a serverless option for Kubernetes? Introducing Kubeless. This new Kubernetes-native serverless framework provides auto-scaling, API routing, and more without having to worry about the underlying infrastructure.
Kubernetes means “helmsman” in the original Greek, in order to highlight how much control it brought to users. And now, developers have even more chances to master their fate with the all new Kubeless, the Kubernetes-native serverless framework.
Leveraging Kubernetes resources, Kubeless provides auto-scaling, API routing, monitoring, troubleshooting, and more. It’s purely open source and not affiliated with any company or organization. (Bold move, Kubeless.)
Why make the switch to Kubeless?
Kubernetes is great! And so are the other open source options, fission and Funktion. There’s even OpenWhisk percolating away as an Apache Incubator project.
Kubeless stands out because it uses Custom Resource Definitions (CRD) to free you from having to write your own API services to handle the custom resource. In this case, Kubeless runs an in-cluster controller that watches these custom resources. Also, the controller launches runtimes on-demand. Helpfully, the in-cluster controller dynamically injects the functions code into the runtimes. It also makes them available over HTTP or via a PubSub mechanism.
SEE MORE: DevOps engineers think Docker, Ansible and Kubernetes are the top 3 tools to learn
Kubeless uses Kafka for an event system. A kafka setup is bundled into the Kubeless namespace for development as well.
Additionally, Kubeless uses k8s primitives. There’s no additional API server or API router/gateway. This makes it easier for Kubernetes users to switch over and leverage their existing skills into Kubeless.
Here are some other tools for this new framework:
- A UI is available, which can run locally or in-cluster.
- A severless framework plugin is also available for additional support.
The way forward
As of right now, Kubeless is still in the early stages. However, they have a detailed roadmap forward and would welcome any helping hands. Here are some of the high level features they are looking to implement:
- Add other runtimes. Currently, Kubeless supports Python, NodeJS and Ruby. We are also providing a way to use custom runtime.
- Investigate other messaging bus (e.g nats.io)
- Instrument the runtimes via Prometheus to be able to create pod autoscalers automatically (e.g use custom metrics not just CPU)
- Optimize for functions startup time
- Add distributed tracing (maybe using istio)
- Break out the triggers and runtimes
- Support additional event framework like nats.io
SEE MORE: Kubernetes 1.7: Good news for those running scale-out databases on Kubernetes
If you’re interested in Kubeless, the open source Kubernetes-native framework, it’s ready and available at GitHub! | https://jaxenter.com/kubeless-open-source-severless-kubernetes-137036.html | CC-MAIN-2020-50 | refinedweb | 451 | 58.28 |
How to handle integers in the symbolic ring?
Consider the script:
from sage.calculus.calculus import symbolic_sum x, j = SR.var('x, j') assume(abs(x)<1) M = [SR(1), x, x^2 + 1, x^3 + 3*x, x^4 + 6*x^2 + 2, x^5 + 10*x^3 + 10*x] for k in range(len(M)): p = symbolic_sum(x^j*M[k](x=j), j, 0, oo) F = p.partial_fraction() print [k], [numerator(f) for f in F.operands()]
What I get is:
[0] [1, -1] [1] [1, 1] [2] [-2, -3, -2] [3] [4, 10, 12, 6] [4] [-9, -33, -62, -60, -24] [5] [21, 111, 300, 450, 360, 120]
What I expect in the first line is
[0] [-1]
But more generally: Is there a way to get around this darned SR(1) in the first place? This problem appears over and over again and forces to be handled as a separate case. The result is often a mess, as it is the case when the above array M is created by a procedure.
Moreover this workaround does not fit well with other functions as can be seen for example from the bug above. | https://ask.sagemath.org/question/25305/how-to-handle-integers-in-the-symbolic-ring/ | CC-MAIN-2018-30 | refinedweb | 197 | 77.98 |
datomicism
interface for visualizing datomic schemas and queries
Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now!
npm install datomicism
datomicism
An interface for visualizing datomic schemas and queries. It may be easiest to watch the video to get a quick overview.
Getting started
npm install datomicism -g
start the server (defaults to port 6655)
datomicism
download latest version of datomic
start the transactor (defaults to port 4334)
./bin/transactor config/samples/free-transactor-template.properties
start the rest server (here we are starting it on port 9999)
./bin/rest -p 9999 datomicrest datomic:free://localhost:4334/
navigate to in your browser
click connect, enter
localhost for the host and
9999 for the port. If you have a db you are working with select it - otherwise create one by selecting
--new db--.
NOTE
this is an experimental prototype e.g. please do not look at the code as being anything beside a prototype. In minecraft terms this is my dirt/cobble structure I laid out to see if building the real thing would be worth it. Now I'm busy smelting the stone to start laying down the foundation in brick. However, I feel it does represent my intention fairly well so I welcome feedback re bugs/ux/features.
What is this?
I guess you could say it is a smalltalk environment for datomic? The parallels between the two seem apparent to me but perhaps the most important is "turtles all the way down" - in smalltalk this means everything is an object - in datomic everything is an entity which yields a very similar experience/potential.
Installation
sudo npm install datomicism -g
datomicism - the port defaults to 6655 but you can pass it in via -p {port}
You should now be able to navigate and see an empty workspace. If you click on connection and enter a valid ip adddress/port of a running datomic rest server you should then see a list of databases to connect to.
Workspace
This is the "desktop" (though I am attempting to avoid that metaphor) where you drag and drop various widgets. It is persistent (currently local storage but the potential to have shared workspaces is there) - meaning you can refresh and everything should be where you left it.
Toolbar
Contains the various widgets you can drag and drop onto the workspace. On the far right is the connection button which should indicate if you are currently connected or not.
Connection
This is where you set your basic datomic connection details e.g. host (ip address e.g. 127.0.0.1), port, and then select the alias/db you would like to work with. You can create a new database for a given alias from this control as well.
Minimap
Helps you visualize your viewport location in relation to the rest of the widgets you may have in the workspace. Updates in real time in relation to the widgets themselves. You can click on it to scroll to a different location.
Explorer
A list of all the widgets in the workspace. highlighting one should highlight it in the minimap and workspace. You can click the x to the right of any item in the explorer to remove it.
Widgets
Most widgets are available from the toolbar or can be accessed via the browser/other entities.
Browser
The main navigational tool. It is grouped hierarchically by namespace. A node in this list will either represent attributes for an entity or an enum. You can drag and drop any namespace or attribute to the workspace to inspect it as an entity.
Namespace
The collection of attributes for a given entity. You may not alter existing attributes but you can add new ones. Clicking the arrow to the left of an attribute reveals further details.
Enum
The enum widget is similar to namespace but only allows for adding the names of the enum members.
Entity
After the browser this is the most common way to navigate through the system. You can either type an entity id in or browse via namespace. Once you are viewing an entity (or list of entities) clicking any of the links will reveal another entity widget navigated to the relevant location.
Datom
A datom may be dragged out of any entity - the plan is to allow historical interrogation for a given "eav" tuple. Currently it just shows the details.
Transact
Allows for issuing of transactions directly. Useful for importing an entire schema/dataset.
Query
The query widget is very useful for sanity checking your queries as it will do real time schema checking to make sure the attributes you are referring to exist. It will also indicate if terms in your find clause are actually bound either in the in or where clauses. You can click any attribute in to see it in a browser. If you are utilizing input there is an experimental interface which provides inputs that correspond to the in clause. You can toggle to manual if you would like to just pass in
Rules
Useful when you want to share where clauses in many queries.
Note
Markdown based snippets - good for annotating/fluent programming style descriptions.
Sketch
Simple canvas based paint tool for when words will not suffice.
Todo
check the issues page, I should be adding known bugs and features as I find them but PLEASE contribute any bugs/features you find as well. | https://www.npmjs.org/package/datomicism | CC-MAIN-2014-15 | refinedweb | 904 | 64.61 |
I read that the constructor is like the first argument passed to the class, which makes sense to me since the parameters seem to be passed to the class via the
__init__
class NewsStory(object):
def __init__(self, guid, title, subject, summary, link):
self.guid = guid
self.title = title
self.subject = subject
self.summary = summary
self.link = link
def get_guid(self):
return self.guid
def get_title(self):
return self.title
def get_subject(self):
return self.subject
def get_summary(self):
return self.summary
def get_link(self):
return self.link
firstStory = NewsStory('Globally Unique Identifier', \
'first_title','first_subject','This is an example \
sumary','example_link@something.com')
print firstStory.get_guid() # prints Globally Unique Identifier
__init__
I see a misconception here between a constructor--constructing the object and initializing the object:
Python's use of
__new__ and
__init__?
Use
__new__when you need to control the creation of a new instance. Use
__init__when you need to control initialization of a new instance.
So we must be careful here.
I read that the constructor is like the first argument passed to the class, which makes sense to me since the parameters seem to be passed to the class via the
__init__method.
The constructor is not passed to the class, to be precise the result of the constructor (
__new__) will be the first argument for every instance method in the class or its sub-classes:
class A: def __new__(self): return 'xyz'
See what happens when you call the class (create the object):
>>> A() 'xyz' >>> type(A()) <class 'str'>
Calling the class no longer return instance of type
A, because we changed the mechanism of the constructor
__new__. Actually by doing so you alter the whole meaning of your class, not only, this is pretty much hard to decipher. It's unlikely that you'll switch the type of object during the creating time of that specific object. I hope this sentence makes sense, if not, how will it make sense in your code!
class A: def __new__(self): return 'xyz' def type_check(self): print(type(self))
Look what happens when we try to call
type_check method:
>>> a = A() >>> a 'xyz' >>> a.type_check() AttributeError: 'str' object has no attribute 'type_check'
a is not an object of class
A, so basically you don't have access to class
A anymore.
__init__ is used to initialize the object's state. Instead of calling methods that will initialize the object's members after it's created,
__init__ solves this issue by initializing the object's members during creation time, so if you have a member called
name inside a class and you want to initialize
name when you create the class instead of calling an extra method
init_name('name'), you would certainly use
__init__ for this purpose.
So when I 'call' the class, I pass it the parameters from the
__init__method?
When you call the class, you pass the parameters (to)
__init__ method?
Whatever arguments you pass the class, all the parameters will be passed to
__init__ with one additional parameter added automatically for you which is the implied object usually called
self (the instance itself) that will be passed always as the left-most argument by Python automatically:
class A: def __init__(self, a, b): self.a = a self.b = b
A( 34, 35) self.a = 34 | | | | | | self.b = 35 init(self, a, b) | | | The instance that you created by calling A() | https://codedump.io/share/EmWaY58vumD4/1/is-a-constructor-init-necessary-for-a-class-in-python | CC-MAIN-2017-13 | refinedweb | 562 | 63.7 |
Earlier...
Thankfully Scott Mitchell kindly offered to help write them instead, and has put together an awesome data access tutorial series that is now online here under the "Learn" tab of the website. 15 of the data tutorial segments can now be read online, with another 25 still on their way. Each of the tutorials is available in both VB and C#, and in both HTML and PDF format. Full source code is also provided for all samples.
The data series begins by creating a DAL using the built-in data TableAdapter designer in Visual Web Developer Express and Visual Studio. Scott then create a business class layer that encapsulates the DAL and adds additional business logic and validation to it. All of the samples then use the ASP.NET 2.0 ObjectDataSource control to bind against the business class layer, and show how to perform common binding operations against it. Note that if you want you can easily substitute the table adapter DAL for your own DAL implementation with the business class layer -- all of the 39 other data tutorials will then work against it the same way.
The list of currently published data articles in the series includes:
Introduction Articles
Basic ASP.NET Data Reporting
Master/Detail Reporting
Custom Formatting
Check out all of these great tutorials on the site here.
Over the next few weeks 25+ more tutorials will appear covering paging, sorting, editing, deleting, validation and much, much more.
Hope this helps,
Scott
15 Great ASP.NET 2.0 Data Tutorials Published Scott Guthrie blogged it, Scott Mitchell wrote...
Scott,
I have read many of your articles and would like to say thank you for all of the education you have provided me.
I am a ASP.NET C# and VB.NET developer and I am curious about developing the different layers? I have been developing with .NET since 1.1 and have always developed sites utillizing NameSpacing for the different layers
CompanyName.AppName.Layer
Solution = MyBiz.MyApp
MyBiz.MyApp.WebUi
MyBiz.MyApp.Data
MyBiz.MyApp.Core
MyBiz.MyApp.Rules
etc. etc.
Do you still recommend using this technique or is it over engineering the software?
Hi Moojjoo,
For large projects I think separating our your functionality into namespaces like that makes a lot of sense. It helps keep things organized and logical, and so is a good best practice.
Hi Scott,
Since ADO.NET 2.0 has already come up with abstract classes like DBCommand and DBconnection I would like to see some examples on abstract and Factory Patterns
Scott,
These tutorials are the best I have come across when researching ASP.NET 2.0's new features. Have found them really easy to understand and follow. Awesome!
Just wondering when we can expect the remaining tutorials to be posted. Keen to complete the picture on updating the database, concurrency issues, etc.
Cheers,
Dan.
Hi Dan,
The next set should come out either later this week or early next week. We are looking to release them in chunks -- about every 2 weeks from now on.
This is excellent. Please continue the good work.
Hi Scott,
These tutorials are great and enable the developpers to focalize on the real business process.
But, would you recommend this kind of architecture (GridView / BLL / DAL with typed dataset) in an B2C Web apllication like e-commerce with several thousands users connected at the same time ?
Even, would you only recommend a DAL with typed dataset in that conditions ?
Thanks for your blog.
Hi DDD,
Yep -- this approach should work well in a B2C scenario. It will scale very well.
I'm working from the second tutorial at to create a strongly-typed DAL, wrapped by BLL classes.
However, I'd like to keep both the DataSet itself and the BLL classes inside their own class libraries instead of the website's App_Code directory, since, well, they have nothing to do with presentation, which is what the website is.
I'm now getting problems entering the dataset designer in VS - it can't find Web.config to find the connectionstring it used to be able to use when it was in App_Code. I can't find _anywhere_ to set this up as a property.
I've tried messing with the XML of the dataset directly, to point its ConnectionString/ConnectionStrings property at what I'm using to encapsulate my configuration; a roll-my-own static Config class (this is a method I've used in the past back in .NET 1.1; I don't know whether it's still a good idea these days). I couldn't get this to work; the designer kept telling me the XML was now badly formed (but without telling me why or where).
I read that it should be possible to override the InitConnection event in the dataset, to programmatically set it to my Config.ConnectionString property; I haven't tried that out yet, because I read at the same time that even if that worked, the designer wouldn't pick it up...
Is there any way to do what I'm trying, or am I going to be forced to stick the frigging thing back in App_Code? If I'm forced to do that, how is it re-usable, if I subsequently want to use the same logic and classes in, say, a different presentation (eg WinForms) app?
I can't believe this sort of thing didn't occur to you guys, so I have to assume I'm missing something (probably something ridiculously obvious, to be honest); can you give me a hint, please?
Hi Peter,
When a DataSet is used within a class library or Windows client project, the connection-string is stored within an App.Config file. The format of this file is the same as Web.config -- and so when you compile the assembly and reference it from a web app you just want to make sure the connectionstring section in the web.config file has the same values as the one in app.config.
My guess is that the problems you are running into have something to-do with porting existing dataset code form the app_code folder to this class library. Have you tried creating a new dataset class in a class library to sanity-check that that is working?
Thanks,
Hey Scott,
This section on tutorials for data usage is great, but I'm looking for some more information on WHY you would use certain things - I guess more from a design perspective.
I've always used Datareaders in my applications for example. Currently, I used them to load up a custom valueobject in the DAL, and pass that back to be used as an ObjectDataSource. I've alwyas read and believed this is better from a performance perspective. However, stongly-typed datasets may make my life simpler from a development side.
I guess what I'm looking for are architecture/application design decisions on when to use what. Patterns/best practices /pros and cons etc for each one. I've been to Microsoft's patterns and practices site, and use things like the enterprise library, but haven't found any definitive "use this or use that" in certain scenarios comparisons. I'm probably missing it somewhere, since it seems to me like a common question. Any help or thoughts would be appreciated.
Thx
Hi Terence,
Sorry for the delay in getting back to you on this (I'm just catching up on comments now).
The reason those two fields aren't being displayed is because they probably aren't visible on the DetailsView. In cases like those, you want to explictly add their column names to the DataKeyNames collection -- which will cause the values to be preserved, and enable the DataEntityObject to be populated with them when the update occurs.
Hi Yuval,
The Settings class should check the web.config file first, and then only fall back to use the default one used at development time if that value isn't there.
If you aren't seeing this behavior, can you zip up a simple sample that shows the problem and send it to me? I'll then loop some folks in.
I suspect the problem you are having might be that you don't have the exact same connectionstring name in your app.config file and web.config file for the web application.
Yes, it was indeed a discrepancy in the names of the connection strings.
I guess even while writing my comment, I did not realize that in the Web.config I used the name given to the TableAdapter wizard, which did not have the leading "Data.Properties.Settings" part in it.
Thanks!
Yuval
This page lists some of the more popular “ASP.NET 2.0 Tips, Tricks, Recipes and Gotchas”
Hi George,
Unfortunately I don't know of any formal case-studies that have been done yet on this.
Sorry!
Hi Steven,
There are a couple of ways you could do this. Probably the easiest would be to just instantiate your data access code or component directly, rather than using an ObjectDataSource to call it. This way you can do whatever you want with the return value result.
Hi Todd,
If you can send me email (scottgu@microsoft.com) I can try and put you in touch with someone who can help.
Hi Earl,
Here is a pointer to a great set of tutorials that show how to split the DAL and BLL into two separate classes:
You should be able to create two class library projects and split up the work across them (just have the BLL library reference the DAL library).
What you'll then want to-do is to make sure the web.config file inside your web application has the same connection string value as in the app.config file of your DAL library. That way it will resolve the connection string reference correctly at runtime.
What if you use the VS2005 designer to create all of your tableAdapters and tables, and then you need to change the data-access methodology so that you use the DABB provided via the Enterprise Library? Is a developer required to edit the generated code (that would most likely get overwritten if the IDE is used to make any changes?)? Is there an easy/global way to make this change?
please help me to find the solution
I'm developing an order form which have order header and order detail like the Northwind database.
I use the textbox to capture the user values for Order header. As for detail, I use DetailView for insert and update record, and gridview is use to display order details.
An a submit button to save all records to the server.
As we all know the Add and update features In detailview will update the database once user click insert or update. It is a good features but the header is not save yet.
How should I handle this?
Please advice.
could you tell me, why
project>add new item>dataset are different in windows forms and web site projects, but have the same extension? is it possible to use in web site windows form's xsd dataset and vice versa? where to find more info?
Hi Gierdrius,
The .XSD files can be used both in Web Application Projects and WinForms project interchangably.
The .XSD files are slightly different between web site projects and winforms projects, though, and need to be updated in order to be shared.
it is fine.
i want some more advanced material
I don't know how I misssed putting this one in on Wednesday, but here it is. Building a Grouping | http://weblogs.asp.net/scottgu/archive/2006/06/22/454436.aspx | crawl-002 | refinedweb | 1,956 | 63.7 |
Hey again,
I'm having another problem unfortunately. We were asked to create a tree that has binary tree properties as well as max heap property.
(take A(7),C(8) and B(3) ; the tree should be so that the it should alphabetically represent a binary tree and numerically represent a heap)
I tried to create a treap but didn't succeed. so I thought that I'd create a priority queue and sort the items numerically and then remove them one by one and add to the tree, which will sort them in alphabetical order (The best I could come up with).
Now the problem is with the priority queue, it gives me an "operator < cannot be applied to int, java.lang,string " error msg.
public class PriorityQueue { public String createString(int item, String str) { String space, priort; priort = Integer.toString(item); space = " "; totl = str + space + priort; return totl; } public int insertFirst(int item, String keys) { String str = createString(item, keys); insert(str, item); } public void insert(String str, int item) { int i; if (nItems == 0) { queArray[nItems++] = str; // insert at 0 } else { for (i = nItems - 1; i >= 0; i--) { if (item < queArray[i]) { // the error appears here queArray[i + 1] = queArray[i]; } else { break; } } queArray[i + 1] = str; nItems++; } (nItems > 0) } public void EmptyQueque() { while (!isEmpty()) { remove(); } } public void remove() { if ((!isEmpty())) { while (!isEmpty()) { String str = queArray[--nItems]; System.out.println(str + " "); } } public static void main(String[] args) { PriorityQueue thePQ = new PriorityQueue(100); thePQ.insertFirst(3, "H"); thePQ.insertFirst(10, "M"); thePQ.insertFirst(2, "O"); thePQ.insertFirst(5, "Hfsh"); thePQ.remove(); } }
I wanted to have the createString method because it would be easier for me to just remove items and send it to the tree (is there another method?).
I understand that you can't compare int with the string inside the array but I'm really stuck here and haven't got any ideas.
Is there a way to add a string and integer in to a two-dimensional array or something?
Sorry about the long boring explanation, and thanx for taking the time to read it.
Any help will be much appreciated. | https://www.daniweb.com/programming/software-development/threads/338107/operator-cannot-be-applied-to-int-java-lang-string | CC-MAIN-2017-26 | refinedweb | 357 | 63.8 |
After upgrading to Java 7, I've noticed some applications fail after about 50 days f (for instance May 8 till June 27). This is suspiciously close to 2 ^ 32 -1 milliseconds:
Jun 27, 2014 9:24:47 AM org.apache.catalina.core.StandardServer await
SEVERE: StandardServer.await: accept:
java.net.SocketTimeoutException: Accept timed out.apache.catalina.core.StandardServer.await(StandardServer.java:431)
at org.apache.catalina.startup.Catalina.await(Catalina.java:676)
at org.apache.catalina.startup.Catalina.start(Catalina.java:6.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jun 27, 2014 9:24:47 AM org.apache.coyote.http11.Http11AprProtocol pause
INFO: Pausing Coyote HTTP/1.1 on http-51080
Jun 27, 2014 9:24:47 AM org.apache.coyote.ajp.AjpAprProtocol pause
INFO: Pausing Coyote AJP/1.3 on ajp-51009
Jun 27, 2014 9:24:48 AM org.apache.catalina.core.StandardService stop
INFO: Stopping service Catalina
After this, the application is no longer listening.
I suspect this may be due to a change in behavior in Java., 1, InetAddress.getByName("localhost")).accept()'
File contains:
2212 bind(47, {sa_family=AF_INET6, sin6_port=htons(60001), inet_pton(AF_INET6, "::ffff:127.0.0.1", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, 28) = 0
2212 listen(47, 1) = 0
2212 poll([{fd=47, events=POLLIN|POLLERR}], 1, 4294967295 <unfinished ...>
$ $JAVA_HOME/bin/java -version
java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)
2661 bind(46, {sa_family=AF_INET6, sin6_port=htons(60001), inet_pton(AF_INET6, "::ffff:127.0.0.1", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, 28) = 0
2661 listen(46, 1) = 0
2661 accept(46, <unfinished ...>
While java6 calls accept(), java7 first waits for an event on the socket with poll(). However, it uses a timeout of 4294967295 milliseconds.
Hmm. My initial impression is that that is a JRE bug. I've contacted someone at Oracle (see the dev list) who has been helpful in pointing us in the right direction to report bugs. Keep an eye on the dev list for progress on that.
However, I can't repeat the results you report. When I run strace on the same Java version as you are using, I see a call to poll with a timeout of -1 which I am assuming is an infinite timeout.
You'll need to provide enough information about your environment to enable us (and Oracle) to repeat this otherwise this is going to get resolved as WORKSFORME.
I tested this on Ubuntu Trusty amd64. I can also reproduce on my home machine, which runas arch (amd64).
You can try this Vagrantfile:
Vagrant.configure('2') do |config|
config.vm.box = "ubuntu/trusty64"
provision_script = <<-eos
cat > ~vagrant/run-test << eod
#!/bin/bash
# only one version of Java installed; no need to set JAVA_HOME
# so Groovy picks the correct one
aptitude install -y oracle-java7-installer groovy
java -version
strace -f -o /tmp/hh groovy -e 'new ServerSocket(60001, 1, InetAddress.getByName("localhost")).accept()'
eod
chmod +x ~vagrant/run-test
apt-get install -y python-software-properties strace vim
add-apt-repository -y ppa:webupd8team/java
apt-get update
eos
config.vm.provision "shell", inline: provision_script
end
after ssh'ing, run sudo ./run-test, accept the license and then Ctrl+C. You can then instpect /tmp/hh
The strace output may actually be a bug in strace because poll() takes a signed int as timeout; it would seem strace is interpreting the value as an unsigned int. Indeed:
$ cat a.c && gcc a.c && strace ./a.out
#include <poll.h>
#include <stdio.h>
void main() {
struct pollfd fd = { .fd = fileno(stdin), .events = POLLIN };
int timeout = -1;
poll(&fd, 1, timeout);
}
execve("./a.out", ["./a.out"], [/* 57 vars */]) = 0
brk(0) = 0xeb5000
(...)
poll([{fd=0, events=POLLIN}], 1, 4294967295^CProcess 6565 detached
That leaves me (short of a bug in glibc or the kernel) with no explanation for the exception I got, which takes quite a while to reproduce, though if poll doesn't use the monotonic clock, there may be an faster way. I'll check tomorrow.
A quick observation: the poll syscall used to take a long, and now takes an int. Maybe strace hasn't been updated yet:
I was testing on Ubuntu Precise. After updating to Trusty I see the same value as you of 4294967295. That, at least, explains why we were seeing different values.
I've looked through both the Tomcat code and the Java 7 code and I don't see anything wrong (although I am no C/C++ expert). Neither do I see anything that explain the behaviour you are seeing.
I think the next steps are to see if you can reproduce this issue with a test case that doesn't take ~50 days to run.
Javadoc for ServerSocket.accept() says that SocketTimeoutException can be thrown by the method "if a timeout was previously set with setSoTimeout". [1]
[1]
BTW,
Javadoc for ServerSocket.setSoTimeout() says that to set an infinite timeout one uses the value of "0". Is somebody confusing '0' and '-1'?
I think the javadoc for ServerSocket.accept() implies that the default timeout is infinite. So I think it is a JRE bug.
In general it makes some sense to protect against this. A timeout is not a "receiving a valid shutdown command" event, and encountering a timeout does not make the server socket an invalid one, so we should be able to continue.
(In reply to Konstantin Kolinko from comment #6)
> BTW,
> Javadoc for ServerSocket.setSoTimeout() says that to set an infinite timeout
> one uses the value of "0". Is somebody confusing '0' and '-1'?
Not that I can see having looked at the JRE code.
> I think the javadoc for ServerSocket.accept() implies that the default
> timeout is infinite. So I think it is a JRE bug.
That is a possibility, but having looked at the JRE code, I don't see where the problem is.
> In general it makes some sense to protect against this. A timeout is not a
> "receiving a valid shutdown command" event, and encountering a timeout does
> not make the server socket an invalid one, so we should be able to continue.
Agreed. There is no reason I can think of that accept should time out so we can certiainly add some protection against this issue here. We can probably add some useful debug info as well.
Note that the protection and debug info is going to go into Tomcat 8. It would help a lot if you could upgrade at least one system experiencing this error to Tomcat 8.
Workaround added to 8.0.x for 8.0.10 onwards. If the timout occurs a warning is logged that reports how long accept was blocking for before the timeout.
The workaround and simple debug code was pretty simple so I have backported it to 7.0.x (it will be in 7.0.55 onwards) and proposed if for 6.0.x.
Work around added to 6.0.x for 6.0.42 onwards.
is this fix available in tomcat 7.0.50? I am getting this error in jdk1.7 64 bit tomcat 7.0.50
(In reply to fach hoch from comment #12)
> is this fix available in tomcat 7.0.50?
No, it's in 7.0.55, as stated in comment #10. | https://bz.apache.org/bugzilla/show_bug.cgi?id=56684 | CC-MAIN-2017-43 | refinedweb | 1,237 | 68.77 |
This is the implementation fo the vertex for the coupling of three standard Model electroweak bosons. More...
#include <SMWWWVertex.h>
This is the implementation fo the vertex for the coupling of three standard Model electroweak bosons.
Definition at line 29 of file SMWWWVertex.h.
Make a simple clone of this object.
Implements ThePEG::InterfacedBase.
Definition at line 81 of file SMWWWVertex.h..
Definition at line 87 of file SMWWWVertex.h.
Function used to read in object persistently.
Function used to write out object persistently.
Calculate the couplings.
Implements ThePEG::Helicity::VVVVertex.
Storage of the couplings.
The factor for the
vertex.
Definition at line 122 of file SMWWWVertex.h. | https://herwig.hepforge.org/doxygen/classHerwig_1_1SMWWWVertex.html | CC-MAIN-2019-30 | refinedweb | 108 | 54.59 |
Concrete Class in Java
Last modified: October 18, 2018
If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen
1. Introduction
In this quick guide, we’ll discuss the term “concrete class” in Java.
First, we’ll define the term. Then, we’ll see how it’s different from interfaces and abstract classes.
2. What is a Concrete Class?
A concrete class is a class that we can create an instance of, using the new keyword.
In other words, it’s a full implementation of its blueprint. A concrete class is complete.
Imagine, for example, a Car class:
public class Car { public String honk() { return "beep!"; } public String drive() { return "vroom"; } }
Because all of its methods are implemented, we call it a concrete class, and we can instantiate it:
Car car = new Car();
Some examples of concrete classes from the JDK are HashMap, HashSet, ArrayList, and LinkedList.
3. Java Abstraction vs. Concrete Classes
Not all Java types implement all their methods, though. This flexibility, also called abstraction, allows us to think in more general terms about the domain we’re trying to model.
In Java, we can achieve abstraction using interfaces and abstract classes.
Let’s get a better look at concrete classes by comparing them to these others.
3.1. Interfaces
An interface is a blueprint for a class. Or, in other words, its a collection of unimplemented method signatures:
interface Driveable { void honk(); void drive(); }
Note that it uses the interface keyword instead of class.
Because Driveable has unimplemented methods, we can’t instantiate it with the new keyword.
But, concrete classes like Car can implement these methods.
The JDK provides a number of interfaces like Map, List, and Set.
3.2. Abstract Classes
An abstract class is a class that has unimplemented methods, though it can actually have both:
public abstract class Vehicle { public abstract String honk(); public String drive() { return "zoom"; } }
Note that we mark abstract classes with the keyword abstract.
Again, since Vehicle has an unimplemented method, honk, we won’t be able to use the new keyword.
Some examples of abstract classes from the JDK are AbstractMap and AbstractList.
3.3. Concrete Classes
In contrast, concrete classes don’t have any unimplemented methods. Whether the implementations are inherited or not, so long as each method has an implementation, the class is concrete.
Concrete classes can be as simple as our Car example earlier. They can also implement interfaces and extend abstract classes:
public class FancyCar extends Vehicle implements Driveable { public String honk() { return "beep"; } }
The FancyCar class provides an implementation for honk and it inherits the implementation of drive from Vehicle.
As such, it has no unimplemented methods. Therefore, we can create a FancyCar class instance with the new keyword.
FancyCar car = new FancyCar();
Or, simply put, all classes which are not abstract, we can call concrete classes.
4. Summary
In this short tutorial, we learned about concrete classes and their specifications.
Additionally, we showed the differences between interfaces and concrete and abstract classes. | https://www.baeldung.com/java-concrete-class | CC-MAIN-2019-22 | refinedweb | 532 | 55.03 |
:
The Lightroom team wanted to let the community know that we’re investigating some critical performance and crasher bugs, and will be issuing an update shortly to address them.
note – Lightroom 2015.2.1 / 6.2.1 has been release to address the critical performance and crasher bugs. Please update if you have been running into issues with performance and crashes in 2015.2
If you are experiencing crashing or slowdowns, please try the following:
- Go to Lightroom > Preferences.
- Click on the General tab
- Uncheck “Show ‘Add Photos’ Screen”
- Restart Lightroom
I think it’s important to provide some context to why we made changes to Import. Over the years we’ve done extensive studies of customers interested in Lightroom. The studies have been comprised of people passionate about photography and who use their cameras as a creative outlet. In short, their motivations share the same motivations as people who already love Lightroom.
We visited them in their homes, and asked them to install, launch and use Lightroom. Since this was their first interaction with Lightroom, we were interested in observing specifically where they encountered obstacles, and therefore where we needed to focus our attention...
Please keep the feedback coming!
Previous Import
Current Import
from the feedback here and in the forum i wonder what people took part in this study?
mobile user (selfie crowd) who don´t know what a folder is or working pros?
because the overal response is VERY VERY negativ….. there is no way around it.
show me 1 positiv comment and i show you 50 negativ comments about this new import dialog!
instead of justifing that imho stupid new import dialog you should listen to your customers!!
Totally agree with you Tanja, Adobe have ruined Import and dumbed it down too.
They say: “Keeping the existing Import experience isn’t an option” so I think they may find some customers saying that to keep paying Adobe for removing functionality isn’t an option and they will move to Capture One, and maybe if the excellent Affinity Photo come up with a DAM software in a year or two I and probably many many more will be off like a shot. Then it’s goodbye Adobe and good riddance.
If offering the old import set up is not an option for Adobe what will they offer us experienced users?
It’s not that so many people are complaining because they don’t like charge per se; we’re complaining because the change is counter– productive.
Surely it is not beyond the wit of Adobe to rethink how the Move, Rename, Destination Folder check etc–the items we miss so much– could be incorporated as an option for experienced users. Keep the new simpler interface AND offer a more comprehensive interface for experienced users, perhaps warning newbies they shouldn’t try this at home until they have used 6.2.1…for six months or imported 1000 photos which ever comes later
I agree. A simple and advanced import dialog option is called for. Why insult your experienced users by dumbing down the import dialog for the sake of new users? It doesn’t make sense. Get a clue, guys.
I agree. having an option would be nice. I can’t stand the new import as well.
I totally agree. Adobe has now given us “LIGHTROOM FOR DUMMIES.” Time to look for alternatives to LR for those wanting to graduate from kindergarten. Any suggestions from someone who has made the switch?
Is there any way to reverse and update to go back to the previous version? This new version is unusable. I’ve been using Lightroom from version 1 and now feel it may be time to go elsewhere.
Instructions for installing the 2015.1.1/6.1.1 update:
Thanks!
I agree 100% with this comment!
The changes made for “new” users should not blow up the workflow for those who have been feeding your coffer’s for years. Go ahead and have a simplified interface for importing, no problem, but don’t take away features many of us use overtime we import photos!
Good to see a quick response, but …..
I am making arrangements to do all of my file handling activity outside of Lightroom, where I can control the process. I have a complex folder and file structure, but will have the transfer from my cards to disk completely automated outside of Lightroom.
My import routine will consist of dragging my files onto the Lightroom grid, apply default develop and metadata pre-sets. Occasionally, I may need to synch a folder. QED.
I can only test this obviously on Lr 6.1 as I will not be installing Lr 6.2.
You are lucky… I just reinstalled my pc and the only option I have is to download the new 6.2 version, which is almost unusable on windows 7 and windows 10.
Do someone know how to get the previous 6.1 version without looking for a cracked version on the internet?
See this post. You can roll back to the prior 6.1.1 update until things are reverted and corrected:
I agree the previous Import process was unintuitive. It was powerful, and that made it hard to understand. I suspect it also felt to a new user like they weren’t totally sure what was happening. (Copy? Move? Add?)
Of course that power made it valuable to people who have been using LR for many years and are familiar with it, and appreciate all those options. Experienced users had a system that worked, and Adobe went and changed it.
I don’t think those options are gone, but they are in different places and hidden away by default. This, and the more “friendly” start screen of Import, I think are the majority of negative views.
This is such a common change management story you could repeat it for many products around the world.
To experienced users, please try and get used to the new interface, as the more Lightroom users there are – new and unfamiliar users – the more licenses Adobe sells and the more new features and development Lightroom gets. Whether the direction of this is something you agree with or not is another topic.
To Adobe, perhaps a heads up next time of upcoming changes would have helped not alienate your experienced users. Even a consultation process of “How do we make this easier for new users?” that experienced users could chip in on, whether their opinions were taken on board or not. Sometimes simply being heard is more important than having changes.
I like that LR’s interface is up for evolution and hopefully future UI modifications can have slightly better change management around them.
touché!!
I do appreciate many aspects of the redesign, and I am on board with the direction of making this important process easier for beginners (though I am in favor of a solution that serves experienced users well also.) Unfortunately, Aidan, you are not correct – complaints stem mostly from features having been removed entirely, including some that are important for beginners.
I totally agree with your post. Adobe is doing a very silly thing by changing a system that thousands of users all over the world is used to and loves, just in order to “dumbify” their product to newbies. We don’t need Adobe to do this. Picasa and iPhoto is already there for those users.
Aiden
The Move option is gone. It’s not “hidden in a default window”. I need it. One of my workflows is broken without it.
…and workflow is the issue!
I agree with much of what you say; however, Adobe should provide an option to allow users to CHOOSE which interface they wish to use. Microsoft has used this technique many times in their Office products so experienced users could CHOOSE which interface they used. Frankly, this new user interface insults experienced LR users who depend on LR room for their productivity, etc. and to say there is NO going back is simply arrogant!
If they were honestly showing concern for new users’ confusion with the import screen and if they really cared about long time users with established workflows, then they could have easily supplied the traditional advanced import screen as well as an new streamlined import screen. Heck they could have recognized that the user was updating an older version and defaulted to the old import screen, while defaulting to the new import screen for new installations.
This update and Adobe’s response above are bogus and they should simply apologize and return the old functionality to those who need it. I am already looking for LR alternatives. Does anyone have suggestions?
If they want to make a simplified import the default, then fine: but you can’t remove the power features for those of us who are experienced and rely on many of those import features. It’s a horrific update that honestly has me questioning my CC subscription. I also own a license for Capture One, and I use it on occasions. The quality is great, but to be honest, the thing that keeps LR as my primary is the import and cataloging functions, and if you start screwing with that, you start making my desire to stay using Adobe diminish.
Adobe needs to reinstate the classic import immediately, and if they want, have it as an option, or as an ‘advanced’ mode, if they want to keep the simple interface for new users. There’s no reason to remove features for simplification. Just give us an option!
There are ways to improve the novice experience without crippling features that more experienced users have come to depend on.
Hear! Hear! Well said.
“Since this was their first interaction with Lightroom, we were interested…….”
1. Most new users to Lightroom do not grasp the fundamental concept that Lightroom is structured around a database, as opposed to a file centric app such as Photoshop, Word or Excel.
2. Adobe made the first fundamental mistake with the title of “Import” on day one.
3. Dumbing down the import process is not going to improve the concept of a database to new users of Lightroom and in the interim, your existing customers suffer.
Yes, been doing photoshop since CS2. I now have CC.
I installed LR just recently so as to tether import which I need for a large project. I have tried it several times before, but it is totally confusing with the data base concept. I also lost hundreds of raw files cleaning out old versions.
Why do I have to work so hard when PS and Bridge work with the same or better functionality. You do know know there is a function in Bridge to apply the last conversion to hundreds of new files? It is under edit menu. Just go have coffee and let the computer work & it takes no more time than LR. I have better image control in ACR & PS. I do not lose files as I can keep the same file structure I have used for a decade.
The image processor does a fine job of resizing, running an action, converting to JPEG. I go for second coffee at this stage. It really is as fast a LR
I honestly can not see an advantage to LR except for tether for a church directory project.
I think I understand it, but just plain do not like it.
Well, at least for me on a Macbook Pro Retina, Mid 1025, i7@2.5GHz, 16GB Memory, 512GB SSD, Lightroom has become completely unusable. It is so unusable that I’ve not even seen the new import dialog yet.
The program behaves completely erratic:
Scrollbars in the side panels stop reacting to the scroll wheel of my Logitech USB mouse but still reacht on scrolling via the touchpad or via grabbing and dragging the scrllbar. Or sometimes not.
I open an image from the grid, click into it to bring it to 1:1, click again out, repeat a few times, and suddenly clicking into the image to zoom to 1:1 does not center the image around the click any more, the navigator does not work any more and I can’t drag the image around. Once in that state, clicking throuch images in the grid updates the image highlight in the grid and the image on the secondary display, but it does not update the panels (Navigator, image data like Title or Filename on the right panel, …)
Close LR CC 2015.2, open it again, repeat. It’s completely impossible to do any work. I guess I’ll have to revert to 2015.1.
On the feature side: I see that you’re looking for new customers and want to please them, but forget about taking features away from your professional or serious amateur users. There is no way to drive people away faster, no way to destory the biggest customer base more securely.
Forget about the changes to import. People rely on the way things used to work. Their workflows rely on it, their productivity relies on it and for many their income depends on productivity. Every feature you’ve removed is relied upon by someone. You can’t take that away. That’s a big, big no-go. Bigger companies than Adobe have failed for their long-shown disregard for their customers.
If you really, really want the new dialog, make it an alternative and support the old one ad infinitum.
All in all this upgrade was my first since Lightroom 3 that caused any problems at all. I’ve always praised Adobe as a company that knows how to create stable work environments. At least on the CS side. Flash is another thing 🙂
Anyway. This time it was devastating. Probably the worst upgrade I’ve ever seen for any kind of software. It reduced a stable workhorse to complete garbage. Please fix it. Soon. I rely on it and I pay for it.
Couldn’t agree more!
Well said.
People often fear change. But sadly, all too often companies make change for no good reason.
The latter seems to be the major issue here.
The changes could have been done in a less intrusive manner that would both simplify the UI and keep the workflow for the loyal customers who are very familiar with the old one. At the very least bring up a notice for those who have upgraded (not needed if a first time install). I honestly thought I somehow triggered the wrong software and made multiple attempts to figure out what I was doing wrong. This is NOT funny.
First impression:
– Giant check boxes obliterate dimmed images images so much that I cannot determine which ones I want.
Honestly! Who thought that was an improvement by any stretch of the imagination!?!?!
– The “Select All” button state is inconsistent and does not match actual photo state. BUG or just lack of usability testing?
– is it just me or has most of the text been made smaller (but with extra space between lines) for no apparent reason?
– default wording in text fields (i.e. keywords and metadata) is so dark and small that you cannot read it.
– the displayed portion of the Destination folder is so small that I’m not even sure which folder I have selected.
I worked through the new UI in a few minutes, but I honestly am not sure I have all settings correct and consistent to how they were in the past. Why were my old settings NOT brought forward in a consistent manner?!?!!?
The advanced UI is similar to the old one, but you really spit in the face of your current customers!
Why not allowing a parametrized interface
basic with few options and full with all options from previous version
several software allow to do so like DXO optics pro
So, in streamlining the workflow Adobe decided to remove the auto-eject of the SD card on Mac.
How is that streamlining the workflow.
Now I have remember to manually eject (by going out of Lightroom) before pulling the card from the slot,
In a fast-paced work environment where I may have minimally trained assistants importing photos, this is disruptive, confusing, error prone, and potentially damaging to the data!
Again I have to ask, Who thought that was an improvement by any stretch of the imagination!?!?!
Well it’s streamlined for Adobe’s programmers, who no longer have to have code that works only on the Mac for that feature.
I totally agree that the Previous import dialog was difficult for beginners…
But the change in Lightroom 6.2, is not good enough to fix this…
Not so clear for beginners, I’m afraid it doesn’t improve so much !
And quite frustrating for experts and professionals…
You should add an option in Pref Panel, for those who prefer to use the old Import Dialog which we really need !
YES!
Why not create Lightroom Elements? Isn’t this the same road that Apple travelled from Aperture to Photos, Final Cut Pro to Final Cut Pro X?
That’s what I thought it was the 1st time I opened It.
I’ve never had any issues with the import dialog.
I don’t really understand what the issue is. When you plug in a card, the import dialog opens automatically, displaying all the images on the card.
All the information about location and metadata is in the right pane. If you have eyes in your head to look, it’s not hard to figure out what goes where and how.
It’s not rocket science.
With the bugs in the new release I haven’t updated to the new version, yet, but the screenshot of this new import screen looks like a dinosaur.
I hope it doesn’t work like one…
the new LR import is not user friendly….If I used LR…with this new import system for the first time….I would be looking else where…..
Don’t like it at all…think it is crap!
This is all very sad. Has there been a significant turn-over of personnel in the Lightroom development team? The nature of the issue and the response from Adobe suggests to me that the developers have lost their way and forgotten what they are they are trying to do. Lightroom has been around for about 8 years now and has built a following of professional and hobby photographers keen to exploit its power and capabilities. It is simply too late to decide that new users find importing images “too hard”, and replace the old system with a “easier” version that only irritates the existing user base.
Taken with the reported bugs and instabilities associated with version 6.2, this makes me wonder if Lightroom is falling victim to the common malaise whereby the original drive and motivation gets lost and changes start to be made for change’s sake. I hope this is not the case, but I shall not be upgrading until I am sure that Lightroom is once again on track.
Please restore the old way of working, at least as an option. Making things easier for a certain group shouldn’t really be at the expense of the huge base of existing users.
Not only did you remove the Import screen you also broke the Synchronize Folder mechanism totally and utterly, which was really wasn’t any kind of improvement for many of us who use other other ingestion mechanisms.
Please , please be more careful testing … it truly is an integral part of the product.
So, you based a major change in the user interface based ONLY on research on new users? Absolutely no feedback from established users? This makes no sense. You’ve removed some important functionality. Find a way to make it available again for experienced users. Perhaps there could be several “levels” of the import window available, with the current one being the default, but the older one still available to those who know where to find it.
Well said Steve. I wholeheartedly agree with you.
+1
You’re missing the point, Adobe just stated that you have to see the “context”. Which is: existing users have already paid or subscribed, it’s the potential new customers running LR in eval mode that are to be cared for with the new import experience.
If long-time users get frustrated, what competition are they going to turn to? ACDSee? DxO? Or PS and Bridge? None of these can replace LR’s library management and raw bulk ops, and others are already gone like Aperture. Welcome to the world of software monopolies.
OnOne Perfect Photo Suite has a browser feature that works faster than Lightroom. It’s not a full replacement yet, but they are working in that direction.
Actually, Aftershot Pro 2 is looking better all the time, especially considering it includes some add-ons like Perfectly Clear.
And the naysayers said that adobe wanted the subscription model:
1. To address the dumb buyers who will pay for everything that is easy (iOS anyone). These interested “customers were universally unable to decipher the Import dialog without getting frustrated.”
2. So they can tell us that ” Keeping the existing … experience isn’t an option”, and “…continue to evolve the experience going forward…”
3. So they can make the product expensive, over time (read slooowly) and we’ll have no choice (or that’s what they think)
I was content with Lightroom 5 and what my camera (skills) can do for me, had to get Lightroom 6 so I could stop using Photoshop (for panorama and HDR). LR 6.1.1 is very stable, hence I can stop getting distracted by software updates and focus more on improving my photography skills. Thank you Adobe for that!
@Aidan: every brand should learn from successful change management stories and Maxon (Cinema 4d) has made an example of itself (Adobe partners with MAXON) Adobe has always been a bully and there business models are always profitable (hurray for shareholders!). If we don’t want them to act snobbish like Apple, we’ll have to use our money (or not use it on them) to make it happen.
Happy Clicking everyone!!
”
I’d really like to hear why “Eject after Import” made someone push back from their desk in frustration. It;s too bad you didn’t sit down with your EXISTING users to see how they were actually using the program they’ve been supporting for years, and to see what they find important. Maybe this new “experience” wouldn’t be so half-assed.
I’ve tried to glean some grain of hope from the quote above, but the only part I can take away is “Keeping the existing import experience is not an option…”. So basically we’re screwed. The rest is just the vague sort of “We’re listening…” non-answer that I’ve come to expect these days: “…continue to evolve the experience moving forward with your feedback in mind” Does this mean that some of the lost functionality will be returned — but under the new interface? What does it mean?
Back in the day, Photoshop CS3 was released with a revamped printing system that totally messed up the workflow of Windows users. John Nack was aboard then, and there was a massive backlash against the changes on his blog. It would be instructive to see his take:
” ….]
A straight answer and a promise. I miss those days.
Thanks to Scott Kelby and Phil Steele I have been able to muddle through LR 4 and 6. I was determined to make sense of the program without the help of Adobe! Those guys are so helpful, my go to resource.
I think the new interface is interesting.
Interesting because Adobe wanted change. Externally though the Import dialog worked. Sure it takes a bit of reading between the lines to use but really, it’s not rocket science.
I think it could have done with some minor UI improvements, with more of an emphasis on ‘flow’ like the new one.
i have a friend who likes to say “Better is the enemy of good enough.” That certainly applies here. A cute icon oriented screen is really not needed. We appreciate many of the new features; but not this one. The import functions in the previous versions of LR were just fine and not difficult to use. Perhaps we could have a choice of the old flavor or the new flavor as a preference setting (asking too much no doubt).
Why not have both interfaces and have a setting so the user can choose which he wants to use. I can start at the sandbox mode and as someone get more experience, he can switch to the move complex interface.
that should read “It can start…”, apparently there is no way to edit comments.
Hi Adobe,
Could it be possible for users to decide which import dialogue they want by selecting (or unselecting) a box in the preference -> General
Please give us back our “old” import screens !
I can understand that your studies have pushed you toward this for “new” users,
but the old ones, the one that are your all timers (from the first public beta in my case) are used to the “older” presentation of the import screen and WANT THEM BACK !!!
Please do something for us NOWWWW !!!
Regards
Phil
I’m not able to force an import “of a suspected duplicate” and I immediately found some situations of WRONG duplicate detection that i cannot manage. An orrible changement, please give us back, optionally, the old interface!
I hate the new import Module.
Please provide an option for Pros to change it back to the way it was!
I was a big fan of LR since the very early version. You guys put everything great together. Until version 5 (included), it was a really pleasant solution, I really enjoyed it.
While some new features like Dehaze and local adjustements are just great, LR 6/CC is suffering about performance, and a big hit. I hate to say that but it is kind of your Yosemite.
Now, subscription model is suitable for incremental improvement, both in feature set AND productivity.
I was expecting a release with a real effort on performance, but instead you really messed up with this new import. You focus on a number of user visiting their home. Am I reading this correctly: “home”? I always though you undersell the product, and you continue to prefer quantity over quality, more users. But hey, feel free to get a little brother “Express” to LR and give it to Photoshop Express user. You don’t want bring back the old import, that’s a great proof of a company not listening. You don’t want maintain 2 versions, there is definitely something wrong, a disconnect my dear Sharad.
Why deciding otherwise? Why introducing a complete new UI, completely different from the rest of the application. Why removing the other one? Worst, why removing 3/4 of the features that were available on this window. Too complex? Well certainly for people that use to plug their camera and let the software store the file in some gigantic file and barely run some backup, cloud will save us all.
Wake up! A core user base is simply using *intensively* your product and your latest toy is just becoming unusable. Those people are loosing hours of work and so money thank to you. And despite the openness of the software to plugin, they can’t solve everything for you guy, you are supposed to create magic.
So, unless you decide to go in direction of the photo professional and amateur, I think I’ll reconsider my workflow to the professional competition, which is far from perfect, but a competition that is paying attention to professional.
Antoine,.
Anoine,.
Having been a Lightroom user since version 1, the new import screen is somewhat nice, but I don’t think that it’s significant enough, and still could use a little more work and thinking outside the box before implementation.
I ran Lightroom side-by-side with Aperture and Photo Mechanic (ew) from day one, as to know all the software and to see how they would develop. I can say, there were a lot of things I appreciated about Aperture’s user interface and the design of the working environment as a whole. They were things I wish would have inspired Adobe to do better with on Lightroom. I miss the process of importing on Aperture. It was seamless.
The main thing is, that Adobe should be making software that allows us to spend more time (or our limited time) focusing on what we do best, being creative and making great work. While Lightroom is wonderfully robust, it still lacks in that area, that is, being a virtual work environment where photographers can really edit efficiently and at ease. The import dialog is a small step, but it’s trying to be both for the novist first and professional second. I agree with the sentiment that professionals should have the option to have a more robust import dialog, but I feel like the whole concept of importing, according to Adobe, needs a fresh look.
My main issue right now however, is not that import dialog, it’s the nearly unusable state of the software which has wasted me much time and money recently. It’s also about the leadership of the company which seems to allow for this botched update, which seemingly has become complacent with outdated approaches to software design. As I’ve said before, it’s important for creatives to have good virtual workspaces, and it’s an irony that the software used to create hopefully well designed/created things, is in itself, poorly designed.
I simply want to edit on deadline, fulfill my client needs on a timely basis, and go home at a reasonable hour, because my work can’t wait. I sure hope this kicks Asobe in the ass to do better in the future and I mean, to really rethink things and the way things are done and to focus on improving the experience rather than increased functionality and features that aren’t necessary. It’s very clear through the forum posts, which I have been tracking, and from other sources, that Adobe hasn’t been doing this. While it’s great that there is an effort to obtain feedback, it doesn’t seem to be from the right place. Sure, Lightroom is possibly for everyone, but first and foremost it should be a professional product and a reliable one at that.
So basically what I am hearing is that Adobe is following Apple and abandoning professionals and going for the low fruit of beginners.
Sharad,
I think nobody regrets the chaotic aspects of the previous dialog !
I personally can not get how :
– You can get a software released which crashes immediately on so many computers
– You can afford to suppress 2 features :
1. MOVE your files. We now have only COPY !
2. PREVIEW of the resulting folder tree
Also, managing of double pictures and the giant check marks on the thumbnails is less than nice, but it is less important.
When I first started using LR (having used PSElements for years) I was totally confused.
It took me some time to hnderstand the idea behind LR (I’m still looking for a good book on establishing a process, haven’t found any).
I’m doing a lot of Rugby and Concert shots, literally thousands of pics on a single day.
With LR I can easily manage that.
Because it’s a tool for photographers that do shoot a lot more than ten pics a day.
If the logic about newbies were right then we’d only have point and shoot cameras with a fixed focus running full auto.
You’ll need to address the “problems” in starting with LR with a better tutorial on the process not getting rid of features.
(And yes, the import dialog was a bit strange when I first used it, but I’ve come to terms with it)
Let me introduce a note of heresy. I wish I could, when I choose to, easily use LR a la carte. I wish I could easily skip the whole damned import, horribly confusing as to what’s what and where database rigmarole, and just open a folder of image copies I created on my hard disk, view the folder contents and pull the one or ones I want into the editor for processing. I wish LR would save all edited images from that session into an automatically created subfolder of the folder the unedited images came out of. Same name with “edits” appended. And then, should I decide at some point I want to bring the unedited images from that take, the edited images, or both, into a LR database, I’d like to be able to do that as a separate and completely optional step.
Maybe there are ways to do what I want the way I want with LR and I just have figured out how.If so, I’d appreciate hearing from someone who knows how.
My work flow isn’t large volume. I’m sure most LR users’ work flow is much larger volume than mine. I’m sure the a la carte approach could be set up as an option for users like myself, without spoiling anything for those who do lots of batch editing, labeling, rating and storing, and who want everything imported into LR (wherever, however) before they get to editing.
Options. Choices. Those are keys to keeping members of a diverse user base content — to remain in that user base.
You can do that now – just use Photoshop/ACR and Bridge.
ACR is not at all a replacement for LightRoom’s Develop module.
I was lucky by the looks of things as I have not yet loaded the latest version of Lightroom. At some point I will have to but for as long as possible I will stay where I am today. Might I suggest as you are obviously trying to attract new users and make the program as simple as possible that you have a choice of modes? Easy mode and professional mode. People just starting out could use what would amount to a wizard to walk them through import and of course any other part of the program, but once they are used to how Lightroom works they could turn off the wizard and either carry on using the easy mode, or switch to the professional mode which could have added features like better file management and a more involved interface.
I have seen many other programs do the same, so it has to be possible.
I think there is more trouble with exporting in LR6.2 than while importing, what can Adobe do about this?
All so, and this is more important, LR6.2 just crashes all the sudden, regardless the action is done at that moment and the work is lost!
Is there a way to return to LR6.1 till the issues are solved?
Sure, the previous Import menu was not easy to master but, as soon as you understood it, it was crystal clear, and I loved the fact that I could see and check the source/contents/destination in one glance.
Now, I have no visual clue of the destination, my photos are covered by a huge check mark and a dim effect and I need to click many times in many places to make it work.
I believe another option should have been explored : keep the old import menu, and add a 3-step, easy import process for the beginners, as Photo Supreme does : no multiple windows, no hidden stuff, just a couple of boxes to click in a row : select source, select destination – and you still have a button to select the advanced mode. I believe this is the idea behind the new import menu, but I’m afraid it fails completely.
And the beginners problem raises another point : since years, I ask for a simple browse mode in Lightroom, based on embedded thumbnails : fast, easy, reliable. Or a solution in-between : look at Picasa’s ease of use, half-browser, half managed workflow.
As I already said to you, Sharad, please don’t be tempted to level Lightroom down. We all understand that the game is changing, and Lightroom needs to open to a wider audience, but don’t forget that there is still a big and strong community of experienced photographers and advanced amateurs. Please, don’t left them behind.
Best regards, Gilles
“We’ve heard great feedback on the changes” Are your sure? I have heard only complains of experienced LR users.
As an early Lightroom adopter and LR ACE I must admit that this is the first time I’m disappointed with a new release. Lightroom happens to be a great product, far better than any other creative Adobe software product.
Do NOT make LR a consumer tool for managing the snapshots and selfies on peoples smartphones!
LR is THE tool professionals need to manage lots and lots of images.
I totally agree. Do NOT sacrifice LR the selfie mania.
i guess that ship has sailed.
when LR mobile was announced i feard that this is the new direction.
and as it seesm there is more developing time put into the mobilw stuff then in LR itself.
to be honnest adobes does not care if 200.000 pros use LR when they could have 5 million selfie user as customers.
for adobe only PROFIT counts… they showed that over and over.
don´t be fooled and think otherwise.
i mean why is there no DEHAZE in LR standalone?
because adobe loves it´s loyal old customers that much?
no, it´s a strategical move to force people to buy into subscription.
thats not a compnay who “CARES” about your needs … like they are never tired to repeat!
+1 for what Han says. I am explicitly worried since the 6.2 /2015.2 update showed pretty much only updates to PR mobile (besides the Import dialog and the local dehire feature). Yes, it seems for be a bit faster, but the focus seems clear.
For professional photographers LR is so much more than just a combo of Bridge and Camera RAW. It’s not yet perfect in every way but currently the best available all-in-one tool on the market. However there is competition in the pro sector and LR is not alone …
like. seconded. agree. hear hear!
This blog summarizes very well the current mindset of Adobe
“Let’s piss off Loyal paying users with changes that MIGHT help potential new customers.”
Then Adobe can show the shareholders shinny sale forecasts…
I’m still shocked that you spend development resources for a new import dialog instead of fixing the many reported GPU-related problems.
The old import dialog wasn’t perfect but why couldn’t you just introduce some kind of skill levels? I’ve seen this already in other products, i. e. showing/hiding option based on a configurable skill level of the user. A beginner would see only essential options while a pro would get control of every aspect of the process.
This new dialog is optimized for beginners only and I’m in doubt if it’s not even more confusing than the old dialog for beginners.
Here are some of the most annoying topics:
– Selected images get dark and are covered by large check-mark that makes it hard to see the image behind
– For me it was not clear that the folder icon on the left and the gear icon on the right are actually clickable buttons because they don’t look like buttons.
– Missing Copy, Move, Add options
– Duplicates are only shown as such during mouse over
– The UI doesn’t fit into the rest of Lightroom. Pillshaped buttons with vertically misaligned text?
But what’s even worse than this is that I had several crashes within minutes. And yes the Add Photos Screen option is switched off. Sometimes just moving the mouse other some icons within Library module crashes the application.
At least on OS X you have introduced a serious import bug that sets exposure of all images to -5 if “auto tone adjust” is enabled.
Lightroom 2015.1 was rock solid on my machine. Now I can use it only for a couple of minutes before it crashes.
Yes Han Blak, you are absolutely right.
I started with LR1 when it became available so many years ago, and this is the first time LR is crashing while working.
But, nobody is perfect and Adobe isn’t neither…
And yes, I am a professional independent photographer for 30 years now, and LR is my main tool now.
And yes, s***t happens (all the time), and we have to learn to live with it!
Come-on Abobe, solve this problem right away!
Mr. Adobe : please restore the classic LR Import Dialog ! Please let us choose in the Preference Panel; I want the thumbnails, the auto-eject features back, and all the excellent features you threw away !
I agree! Why REMOVE features. Please re establish auto-eject. Lightroom is meant to be a one-stop shop for photo editing. Now we have to minimize Lightroom to eject an SD card.
Workflow is being EXTENDED! Please reinstate this option….
„The previous Import experience literally made people push back from their computers in frustration.“
In this case it’s your responsibility to provide better support/education/tutorials for those, who want to actually enter such a a software. It is, however, NOT your responsibility, to break ANY workflows of existing users, especially if they are paying for the product and expect it not to get worse all of a sudden, while they still have to pay the same price.
It is in the nature of DAM software to be complex and you just can’t solve this issue by dumbing such software down, because then you loose functionality that is needed by such software. If users really want to learn such a software, there will neccessarily be a learning curve. So again, it is your responsibility to educate those people that they can master the software eventually.
Following your own logic, you would also need to get rid of DNGs altogether, because that’s “just to complicated for new users”. And I don’t think you would want to do that, OR DO YOU??
Also, why stop here, go on to other software, take away masking from Photoshop, just to complicated for new users. Direct selection tool in Illustrator? Hm, new users don’t understand it right away, get rid of it already. Take away scripting in InDesign, no way new users would know how to use it. Keyframes in After Effects? How are they intuitive? Let’s get rid of them. Dreamweaver? Hm, coding is complicated, should get rid of that software altogether.
I realize that you have decided to change the import dialog but PLEASE AT LEAST GIVE EXPERIENCED USERS THE OPTION to still have the full functionality that we always had before. (eg ability to import duplicates if we needed, Ability to Move files, Ability to eject Media after import etc etc etc)
I’ve been using Lightroom since 2007 and removing the flexibility here this is without doubt the worst change I have yet seen
My friends, you (should) have a beta program still running and I’m curious to know what people said after seeing the new “improved” import panel – or simply IF they did.
The “new” import panel is frankly embarrassing. Helping new users to familiarize with a sophisticated interface does not mean you have to remove all the sophisticated options! You built the “add photos” interface, which I suppose is designed for beginners. No professional will use that, so you already had your import panel for beginners, why damaging all the others demolishing what was perfectly working? Just give the newbies a fancy, simpler and no-complications panel and restore the import panel the way it was. Let the IMPORT button to open the easy or advanced panel according to user preferences and it’s done.
And please don’t talk about user experience studies: putting a big round checkmark icon in the middle of a photo thumbnail obscuring possibly 80% of faces inside them is what demonstrates no real UX expert – or without enough time – was assigned to this project.
I’m really surprised and disappointed by this post, afraid that you don’t believe in professionals anymore and you want to jump into the consumer wagon.?).
Anyway, please talk a little bit more with users, real ones.
thanks.
I can´t believe this statement about the Import.
Where did you make this test with the old interface? In a nursery?
Here is the true impression of your customers about this:
At the moment 282 people complaining about the changes you made. Not one that likes the new GUI. Given the fact this thread is two days old this is the highest number of people complaining about something ever.
Nobody would have complained about a better import, but you removed features and that what makes the majority of your customers angry.
To make it very clear for you. The new import is unusable and in the thread I linked the people explained very detailed why.
If you do not bring the features back, I will cancel my subscription, even though I love all the rest in LR and use it since a long time. But importing pics is the most essential thing I have to do and it´s just not working with the new interface.
Think twice what you do. There are a lot of people not willing to accept this.
Regards
René
Actually that response frightens me. What’s next? Most people don’t really understand what HSL means. So you will reduce it to a simple “no color, normal color, really shiny color” dialogue?
I understand the need to make the UI easier for beginners. You can even make it the default option. But you must bring back the functionality that you removed as an option in the preferences. This would be a Win Win. Adobe you need to do the right thing and restore the old import dialog even if you have to hide it from the newbies.
Sharad, could you please explain the rationale behind making this new feature available to perpetual license customers? Adobe said earlier that they will _not_ provide any feature updates for LR6, only for cloud license subscription customers. Why the discrepancy here?
that´s pretty simple.
the truth is that it´s a way to force people into subscription… that iss what adobe wants.
subscription is a constant calculatable cashflow. the holy grail for any company.
many people don´t like the idea of renting software, so they have to be forced to switch.
a subtle (well not really) way is to make subscription more “attractive” or standalon versions LESS attractive.
by removing features from the standalone version people begin to think to switch to subscription.
not because they like the subscription idea.. but they want the features.
there is no other reason… believe me.
if someone tells you it´s only possible with subscription…. they are just lying.
in case of the new import dialog adobe HAS to introduce it to the standalone
version too.
because the whole purpose is to attract newbies to LIGHTROOM.
and even when they fiert only buy the standalone they will maybe one day be forced into subscription.
it´s another proof that adobes decision are only driven by maximizing marketshare and profit.
simple and clearly answer and absolutely correct
Stefan, that’s because it’s a change to an existing feature, not a new feature
Really hoping for an official answer from Adobe here. To quote Rikk Flohr (who appeared to represent Adobe in an earlier post): “Lightroom 6.x will continue to receive the same level of updates as did its predecessors, (Lightroom Versions 1-5) which included new camera support, new lens support, and bug fixes”.
This new/changed import dialog is very clearly not a bug fix.
If you wanted to make a dumbed-down app for the consumer market, a better strategy would have been a new product (Lightroom Elements, perhaps).
Professionals rely upon your products and you are messing with their workflows, their business.
This will backfire.
Re-designing the import is not the same as dropping some of the extremely helpful and appreciated function from the import.
If you need to re-design and somehow streamline it – OK. However, that does not have to do anything with dropping functionality, which is what you did.
Spot on. I totally agree that the original import was difficult to learn. But making it easier to learn does not mean you have to remove features.
I like the look of this new import screen, and agree it needed to be worked on. But while new users may want to scan their drive for pictures to add I have everything I need there already. I rarely import from anything other than a camera memory card, and imagine most other existing users don’t change their source much either once everything’s set up.
If I could filter imported images by date? Or make some days import to one folder, others to a date folder… that would be very handy. Removing features that exist to prioritise first-timer installers seems a poor decision though. Pretty sure most first time lightroom users would be scared of those complex develop sliders and prefer a preset browsing window showing how images will look with the included presets instead. And it took me weeks to get my head around all those complex export and publish options; why not replace them with just a single ‘export’ button that saves a jpeg the right size for facebook/email to keep it super easy…
Exactly that’s the point. LR is (was?) a perfect tool for professional and serious amateur photographers. And they need for instance complex import/export options for doing things exactly how they want. No serious photographer will export his images by a single export button.
To Adobe: if you want to fish for mobile users then make a LR Elements (like PS Elements).
yes – LR Elements! I can cope with UI changes when adding functionality, but not when re-designing to capture an imagined audience.
So how does removing the ‘Eject memory card after import’ option enhance the experience for the novice user ( just to name one)?
I think that novice users don’t understand the import concept itself. They expect their images go ‘into Lightroom’, a bit like what Apple does with their Photos library. The new dumbed down dialog does nothing to address this misconception. Novice users still won’t understand it, expercienced users get annoyed by the missing features they always used.
At the time my problem is to have something that works. I had to roll back to 2015.1.1 and still have a licence number I can use without Adobe CC. I’ve experienced difficult update from Aperture 2 to Aperture 3, at that time I was seriously thinking about moving from Aperture to LR, if it turns that way I won’t renew my cloud subscription and find other software. Or simply use my licence number to reinstall LR 5 and upgrade to LR 6 standalone. Think about that before you make further changes Adobe.
Just started to use Lightroom 6.2.
Zooming in on center of image in develop, LR decides that I want to zoom in on the top right of the image. It then takes like 10 seconds to see the detail in the image.
Who the hell tests these updates??
Previous version worked fine. Professional tool for photographers ?????
New Coke, Windows 8, and now this. 🙁
If the crippled import is what you prefer, fine. But make it optional. You can’t tailor the product for people who _don’t_ use it. Existing customers, who already _do_ use it, and have done so for considerable time, require the advanced mode that existed up until version 2015.1. They won’t care what’s the “default”, but they need to have some way of getting what they need.
Don’t forget to mention that the feedback you received in the last days might well have been “great” as such, but that it was unanimously hostile towards the change. You are monitoring your own support forums, don’t you?
You can (try to) explain whatever you want, but I’ve been using LR since ver. 2 and the new Import dialog is a disaster – I can’t think of a more appropriate word to describe it …
Creating a simpler interface, is one thing removing functionality that many need is another. please bring back the old functionality.
You talk about visiting new Customers in their homes to find out what they found hard about the previous import screen – fair enough, a good way to help evolve the product and get new buyers.
But what about your existing Customers!! Did you visit them in their homes and ask what features they actually liked and used in the original import process? From the feedback in the feedback forums it would appear not.
You’ve got a lot of angry subscription paying customers who have had well used functionality stripped from them without warning, and the above blog post does nothing to to make us think you’ve going to listen to what your existing customers want.
Crazy way to do things.
When you revisit this, please allow us to filter the selected images y
1. file type ( IE raw or jpg) ….. Mostly I do not want my jpgs and raw in Lightroom from a card.
2 date range. Sometimes I forget to format cards between sessions and would like to ignore images from a range of dates
These are two practical enhancements which will make the import process more usable to the Lightroom import user.
Yes the new import dialog is an ENORMOUS way back !
In my view it is not les confusing to new users and it suppress so much appreciated functions to the experienced user.
I do think the solution is an option in the preferences to have a simplified of a complete import screen.
I guess that the old import was to advanced for “newbie”-users that mostly use their computer with family-jpegs and mobile pictures.. but most advanced and professional photographers uses Lightroom and to make the import-function DUMB and remove LOTS of IMPORTANT features just to please the common user is the wrong way to go.
Give us professionals the advanced features back or we will NEVER upgrade Lightroom. I have to stick to 6.1.1 since my entire workflow is now rubbish with the new version. There are so many many things that went wrong with this version …
The new version is very bad. I don’t like the new import. So let us get the old one back.
I solved the problem by uninstalling ver. 6.2 and installed version 6.1.1
I am also very unhappy the Adobe have 2 versions of LR, WHY. They want us to by the CC with PhotoshopCC.
Steen Aage Nielsen
Denmark
I, too, agree that the old import process was a bit opaque. I have no problem with making it easier to use. That would be great. But, as others have said here and elsewhere, the decision to remove functionality is completely baffling. Please post a blog entry explaining that decision. Also, address the issue of why a more full-featured import process is not an option. Or why it is almost impossible to read the text in the import dialogs. Or why selected photos are obscured, while rejected photos are bright and clear. The sort of answers provided in the blog post above only serve to frustrate users who are unhappy with the release. If Adobe truly cares about its existing users, they would provide straightforward answers to these question, I doubt that there would be much grumbling if all you had done was make Import more transparent and easier to use.
You do realize that the underlying fear here is that functionality in other parts of Lightroom will also be sacrificed, don’t you? Can you address those fears?
I don’t understand Adobe’s argument at all. This is powerful software designed for photo professionals. Anyone can use it (I am not a pro photographer at all), but you have to LEARN it. If people need very simple, immediately intuitive photo software, LR is not the tool for them. I use InDesign all the time and I love it, and I’ve talked to people who took a look at it and were intimidated — well, yes, because it’s powerful software, you can’t just sit down and use it. This isn’t an iPhone. Please, Adobe, think more carefully about what you are doing.
I understand that for some user the import could be not intuitive. And Adobe is trying to simplify it somehow.
So what about to remove this import window at all? Then in Library module would be directory structure listed as standard directory tree. And for those who wants to keep their photos in LR Catalogue there would be some option over the actual directory with photos. Options like add all photos into LR Catalogue. Editing using XMP files will be used by default and as well in the case when photo is not in LR Catalogue.
“Customers were universally unable to decipher the Import dialog without getting frustrated.”
So it was changed and released early for marketing reasons before it was ready and broken.
Way to go on keeping customers from feeling frustrated!
I’m still not hearing “Why” subscribers to CC should be getting their monthly payments deducted from accounts to pay for what amounts to a Beta release. These bugs have now cost me two days of productivity with the constant crashing on IMPORT & EXPORT. Yesterday it took three tries to get 30 RAW files from an Olympus camera off the SD CARD. Even then I had to copy them to the desktop first, then IMPORT into LR CC.
I think a partial or full refund of this month’s fees is in order!!
I’ve never got why developers must change what works. Have a look on this forum and see how many people are happy with Adobe’s changes:…/topics/new-update-6-2
There was nothing wrong with the previous Import window. Can’t see what you’re talking about!
Adobe, like most large (faceless?) organisations, will find it very difficult to admit a mistake.
The best best we can hope for, is the addition of a “6.1 like” import dialogue as an “advanced option” in a future (6.3?) version.
I keep my fingers crossed, but I’m not confident enough to hold my breath…
I’ve been very happy with LR since v. 3, but since the 6.2 release I’ve tentatively been searching for Capture One…
Sorry I’ve previously posted a broken link
I’ve never got why developers must change what works. Have a look on this forum and see how many people are happy with Adobe’s changes:
There was nothing wrong with the previous Import window. Can’t see what you’re talking about!
I was one of your new users having bought Lightroom less than 3 years ago. I am a 70 year old who has just taken snaps all his life. I found the input process easy to learn and its features very useful in digitising and cataloguing a lifetime of pics. I was also amazed at the useful features it had both at input to organise my pics and to clean them up. Then I bought a new compact camera with RAW capability and found out the fantastic things I could do with my pics. For me you are distroying a fantastic tool just to appeal to those who cannot take a few minutes to utilise its features effectively. If they can’t cope with the input experience they have no hope with the rest and I can see that you will be going down the route of messing up the Development Module next. I was very tempted to go with CC but decided to stick with owning version 6. How glad I am as I can stick with the previous version until you come to your senses like Microsoft did with Windows 8.
I have no argument that the old import dialogue sucked and needed a re-design, but not *this* re-design. It isn’t all that clear to me that this design will solve any of the naive user’s problems. Making an interface “pretty” is not at all the same as making it good. Really. Making a pretty, but hard-to-use interface is a classic rookie mistake, and Adobe shouldn’t be putting rookies in charge of creating new content that interacts with users.
Getting the design right is a *hard* problem. It takes hard thinking to come up with a decent interface that makes a user’s work quick, intuitive, and not error-prone. Then it takes a lot of iterative real-world testing to make it *actually* work that way. I’m sorry, but this new Import dialogue isn’t even a good first try. It should be thrown away and re-thought. Merely fixing the bugs in it and adding the missing functionality back in won’t help.
Hal
“We’ve heard great feedback on the changes” -> Can you please give me one example? People who are overwhelmed with LR functionality should use other tools, there are plenty of them. But there is only one LR – PLEASE don’t destroy it!
“Uncheck “Show ‘Add Photos’ Screen” -> Still not working on my MacBook Pro, Retina, 13-inch, Early 2013 🙁
This was the my worst software update ever 🙁
I am very frustrated and disappointed!
René
Sadly, Adobe feels the need to grow the business by dumbing down and going for mass appeal (more or less like everybody else). The powerful import dialog and other grown-up features of the program that attract the professional user are being replaced by a mother-knows-best version seen as more profitable now that a sufficient number of users has been attracted to the subscription model. We’ll have to continue paying even though we may, now, reject the upgrades offered. Quite a cynical manipulation of the customer base when you think about it, but unfortunately not atypical.
Can LR not be offered with legacy options like PS for those of us with an established workflow?
Would that we could get out own back by voting with our feet but what alternative is there now?
Sharad Mangalick, are you the “smart” guy how had this stupid idea ?
Where have you heard great feedbacks ? Can you give us some links ?
I haven’t seen any, but lot’s of upset users …
Ejecting card after download and preview magnification did not push people back from their desktop. These were useful functions for me. Not being able to view my photos at higher magnification meNs I have to import the marginally sharp shot and that wastes drive space or takes more time to delete. Seems to me keeping these functions harms no one.
The most absurd thing about this rejig is that it makes errors and mistakes far more likely for all, in particular the novice who supposedly it is to benefit.
I always use move on import as I copy files [from possibly several sources at once] to same HD as where LR photos are stored, I then check everything has imported properly and then import to LR. LR then just moves items to correct folder on same HD. This was because LR didn’t and still doesn’t always copy all files off the disk/phone and data can get left behind. I also seem to recall on testing such things a while back that Adobe software was slower at copying than using a file browser to move the same data.
Now I have to copy off HD/phone, copy into LR and then delete from two locations rather than just off the card to be safe.
So more chances of mistakes and at least doubling time to import data.
Also removing by feedback about what is going to be done such as with file renaming and file destinations, this is only going to increase mistakes on import.
LR seems to have gone down the simplistic route rather than a simpler route. I seen no benefit to removing these features as they will only increase the chance of errors, so anything but novice friendly – the supposed justification.
I should add that I have zero problem with things changing even quite dramatically, IF and only IF it results in a better/easier workflow. Such as LR moving away from the actually still very good [for individual images] PS interface. .
Could I suggest that age old IT phrase – “RTFM”?
There are plenty of creative beginner programs out there for people who find LR too complicated.
Please give us back what we had previously. This is just what Apple did to Aperture – “Photos”.
Now I’ve switched to LR and am having to uninstall and rollback versions.
Not a happy bunny 🙁
It’s now the first one problem of Lightroom user in 3 days …
Others top ten problems are here for a a year or more …
What a “great” feedback !
To: Sharad Mangalick,
What an absurd, arrogant, condescending basket full of poppycock.
Perhaps you should contemplate the lessons offered in the Greek proverb about a “Bird in Hand,”
Do you think your longtime traditional users are incapable of seeing through your double speak?
You use the term ‘evolve’ several times and apparently you seem to choose to ignore the fact that successful evolution rarely relies upon loss of function as an organism progresses.
Secondly, you state that ‘Customers were universally unable to decipher the Import dialog without getting frustrated.’ … if you paid any attention to the feedback forum over the past 72 hours, you would be well aware that the true universal concern.
Additionally, you close you statement with … ‘Keep the feedback coming!’ … why should we bother? … you will do as you wish and expect we paying customers to accept whatever you offer without question. How can you choose to ignore all that feedback on just this issue … the thread in question has surpassed other topics in just a couple of days that took years for other topics to achieve.
Once again, the arrogance of this ‘context’ you share is quite evident that you hold your existing customers in very low esteem and actually take them for granted and are more than willing to sacrifice them in order to attract ab unproven market segment to the fold.
What makes you believe that a potential customer that found the traditional Import dialog too intimidating will be in the effort for the long haul to support your salary in perpetuity without question?
I, for one, after over 22 years, will be getting off the Adobe merry-go-round as I have had my fill of this attitude and arrogance. I will be canceling my subscription at the end of it’s current term and I won’t be back.
Can we not simply have the previous import behaviour as an advanced setting that we can turn on if the new default makes sense for some customers??
I don’t follow at all why the eject after import option is gone though.
I can’t use Lightroom at all without crashes if I upgrade to Windows 10 (from 8.1) in any case.
The newest seems to work on my Macbook Pro so far, except that I’ve lost functionality for tethering for example.
Dear Sharad,
‘The previous Import experience literally made people push back from their computers in frustration. Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.’
I certainly pushed back from my computer in frustration, then searched the web until I found a way to roll-back to 6.1.1. I could not agree more that keeping the existing import experience isn’t an option, which is why I had to leave 6.2 behind and move to a better, more refined and much more useful import experience.
If you want to have an import experience that is aimed at people with none of their own, then at least try:
1: bring out LR elements. If they can’t understand your previous import workflow how did they go with a histogram?
2. put in an option for ‘beginners’ and ‘experienced’ users. Lots of programs out there will have menus tailored to the audiences self-assessed experience level. It works well for them and it could work very well for Adobe.
Did Adobe even read this on their support forums ? Massive negative feedback on the new import and they reply “Keeping the existing Import experience isn’t an option” .
Seems to be an interesting new way to import photos in Lightroom 6. But why would’nt you add a short tutorial for the first time we import a camera or an external HD asking for those changes to be made? I do agree with Enoch when he says that Aperture’s importing photos are more efficient (such as Apple’s Photos new importe panel box).
Most of the time we have difficulties between importing pics, copying them or moving them. It should be clarified the first time the importing dialog box is launched…
I’m struggling to decipher what’s so impossible to understand about the import dialog. It really doesn’t need to be simplified. And once you’ve uses it a few times it’s pretty intuitive – and enhanced by the use of presets. Redesigning a part of Lightroom that isn’t broken (really – it’s not) doesn’t help your existing users, and I suspect won’t help your new users once they discover that they need the functionality that’s just been removed.
Removing the automatic card eject is ridiculous – that just creates an extra step in the process of import – and it’s one that long term users will forget.
Disappointed.
As a “from the beginning” user of LR this upgrade has be stuck on Import. I am totally unable to get any images in the preview window let alone get the files into the catalog. In order to be able to keep working I must downgrade until these issues are resolved.
Simplifying for new users I get, but eliminating functionality like “move”….I don’t get.
Looking at what was eliminated, it seems apparent that Adobe was more interested in what would make it easier for them in managing files on the cloud, then on what users actually value. This is the first “upgrade” I have experienced in Lightroom that is actually a downgrade, and I’ve been a user for a very long time.
Add in the fact that the update was clearly not ready for prime time, and you are giving users a reason to look elsewhere.
The above “justification” is weak IMO. You all can and have done much better. It’s disappointing.
So in other words, we’re going to continue to make Lightroom harder to use for standalone customers while tailoring it exclusively to the CC use model. I’ve been a user since LR2 and I have never “pushed back from the computer in frustration.” The Import model is simple and straightforward, and the only consistent problem I’ve had has been due to my own stupidity – not checking if Move was selected when I wanted Copy.
At least be straight with us Adobe, you don’t care about SA customers any longer and frankly you’d be happier if we took our business elsewhere.
Quo vadis Adobe? One of the reasons why I decided to go for LR at the time was the combination of a powerful high quality Raw converter and a good tool for organizing my fotos – all in one Tool. In this respect LR is (was?) unique. The OLD import dialog was one of the components that helped me organize my photos efficiently. Some of the options that were removed now I rely on in my daily workflow (importance in this order):
+ destination folder preview
+ Eject card
+ filename preview
+ Move option
+ Total file size
+ Zoom would prefer if Adobe were to take the tremendous negative feedback on the new import serious and bring back the lost functionality . It’s not a shame to change you mind if you see you have been wrong but shows true size and professionality …
Uli
Lightroom 6 is full of bugs and very slow, I lost my money. I’m not going to buy Lightroom 7.
I want to echo the huge and loud outcry at the loss of many of the functions that those of us who rely on Lr for our workflow need to have. Crashes are one thing, but to DECREASE our efficiency and take away functions makes no sense. You could have easily built in the capabilities to have the choice to use either method. It appears you sold our you vast existing user base.r
I was deeply shocked at how much, and how badly this interface was changed – particularly in a “dot” release. So, I’ve read the comments above, and let me try to understand Adobe’s approach here. Go and visit **naive** users to find out what they don’t understand. Modify your product based on their feedback. If I want a better guitar, I go ask Eric Clapton, I don’t go ask some random guy on the street who doesn’t even know how to play do I? “Man I can’t play this thing” he says, pushing his chair back in frustration, “the strings hurt my fingers, can you give me softer strings or somethin’?”
I understand if you want to make a product that is usable for **new** people – you want to compete with iPhoto (or whatever it is called now). But that is not Lightroom is it? I thought you had the “Elements” products for these entry level customers.
Very disappointed with this update. It took me a few hours of struggling to get the updater to do anything but hang while I was trying to update Lightroom and Photoshop yesterday and now I wish I hadn’t succeeded.
WOW, unbelievable. Adobe was always bad at UI design and now they have made a marginal import function worse…
Just make it user selectable if you want pablum import design or legacy…
I really wish there was competition in this space, RIP Aperture 🙁
The screen shot says it all. The new import has dimmed images with a big check in the center. Why is that a good thing?
This is not one of those changes where many people complain because they don’t like change. It’s a horrible update for all the reasons being stated.
Just man up and admit that someone made a mistake.
If you’re going to start dumbing-down Lightroom for the first time snapshot shooter who just bought their first high end digital camera and who thinks they have to have the top-of-the-line post processing software to go along with it, $DIETY help us all.
Basing major workflow design changes on noobs is a sure way to alienate the professionals who built up what you now are.
But you’re a monopoly, so what recourse do we have, except to post comments on a blog post. Comments that will be completely ignored.
I was a Photoshop-only guy for a long time. Even so, I’ve been using LR for several years. When I made the switch to using LR along with PS I was amazed at how it boosted my productivity. I was an early adopter of the CC subscription plan and am quite happy with rate of improvement and development of all the programs.
However, I’m afraid I have to agree with the negative reactions to the new import interface. Some functionality seems to be missing. I also now have to click through an additional screen to get to the real interface. The destination dialog is dumbed down and harder to use for an experienced user.
I understand the need to make LR easy for new users to incorporate into their workflow. But please do not add friction to the workflow of professionals and serious amateurs. Adobe already has a product for the casual users (Elements). It’s not a bad idea to add a third product to the Elements line, LR Elements.
After the “rant” I “uninstalled” LR and downloaded from CC. Program working as advertised.
Oh, my goodness! Do you have this slightest idea how arrogant this post is? Perhaps, it’s as simple as you just don’t give a damn. It’s certainly true that someone at Adobe doesn’t care.
If your test subjects were that intimidated perhaps you should suggest they study a bit just like the rest of us had to do. Better yet, send them to Photoshop elements.
Are you designing Lightroom for idiots who don’t want or care to learn powerful software or are you designing it for working professionals who need all of the features we have learned to use? Bring back the old Import and let the non-professionals learn to use it!
Ok, so what you’re saying is that you changed the import function so that you could get more new users at the cost of your existing power users who are paying you a monthly fee for this program? How is that customer friendly? What kind of focus does that betray within your business model? Did you realize you’re charging us a fee for this and we can expect consistency in return for paying that fee?
And, come on, new users were turned off by the import function but were fine with everything else? The rest of the program requires even more training and knowledge than importing. So, is your next step to simplify the rest as well so all those newbies who can now import their images but don’t know yet how to make them look better, can just click a few buttons?
Who did you make LR for anyway? The Instagram crowd or serious photographers?
You certainly have made clear where your loyalty lies and over time we will show you where ours lies. Hint, you’ll get the newbies and we will move away…
To clarify:
Your professional software was hard for beginners to understand, so you threw out some of the professional aspects of it. Great.
Just wanted to say that I’ve held off installing 6.2 so far PRIMARILY because I hate what I’ve seen so far of the “new” import dialog. I know I’ve been using it for years but I really don’t know what was so bad about the original that a simple “easy-mode” option couldn’t resolve…
I can get on with the new import dialogue if I have to especially if I untick the add photos box but the 6.2 build is not stable, I have read that MAC users have had crashes; I have had 2 with Win 10 especially with high processing load. Also the merge to panorama no longer works it just gives black previews and if you merge black panos as well. Going back to 6.1.1
Wow Adobe… Can you “feel the love” in reviewing these posts? Not only have you alienated your loyal professional users in an “update” that was more targeted to newbies who didn’t want to take the time to learn the program, you released a buggy update that has crashed machines and performs poorly. Now, show us that you are really a company that “cares about you users,” admit this was a blunder, and fix the problem. You might even consider rolling back the import interface to the previous method, which worked. It takes guts to admit you made a mistake, apologize, and own the problem. Does Adobe have what it takes to do that? Make us proud, not angry.
A disaster and the “reasons” are insulting to your existing customers. I, and it would appear many others, had no problem with the old import screen so the very least that is needed now is a choice between the “Classic” Import or the “Mickey Mouse” one. I’ll upgrade to 6.2.1 if you offer me that.
I wrote extensively on the family blog about my dissatisfaction with the new Import loss of functionality. In that piece, I wrote specifically how the loss of features had me pushing back my chair in frustration. But even if you brought back all the functionality you stripped out, the interface would still blow. Sometimes, I have images on my card that need to get directed to different folders; I use folders to session my work. So I might have to run import a couple of times on the same card, because rather than Adobe figuring out ways that I could stack import targets in a single operation, they were too busy reducing the Import experience for the selfie crowd.
So, before, when I would go back to Import to bring in another session from the card, my previous import would be greyed out because it was duplicated (if I had the “don’t import dupes” check box selected. With the new UI, there’s no way to know which files were previously imported UNLESS I CHECK THEM ALL or mouse over the image. This is exactly the opposite of what I want. I want to uncheck everything, and all the potential candidates dim and the dupes dim more. Then, as I check them, the thumbnails brighten. With the new version, when I select them, the check mark covers the image and the image dims. It’s exactly the opposite and it’s profoundly stupid.
So, let’s jot it up: severe loss of functionality and a confusing, reversed UI for seasoned users. And you say returning to the former version “is not an option.” I am very sorry to hear that. I thought that maybe LR would avoid the rot that has set in at Adobe. I guess I was wrong.
The new format might be ok, my initial frustration was losing the ability to import. Uncheck “Show ‘Add Photos’ Screen” fixed it for me. The traditional format was not great, but the new one is a good idea but needing more work.
Sounds like it is time for Adobe Lightroom Elements.
If not how about the choice of import interface in the preferences?
Like most people, I really don’t like the new import dialog at all. If there was a problem for new people, give them an option to use the new screen, or give us the option to turn it off.
I really miss the destination folder panel. That was so easy to use. I simply chose my import template and filled in the subfolder name. All done. I’ve tried to figure out how to do something similar with this new import dialog and I don’t see how get anywhere near the efficiency.
I agree with Adobe here. I have used Lightroom most every day for the past two years. The import process was not at all intuitive and once learned was difficult to execute properly on a consistant basis, resulting in occassional lost files. When lightroom trainers talk about teaching the software, the most common user complaint seems to be “where are my pictures?”.
it seems that Adobe has used the popular ‘Voice of the Customer” process to re work the input section. That is a difficult nut souund process, but can sometimes lead you astray. If Adobe did not include a sufficient number of seasoned/proffessional users in their customer base they could easily slant their results to the needs of beginners. I think this can be salvaged be expanding the user-base in the study and making sure that the software is flexible enough to accomodate al levels of users. in other words, keep what you have here but build on that base to add back features that the Pros need.
Dear Sharad Mangalick,
Thanks for the update it was really needed, while it does not at all address any of the concerns from your loyal users over this “update”, at least it sheds some light on the reasoning behind it.
I use Lightroom on a daily basis, and your post confirms my worst fears. Adobe are now designing Lightroom to pleasure absolute beginners, and are more than willing to sacrifice your core customers needs at that expense. Obviously you can’t have an interface that really suits the needs of both newbies and professionals at the same time. The hundreds of comments with valid descriptions on how this “update” breaks peoples workflow clearly illustrates that. But it is clear that you have made your choice. Now it is time for us to do the same.
You have observed that the import process is complicated for new users, and your brilliant answer is to remove all features that are confusing to beginners. And to create a big fat blue import button to guide them, and advise them to just import all photos.
I can only assume that you have made the same user observations in the develop module, and now have a list of confusing “advanced features” that you plan to remove in the next update. It is not hard to imagine what havoc this new design philosophy will bring, when it gets to the develop module. Nothing in your response makes me think otherwise.
Adobe is looking for profit and new market shares, but should be thinking about the millions of dollars already invested in Lightroom, that is now being wasted by dumbing down the software in this so called “evolution”.
You say: The previous Import experience literally made people push back from their computers in frustration.
Try to imagine how many of your existing valued customers are now doing the same with the new one…
Personally I think Adobe has a very short window of opportunity to show that they are still developing software for professional users. The nonchalant “Keep the feedback coming” is simply not enough!
This is the first upgrade ot Lightroom which I am going to uninstall. I used the variable thumbnail option to identify those photos that were not worth importing in the first place. In my Lightroom 6.1 I also set the option to make a second copy to another drive for security purposes as well as subsequently doing backups to external drives and cloud services. Now I end up with useless photos cluttering up my hard disk, taking longer to import etc.
What happened to the old Destination section which gave one reassurance that the import was ending up in the right place. Please bring this back or as others have suggested give options in the preferences screen to enable previous functionality.
I had started wih Photoshop elements but gave up on it in preference to Lightroom as it was so logically laid out and easy to use. I am again starting to use Photoshop sometimes to undertake those things I can’t achieve in Lightroom but use Lightroom 95% of the time. Perhaps you should consider a Lightroom Lite if you are wishing to attract a wider audience to the product who can then progress onto the full version when they need to use more advanced options.
What on earth possessed Adobe to remove the eject after import option, please re-instate.
Microsoft received a lot of negative feedback on Windows 8 when it was introduced because it was difficult to find items which had been hidden away in the interests of user experience. Thankfully they listened and Windows 10 is actually a pleasure to use. I hope Adobe will listen to its existing user base and not disenfranchise them.
I’m sorry Adobe, but this is the worst software update EVER. I’m so frustrated and ANGRY. I teach Abobe products and this has my blood boiling. If this is progress then its time to use another software supplier.
PLEASE PLEASE PLEASE restore this hideous change or give us an option to choose which we prefer!
NOW……………………….
I just completely disagree with what you have said here. The Import dialog was no less or more confusing than anything else in Lightroom. People cannot be expected to jsut jump in and use software without some basic understanding of how it works.
Why was the Import dialog so confusing? Source on the Left, Method top middle, Destination and options on the right. Why is that confusing? What is confusing is people think that Lightroom is capturing their images and putting them in some container (i.e. Aperture, Picasa, iPhoto) which is not the case.
You have a taken a professional level piece of software and dumbed it down for Smartphone users. Just put out Lightroom Elements if you want to make a consumer level app.
Leave Lightroom with the professional options for Workflow that we need.
Dave Doeppel
Adoe Certified Expert Lightroom & Photoshop
Why not put this on Facebook and put this to a vote!
Keep it or LOSE IT!
I say lose it – first vote!
I lead two Mac Photography groups with passionate and fairly experienced photographers. Over 50% of our users- 69 to be exact installed the update to their CC packages- 59 couldn’t get past the splash screen. If they did manage to get past the LR splash screen ALL were told that their catalogues were corrupt. ALL downgraded within hours.
I’ve written software for a large company for many years– clearly this update was rushed out and not tested beyond the alpha stage. You owe all us an apology and a quick fix. The input here on the import screen speaks for itself.
Being a Lightroom user for the past 8 years, this update comes out of the sky like a bad surprise and leaves me VERY frustrated due to an unusable LR. I am used to upgrades on LR that makes it faster and better, but this time the upgrade really makes me believe that Adobe has lost its contact with the professional consumers, like me. The new upgrade with its new import dialogue looks like something that is made to attract new beginners to use Lightroom, hence the “studies” you did with “users in their homes”. Adobe is this way stabbing their core users in their backs by first of all removing really good functions (but may seem like complicated functions), secondly for making LR unstable and thirdly for making no option to roll back using CC cloud.
One solution could be to provide to alternatives when importing: The old import with all the good stuff, or the new one for beginners and amateurs which took part in your “study”.
I understand that there are more photographers now than ever before. I do understand that Adobe is a for-profit and profit oriented company. I understand they would like to attract more customers.
However I don’t think that you have to drive away your current customers. Why not offer an “easy” (if you really think it is) import screen for beginners and let us professionals keep using the old import page. The “old” one was complete, offered everything needed (Move, Add, Copy, and dog options) as well as complete explanation of where the files where. Not the new one.
So Adobe friends, all you need to do is give us users the option, don’t treat all of us as if we were babies, we are not.
When you have people like The Lightroom Queen and Linda Shoe saying DONT upgrade and here’s how to roll back, you know that you really made a hurried mess of things @Adobe.
2 of your stronger advocates are publicly saying 6.2 / CC2015.1 is a monster and your response above is not a hint of “oops” or “sorry” to so many users who’ve been there since the beta and you building Lightroom on the carcass of RAW Converter.
I’m getting LR hang every 2-5 minutes using El Capitain, so there is no way I’m going near the recently rush release that is not ready for your paying public.
“The previous Import experience literally made people push back from their computers in frustration. Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.”
Well, the new import makes professionals and experienced LR-users push away from Adobe in frustration.
LightRoom team,
I am glad you at least posted the reasons for the changes.
Any software of the complexity of LightRoom requires an investment by the user to understand how it works; if instead you want to make everything intuitive you will have to remove significant parts of the develop module. For example, the tone curves, the histogram, brushes, gradients…. All of these take reading, understanding and time to learn. As such I think you should remove them immediately, since they will confuse the users.
Tim
So will you continue to redesign LR to please new users ?
In the develop module remove all sliders and only have one button : AUTO ?
And only options to Export to facebook , twitter instagram ?
Ohh , sorry, Export is to advanced.
‘Send selfie to facebook , twitter, instagram’
As one suggested , why not just create a LR Elements. You allready got an PS Elements
and Premiere Elements.
Your research design is flawed if you focused only on new customers. It should have included a cross-section of advanced users as well to determine what functionality advanced users deem important in their workflow. I think you’re getting that feedback now from the advanced users. Your solution to “simplify” the Import process is flawed also. Would a 10 minute tutorial on how to use the Import function have significantly reduced or eliminated the new users’ frustration? Dumbing down the software to the lowest common denominator might not be the best long-term solution to maintaining the loyal user base that you currently have.
Sorry Adobe. This change was really poorly executed. And this blog post ranks up there as one of the lamest explanations for a change that I’ve come across in the software industry.
“Over the years we’ve done extensive studies of customers interested in Lightroom”
the problem is simple: if you want to turn LR in a software for novice users version 6.2 is a big step ahead. if you want to continue to provide software for professionals and advanced users this is the wrong way…
I have Adobe photography plan subscription since a year or so. I am just an amateur photographer. I used Photoshop elements in the past. I am a long time PC / Windows user, but switched to Mac some years ago. I can think in files and folder structures and never liked the catalog / database idea of Elements. That is why during my subscription period, I ignored LR and only used Bridge and Photoshop. Only recently I started to use LR, because I had the feeling that I wasted money by not using it and everybody says I should use it. So I did. My experience was not bad. In fact I started to like it. No real problems with the import / export, that I feared so much. Then came the update, Capitan and CC with the modified import dialog. The first use of it, made my iMac hang up and in the end I had to do a complete restore from the Timecapsule. This did take several hours. Something like this has never happened before during decades of computer use. Can you imagen my disappointment as a novice LR user ?
Alright Adobe
1. If you want a LR for Dummies bring out a LR ‘Lite”
2. What happened to the betas on Adobe Labs for comment before releases?
3. It is irresponsible to change a program used by working professionals on a daily basis without some kind of warning.
I have used LR since before it was LR as Pixmantec. I am an Adobe ACE for LR3/4/5.
Disgusting!! Disgusted!!.
So you showed it to a group of people who were intimidated and decide to simplify it and remove features necessary to advanced workflows??
I was intimidated by your software when I started out but I took the time to learn how to use it (and I’m still learning). Your software has always been designed with professionals’ needs in mind and if you want to use pro tools you take the time to learn how to use them. This time, you are telling the pros they have to deal with inferior workflows so the new users will be happy. Huh??
Has Adobe been reading Apple’s playbook?
This statement is unbelievable.
„The previous Import experience literally made people push back from their computers in frustration.“
The present import experience makes me want to cancel my subscription.
Now what is worse Adobe?
Installed this, now my hourly crashes result in crashes every 5 minutes.
Lightroom has gone backwards in reliability.
What on earth are your programmers and QC testers doing?
This is unacceptable from PROFESSIONAL level software.
OS X 10.11, 15″ Retina MBP Late 2013.
“Please keep the feedback coming!”
Gladly.
Just a few random thoughts: I’ve held off “updating” LR so maybe there are some non-obvious mouseclicks involved on the “improved” interface I can’t see (and there’s a hint as to its efficacy right there…)
One only needs a brief glance at the two screens shown at the head of this thread to spot an immediate show-stopper: how can I tell which images I want to import when they’re tiny, dimmed and partially hidden by a great big tick? And, after having unselected the image to get a (marginally) better view, how am I supposed to have a closer look to check for things like camera shake/out of focus and all the other slip-ups that make an image not worth importing?
It seems I have no way and I’m expected to import the lot, space-wasting duds and all.
And where are they imported to, exactly? Looking at that “simpler” interface, I now have absolutely no idea where previously it was easily selected and very obvious, right there on the screen with no additional fiddling.
Why scan the entire disk system for images on the off-chance of finding something to import? I have many other images on my system which I will never import into LR and yet LR would pointlessly trawl through my 25 TB filesystem like a mindless robot, digging them out for me anyway.
I realise this can be switched off, but I fail to understand how presenting a new user with a rag-bag of any old images unearthed on their filesystem was ever considered as an ideal default state. Especially when they have no adequate means of examining each image.
I wonder why was the “move” operation dropped?
I used to be able to examine, select and move only those images I was interested in importing which automatically cleaned up the source, now left containing just the unwanted images. With only a copy option available it seems I’d have to make a note of the images I’ve copied and manually remove them from the source later, outside of LR. Or maybe manually examine and move the images to the destination – again, outside of LR.
Likewise, I can’t think of anything justifying the removal of the “eject” functionality and surely, by forcing one of these poor new users, apparently unable to consult the help or the many other excellent on-line resources for this one interface (I shudder to think of how they’ll manage with the real “meat” of LR) – forcing them into finding how to eject their card via the OS, again outside of LR, will only make what was a one-click operation more complicated and error-prone.
How can that possibly be called simpler or more friendly to new users? I mean really, if a user is confused by the presence of an “eject” option then this surely indicates further basic training is required – and well outside the remit of LR. It therefore seems perverse to cripple a previously fully functional interface in a fruitless attempt at simplifying “eject SD/CF card” by… removing the option.
I suspect there will be data loss occurring as the card is just yanked out because there is nothing on the import screen to suggest it should be (properly) handled any other way.
Echoing what others have said, examining the reactions of first-time users of LR seems to me to be counter-productive, /because/ they know absolutely nothing about how it works.
Any software is confusing to someone who has never seen it, but this doesn’t necessarily automatically translate as it having a poorly designed interface – but here, that appears to be the decision taken. This seems quite magnificently irrational to me, considering all the other superb and /consistent/ interfaces of LR: not one of which looks like this new Fisher-Price interface and very many of them deal with considerably more complex actions than importing images.
I wonder if we can now expect some of that functionality to be replaced with one giant button saying “Make picture look nice”.
That seems the desired end-product, if this awful over-simplified interface is considered an improvement.
There is so much more but I’ll leave it at this and respectfully invite you to consider the many other and more detailed objections on this thread:
Removing the earlier import functionality trashes the established workflow of anyone (who took the time to learn how to use LR) – and that runs directly counter to the workflow-based construction of the LR environment.
Please rethink this.
Still experiencing a frustrating slow response despite Unchecking “Show Add Photos”. The changes to Import have added 2 additional steps to my workflow that had already been incorporated: creating a folder as well as applying a preset – unless these are hidden now in an effort to be more intuitive 😉 If I am overlooking this, please let me know! If not, please bring it back!
The new Lightroom is a nightmare. Crashes EVERY TIME I open it.
I unchecked the ‘Show Add Photos” and nothing changed.
This is not ready for primetime.
As an IT (software) professional I strongly believe you should fire the project manager that came up with the new Import dialog idea. Seriosly, what were you thinking? Only new users matter to you? What about your old customers? You know.. the ones that PAY for your subscriptions? I’m extremely dissapointed!
I don’t like the new import dialogue. I agree that the original required some learning but it was powerful. I hate this trend of making everything “easy” for the smart phone masses and their stupid selfies. Ah well, the time has come to really start learning Capture One 8, the new standard for professional photographers!
Dear Adobe developers
We understand that you have a large market share when it comes to dealing Lightroom and Photoshop.
However when you loose touch with your market and what they want, eventually they will find other solutions.
For example you made a choice to shift to a subscription based product format, that upset many individuals but they were ok with it because you let us keep the older perpetual license versions running and gave us updates.
Then you started to leave out updates for the perpetual license i.e. camera raw and dehaze not for perpetual users
Now you peeve off a bunch more when you update Lightroom and they can’t tether cameras (Nikon and Leica) nor do they like the dumbed down crippled import interface.
Please we beg of you listen to your users that have supported you for a long time do not force us to leave and switch to Emulsion, Affinity Photo, Gimp or another product .
Have you read the literally hundreds of appalled users of LR on the Forums? Go to Laura Shoe for a taste. Like someone says earlier, incredibly you only asked new users, so you removed items us pros rely on every day for our livelihood! What an admission. I don’t know whether to admire your honesty for admitting to such a thing or boggle at your crass stupidity for doing it.
It is time to bite the bullet, admit you got this one wrong, and give us back the folder tree, eject after import, move, etc etc. By all means make these optional and hide them from the newbies until they learn how to use LR, but we need them back.
Every previous update of LR I have looked forward to, and it is an awesome product that has just gone on getting better – until now.
Time to put your hands up, say sorry to us pros, and give us what we want.
Take a leaf out of Apple’s book and hire designers who can make a UI simple and intuitive while hiding immense power under the bonnet, and you will keep us happy AND get your new amateur custom.
Adobe has consistently and relentlessly marketed Lightroom as a solution for professionals, encouraging people (like me) to move over from other software like Aperture, etc. No wonder people are so pissed about the changes to the Import interface. Adobe admits they have made these changes for beginners. Why not spend the resources making tutorials instead? Simplifying and Removing Functionality is not the same thing, Adobe. This update is another reminder that you can’t expect a software company to not gut their own product and you should always have alternatives in mind. Please Adobe, do what Apple did after FCPX came out and ask pros what functionality they miss from the previous version and you’ll know exactly what needs to be brought back.
I n the old import you could have multiple photo shots on you sd card and be able to import individual days by selecting the folder by date . With the new import this feature is gone ..
If you are a pro move somewhere else. I’ll go DXO
I was mostly curious when I first saw the new import screen. I was expecting something awesome, but I was left feeling quite frustrated. I was one of the people who could no longer import photos until I unchecked the “Add Photos” box. It took me quite a while to get that answer, so I wasted several hours at work trying to work around the problem. Very annoying, but yes, it’s a bug, and with the workaround, I’m back to doing my job. That’s not why I’m upset, now.
The real issue is the choice to streamline away so many of the options. I agree, the old import screen could seem intimidating to someone who refuses to take the time to actually read or watch instructions as they begin. But once you understand it, you know there’s a very good reason those options were there! Sure, not every person is going to use every option (I never used “Move”), but that’s because we all have different workflows that suit our situation. I used the checkbox for choosing whether to import previously imported photos or not ALL the time. Why would I want duplicates in my catalog? Because I am trying to organize photos that are spread across many network drives, many of them duplicates with different names. Trying to find and organize them in Finder is much more difficult than doing so in Lightroom. So, I’m frustrated, and I’m definitely not alone.
It’s obvious that Adobe wants more casual snapshot shooters of selfies/kids to use their products to organize all the thousands/millions of images they’ve taken. Fine. That’s great! I’ve even encouraged friends with kids to try using LR to work with their photos. For those people, a newer, simpler import is great. (Though, I agree with one person who posted who wondered why the selected photos are dimmed, while the rejected ones are bright…seems backward to me.) But not at the expense of functionality for the PROFESSIONAL photographers who make their living using LR. I don’t see why having an option to see “advanced” import features wasn’t the first thing the development team thought of! It seems pretty obvious to me.
But I’m even more concerned about the shift in product development to target a different audience. It seems to me it’s time we have a LR Elements. Seriously. If you’re designing the features to suit casual photographers who have no patience for reading directions and want to just click a couple of times to get something that looks passable, the REST of LR is going to confuse them. I’m dreading the thought of opening LR after the next update to find that the entire develop module has been replaced with a simple “I’m feeling lucky” button to make adjustments easier. I mean, all those sliders have got to be confusing first-time users, right? And if those are the target audience, then that’s what Adobe’s going to do? That would be a travesty, but it’s the logical progression. So, PLEASE make a LR Elements. It can be nice and basic and easy for a newbie to use. And keep LR for the professionals and serious amateurs who really want a digital darkroom/comprehensive filing/labeling/exporting tool to manage their images. You can’t serve two masters, and trying to make one product suit everyone doesn’t work, either.
what really puzzles me is that adobe has learned nothing from the microsoft “smart menu” debacle.
I don’t care about the import interface…
I care about the fact that this big company with this horrible 6.2 made me lose a job…simply lightroom stopped to work and no way to develop the photos
thanks adobe, very well done!!!!!
I hope all the worst forr you
While I would agree to the possibility that new users struggle with the import dialog and perhaps a solution is required to solve that problem I certainly do not agree with the current solution as advanced by this update.
Trying to attract new buyers of a product by totally alienating the existing user base is, IMHO, a very poor business strategy.
I am unhappy with the removal of functionality but the real issue for me was the release of an update that was clearly undercooked for the sole purpose of marketing leaves an exceptionally bad taste in the mouth.
This debacle should not be laid at the door of the engineers but, rather where it belongs, with the business and marketing side.
If the new import dialog is to continue at least allow the existing user base the simple courtesy of using the powerful functionality of the legacy dialog.
This update should also be a strong message to Adobe not to release updates prematurely – many of us actually use this tool to make money, we cannot afford to have an unusable app.
The new interface is a broad outline of what it could become…just a start. It needs a lot more work before it will be anywhere near to a good import facility.
Make a dumbed-down version for new users, but please give us long-time pro’s all the advanced options from the old version back.
It just worked, day in and day out.
Adobe’s standard response at the moment is to turn off the new interface…so did you guys know it was not ready for prime time before you released the update?
Why release a new feature and then tell the world to turn it off? So counter-intuitive! Don’t, even unintentionally, throw bugs at us!
Add another yes to please restore all features removed from Import.
Another notable embarrassment about the new “Add Photos” screen is just how awful it looks with its background of an utterly banal tourist snapshot of a lake, and badly color corrected at that.
What UI designer thinks that this is a great looking UI?
What UI designer thinks this UI represents aspirational imagery, even to the rank amateur?
you should at least rollout such “updates” with a big red exclamtion mark in the Creative Cloud panel, and the hint “be careful, this update will remove important functionality” 🙂
So Adobe has become so “PC” that they now worry about offending someone with software new users have to actually spend a few minutes learning? That’s pretty much all I got from this article. As others have said, I don’t get why Adobe didn’t actually consult with actual users instead of newbies who just want to upload selfies and pics of the cat to Facebook. Why stop there Adobe? Photoshop is pretty dang hard too. Why not dumb that down, so you don’t offend anyone looking to put a snapshot of their breakfast on the moon?
I’ve been using LR since v.1 and have never had a hard time with Import, or any feature for that matter. Ya know why? Because I took the time to learn it, which wasn’t hard in any way, shape or form, just took a little time. Adobe has lost focus, and is now catering to the selfie market. LR will soon become a toy, full of useless, consumer-level, social networking tools that professionals will rarely use. Come on Adobe… get your act together and right this wrong.
-End of Rant-
Why not just have the option of which Import screen to display – the old Import screen for “Advanced” users, and the new Import screen for “Basic” users. Why force ALL users to use a single Import screen.
I want to add my voice to the complaints about the mess Adobe has made to the Lightroom import screen. When I started using LR, I had to learn how it works. That included learning about the LR data management model. Once I understood that, the import screen was not hard and provided all the functions that I needed. If new users don’t understand the import screen, maybe it’s because they don’t understand much about LR and need to spend some time to understand the product? Not everything gives instant gratification and has to be ‘dumbed down’. And, if they don’t understand the import screen, what chance is there that they will be able to use the develop module features? You don’t need to remove features from import. You need to recognize your core market, keep them happy and provide ways to educate others to use you r software. Focus groups only on beginners to test changes to a complex product is a dumb approach and a sure way to mess things up – like you have done with LR 6.2
I do not like the new import system on Lightroom 6.2…I do like the update part with de-haze feature on different tools. I would gladly give up the new de-haze feature to go back to Lightroom 6.1.1. Please inform me as to how I can go back to previous version.
This line really made me angry ” Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.” It tells me that getting new customers is more important than keeping the ones you already have
This line really made me angry ” Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.” It tells me that getting new customers is more important than keeping the ones you already have.
Did the above recommendation-no change to the problems I have
LR 6.2 + Mac OS 10.11
Lots of interface problems, selected image doesn’t show for ages
message box won’t go- even if I move the rest of the window
Zoom and hand cursor swapped(i.e. shows hand when small and zoom when 100%
Cell view options don’t stick when changed
and other bits and pieces
I’d heard there was a way to get back to 6.1.1-please let me know how?
thanks
I really hope that this disaster has shown Adobe that running a public beta program (and taking note of the feedback it generates) is much better than keeping everyone in the dark, then forcing untested changes that no one wants on everyone.
As disappointing as the “update” was, this response is even more saddening. I had no issues learning the import menus when I first purchased Lightroom, and Lightroom was the first editing software I ever owned. I’m not sure who the testers were? People who had only used mobile apps? Of course this will be more difficult. It’s an advanced program. If you want to make it simpler, that’s fine. But removing functionality that a significant portion of your long time users require is a ridiculous solution. If people are really finding it that difficult maybe Adobe needs to better educate new users – both how to use the software and what they’re actually purchasing. If it’s still too difficult then come out with a Lightroom Essentials, or Basic or something for the more casual user.
Lightroom’s power is not only it’s editing tools but the image management. It’s the latter that truly separates it from most other software. Lose that and why would anyone stay (or buy) Lightroom?
And removing the “eject after import” is just plain sloppy programming.
“Keeping the existing Import experience isn’t an option,”
yep. adobe team really does want feedback. not.
I usually say “don’t shoot the messenger” but in this case the utterly tone deaf and arrogant tone in this blog post in reaction to the justified outrage of the LR user community makes it clear the first step in resolving the debacle needs to be “fire Sharad Mangalick”. Anyone who thinks this is an appropriate response to the disastrous 2015.2 release isn’t in a position to have any positive impact on the future of Lightroom. Listen to your users and admit your failings and errors is the first step. If Sharad’s job is to write this blog to engender any positive feelings in the LR user community this blog post is clear evidence he can’t accomplish even the most basic functions of his job. And the fact this was even published demonstrates that whomever is further up the food chain from Sharad is either asleep at the wheel or actively trying to drive the Adobe LR bus into a ditch.
The Lightroom 6.2 release is defective and should be recalled.
Use your focus groups to decide how to respond to customer’s complaints. Do not insult your customers.
Let your executive team determine whether this release has damaged reputation.
Instead of dumbing down the product, perhaps better education is needed
True, it wasn’t intuitive when I first used it in version 1, but once I figured it out it was all there and straightforward to use. The current version didn’t really change what can be done it has just hidden a substantially similar UI away behind the gear icon and that new UI broken (Starting number and Shoot Identifier appear but have no entry box on my system; text entry boxes are dark, text is darker gray on dark gray…). Sure, when someone first installs LR now, it will copy the images, complete with cryptic camera assigned filenames to the Pictures folder without overtly offering them any options. Then when they realize they should have been adding keywords as they import them, renaming the images with a sane name, and including a copyright in the meta data they’ll click on the gear icon and voila, a substantially similar and minimally intuitive UI we’ve had since version 1.
I will be the first to admit that the previous import experience wasn’t very intuitive so a rethink is a good thing but where Adobe completely dropped the ball is in choosing to go with an extremely gimmicky look and feel for the new experience that is completely inconsistent with the rest of the UX AND cutting features in the process. The team needs to admit they screwed up, have another rethink, get rid of the Mickey Mouse UI and improve the workflow while maintaining a consistent user experience with the rest of the application. And whatever you do, please do NOT try to take the horrible, big, ugly, screen real estate wasteful W10 style UI you tried and failed with in the new Import experience and try to extend it to the rest of the app.
Shared,
The functionality removed in the “new” import screen impacts my workflow in a very negative manner.
Please restore the “classic” import functionality.
Allow users to toggle to the new mode –
It’s ok to default to the new interface. Let new users experience it. However removing workflow functions after years of use (I’m an early adapter from v 1.0 days) is without doubt an error.
Let me echo similar statements: LR is professional photo editing software. Not Apple’s “Photos”.
Look at the Develop Module. It’s NOT going to work well for people who snap selfies on their phones and occasionally dabble with more serious work or more demanding gear. The new import interface is not consistent with the rest of the tool.
Respectfully, and a long time LR and PS customer
I agree completely with Stephen Starkman
I can’t stand the new import function. I went to preferences hoping to restore the former interface. Did not work. At least give experienced users the option to use the features they are used to, and not waste their time with the new import maze. I would like to be able to make the decision to move my photos, or even to add duplicates if I so desire. C’mon Adobe, honor your long-time users. I am going to reinstall the last version.
Agree with most of the more experienced users comments – seems Adobe has targeted the new user obviously to sell more licenses while forgetting the experienced – yes we should have an option to turn on the new features or leave it alone – fine to have the new as default for new users but an upgrade should ask if you would like to try the new interface not force it on you – starting to be like Apple!!! (yes I use both) The new flow sucks – and to be crashing so many machines is even more disgraceful adobe – shame on you
Please fix ASAP. I wasn’t crazy about the old import module but I don’t like the new one at all.This is one of the worst updates in Adobe history.
Respectfully, and a long time LR and PS customer
I’m a LR user since the beta of version 1 and a long time Photoshop user and teacher. I love Lightroom and am distressed at the loss of functionalality in the Import module. You folks are very clever, isn’t,there a way to enhance the import experience without removing the functionality that so many users depend on? Why not have an “Advanced Import Mode” available as an option.
It seems unfortunate that you have made so many people unhappy including me.
I have never been disappointed by an Adobe product or update until this moment. Taking out key features from the Import section is…well…I’m speechless. What on earth were you guys thinking? Like most of the comments above, this is a product more geared for pros, and there are plenty of other programs for the newbies. You, basically, completely alienated your current core audience, and in my case, have put me in a pretty bad place with my current clients. For the love of God, please find a way to bring back the old, perfectly functioning, import section. I get that you want to make things easier for the newbies, but don’t screw the pros in the process. I think it is pretty clear here that you have caused much pain, and I hoping you immediately find a way to fix this disaster. Please!
Count me as one more user who does not like the new import dialog. I would much prefer the original version, or something similar. How about (in prefs) offering users the choice of “streamline” and “advanced” import dialogs, with the default for new users to “streamlined” and the option for those who want it to use the original “advanced” dialog.
Please restore the “classic” import function.
The removal of the “Do Not Import Suspected Duplicates” checkbox has destroyed any confidence I had that Adobe wouldn’t make those stupid dumbing-down mistakes that Apple and others have made.
This is a disaster, and, if uncorrected, terminal.
Who did this market research, FRANK LUNTZ?
Please bring back the old, far more better import photos dialogue. The new one does not work at all. Or please let the user to decide by preferences. Do not force this bad decision.
The summary removal of features many of us depend upon is unacceptable. This is exactly the scenario many of us predicted and feared with the introduction of the subscription model. Adobe no longer has to satisfy existing users because their income does not depend upon voluntary paid upgrades requiring positive updates. Only new users count for new revenue, so the decision has been made to dilute LR into a glorified Instagram app to appeal to the masses. This puts high-level LR users into the position of finding alternate software for LR, but pay for it anyway or lose Photoshop.
I’ve been a LR user since v1.0, and a Photoshop user since v 4.0. I have purchased every upgrade to both up through CC2015. LR is easy to replace: I own Capture One Pro. Although I prefer Lightroom in many ways, I will switch to it unless this is resolved. I also intend to reinstall my perpetual PS CS6 product. If Adobe does not rectify this travesty or touches another module in this manner, my subscription will be terminated.
I do a lot of training in Lightroom and I think what bothers most is not the import panel but the logic of import.
By trying to please everyone you end up pleasing no one. This is successful with this update.
Someone or some people from adobe should get fired for this mess.
You’re hurting your loyal and professional LR customers. Specially those customers from the early 1.0 version like me.
Very very very disappointing.
What a feeble statement from Adobe. What an insult to long term Lr users. This ill-conceived, premature release is a major embarrassment to Adobe. And who approved that Import dialog? Sigh…
Can’t wait for the properly repaired v6.3
I am a Lightroom User from the very first Version. I totally disagree with the opinion that “previous Import experience literally made people push back from their computers in Frustration”. I never had Problems with that and I am far away from beeing a pro. I think, if someone did not understand the Import dialog then this Person will not be able to use the rest of the Software too. But it’s a decision from Adobe to change the UI so we have to live with it or choose an other Software. In my opinion changes like this has to wow the users and not leaving them with a crashing Software a bad workarround and absolutely no Information about a timeline for a fix. For me it is absolutely impossible this error was not discovered before delivery. That brings me to the Point Adobe rather accept disappointed customers then delay a delivery-date. And that is the real Frustration Thing. Looking Forward for a fix.
My view on the change is that it is now far from convoluted than before – the dialogue does not allow for quick and efficient import of photos – certain critical features previously available are now hidden/difficult to find – inevitably requiring searching/navigating back and forth rather than having them at hand from the start
For example – where is the ‘ignore duplicates’ check box? You no longer see the whole tree of folders on your drive to select an existing folder but now need to navigate via an unnecessary separate interface to it for every import…
Sometimes, in order to simplify, you loose valuable efficiencies that causes the problem to be a lot slower
The crashing and slow operation are equally frustrating 2015.1 was slow enough to start now its even worse have rolled mine back in time machine to 2015.1
As for the import experiance they could have made it like Aperture it worked flawlessly in both cases Lightroom in 2015.1 and 2015.2 are messy and poorly designed not what you expect from a company with Adobe resources.
Lightroom used to be a pro software. Any pro, who had used Photoshop or any pro designer software, had to spend maybe 5 to 10 minutes to fully understand the import dialogue and all of its features, which are clearly needed for a pro to make his job easier.
I also think, that Adobe is trying to fish in the consumer market for more and new customers. And of course, most of these people don’t even know, that many different images file formats exist besides jpg. No wonder, that such a person will be completely overwhlemed by Lightrooms import dialogue. But then, they shouldn’t try ro use a pro software or take the time to learn it!
Adobe also gave us face recognition in LR 6, which for my part, is the worst peace of software that I have ever used out of the Adobe stable. And I am using PS since version 3 and LR since version 1. How that ever got through any quality control is a total mystery to me. Anybody trying to use that with a catalogue of more than 10.000 pictures will know, what I am talking about. LR is super slow, unresponsive and basically unusable.
So far, none of the updates have cured that problem.
Adobe would be wise to start correcting all the problems, that LR has under the hood. It is becoming a big sluggish and unresponsive tanker! Give me an update like El Capitan is to Yosemite, fix the major problems under the hood, concentrate on speed, snappiness and responsiveness! I don’t need new features right now, certainly not dead born features like face recognition (where I wasted 2 full days trying to get it to work), but a program, that works stable and fast to let me do my job!
After all, most people who use Lightroom are photographers, who make a living with their work! They don’t want to become beta testers for consumer software. Like someone said, do a Lightroom Express for those people.
Hi,
although I was not able to update so far, as the app manager refuses to connect to the Adobe-servers since two days, I am aware of the changes, and I must say that I am also really bothered about the new import dialog.
Really; I do not care about it looks, but about the functionality and the features that have been removed.
Especially, I do not understand, why you have removed the preview section (file names, file tree showing the locations where the pics are going to be copied to, etc.).
Right now, I am not sure, if this is acceptable for me or not.
Maybe it is a good thing that I am not able to update at the moment.
I hope that Adobe cares for its long time user community and brings back some of those removed features.
I mean, it should not be such a problem to give the opportunity to switch to a more advanced dialog, which offers at least some of the old but important features.
Cheers
Ok, Adobe. You gave the LR developers a deadline they could not really meet. (PIX 2015 convention).
Now please do the right thing. It is totally possible to have two different import dialogs. User selects which one to use in Preferences: “Basic” or “Advanced”. The latter being the one that we already have. Then Adobe can water down the “Basic” import as much as they see fit for the non-tech people.
I agree with you…hope Adobe listens and gives us longtime users of Adobe our Import option…I am not happy with new Import Adobe has forced us to use.
I’m disconcerted; puzzled; perplexed; taken aback; nonplussed; bewildered and mystified (and so on, but I run out of synonyms). I’m a CC user and this is the kind of operation that I fear most as a subscription user. The subscription method is – among other things – a matter of trust. As in “I trust Adobe not to f—- things up”, or “I trust Adobe with my proven workflow, which is entirely dependent on their tool”. Now I feel like Adobe is pulling the rug out from under their users, and tha’t a bad, bad feeling indeed.
About 10 years ago I was happily using a program called Raw Shooter. Adobe was at the time developing Lightroom. There was technologies within Raw Shooter that Adobe wanted to incorporate into Lightroom. So Adobe bought out the company who produced Raw Shooter. When Lightroom became available for purchase free copies were provided to Registered Raw Shooter owners. I being one got that free version and been using Lightroom ever since. I love Lghtroom. I am not a professional but an advanced user. I saw the posting about all the issues with 6.2 so I held off on upgrading. So happy for that. From everything I’ve read about the changes to import has gotten me anxious. Until they fix the but issues with Lightroom crashing and issues with other applications that I export to from Lightroom also having serious crashing issues with the new 6.2 version of Lightroom, I’ll have to hold off on serious critiques. But I will say, I don’t see the issue with the auto eject of card. I myself never used it as I might come back with hundreds of photos to import into Lightroom but they would not be imported to the same directory but different locations based on content. With that in mind I’m concerned about the new import not showing a directory tree of where files are being imported to. I can see lots of photos going to the wrong directory now. Like most people, we don’t like change and tend to resist change. Hopefully adobe knows what they are doing, hopefully they are not going only after the smartphone user who doesn’t know the difference between jpg, dog, cry, tiff etc. Who can care less about lens profiles, aberration, saturation, – you get the idea. My fear that the change of the import process to keep beginners from pushing their chairs back is the tip of the iceberg. What’s next is they will change the develop module to make it easier. Then move on the the next module and so on until the useful product it now is becomes dummies guide to processing your photos. Will see but the smartphone photographer may be the death of Lightroom as we know it today.
Looks like you arew going to bring the same GUI style to other modules.
If this will be the case…grrrrr!
For my work, I can’t see a single improvement in the new dialog. The biggest disadvantage over the previous one I found so far: you can’t read the file name unless you move the mouse of that particular image. Which is required eg. to distinguish between RAW and JPG. I shoot RAW+JPG because this gives better means to check sharpness while shooting, but afterwards I only import RAW.
I ‘d wish we could have the previous import screen back. It may not be the latest & greatest in usability, however it is consistent with the rest of the application.
This explanation of why you changed the Import dialogue from something that worked perfectly to something completely useless is the most idiotic thing I have ever heard. If you want to make Lighroom for non professionals, make a dumbed down version (like you did with Elements, remember?). Glad I bought a desktop version, I was thinking of getting the CC for PS, but now I think I will learn Affinity instead. I actually feel insulted by your explanation.
Although an amateur photographer I capture large numbers of images from the studio and street scenes and I rely on LR to structure them and let me get back to images I reuse time and again. The import process has never been perfect, and even on a top end iMac it can be slow, but the best feature was the ability to quickly see and set options. With the new interface I was left wondering how I toggled ‘ignore duplicates’ on and off and a range of other things. Then I found that LR crashed altogether when I tried to export images. How could such a critical function not have been tested in a major new release. Surely rule number one with prosumer software is ‘don’t throw the baby out with the bath water’. Professional software needs to be robust, flexible and high performing. Intuitive is nice but not essential. Microsoft Word has huge complexity but even casual users soon get the hang of the parts they need to use (because they need to use it). If a new user cannot engage with LR enough to get passed the learning curve they probably don’t need the product!
It’s great Adobe is spreading the success of LR to new groups of users, making it more accessible while providing great feature upgrades that enhance our creativity! That’s what I’d say when I’d be working in the Adobe press office – but as a mere existing (not new) LR user I have to state…
… There’s a difference between ease of use and “dumbing down”, making LR the “little brother” of PS – is Adobe going GNOME 3 and competing with ACDSee Pro?
Esp. the removal of the “Move” reads as an April Fool’s Joke. I regularly quick-rate/review and process shots with other apps – all on the same hd using “move”. Does Adobe insist I do it all inside LR (including HDR/Pano), in essence breaking the manual prcoess/import and export/process/re-import path?
Please do yourself a favor and re-add the “Move” option, it’s not like it’s a major clutter to the interface. Or do you fear your users are too dumb and lose shots because they don’t realize what the difference between “move” and “add” is?
The new dialog is not really more intuitive, than the previous one but features that are helpful have been removed and the App has become unstable. Can’t be much worse.
Next time, please make UI tests not only with new users but also with customers who use LR in their daily life.
And test the application on current operating systems as well. I guess there are not many software developers out there, that introduce new software versions that do not support current OSX. Without warning! I do not want to read forums before installing CC updates, but I guess I have to.
Ignoring the current customer base for the sake of gaining new customers is an approach that is successful on the short term. Only.
Here we go again. I updated to cc2015.2 and above the name it says synching 1072 photos. It will not stop syncing. So Adobe fixes lr mobile in the last version and now we have a problem again. Do you guys at Adobe ever check to see if things are working? I am also reading about the import process, which sounds like a major blunder as well.
so after going back to 6.1.1 for work i installed the v6.2 trial in a VM to have a closer look at the “accident”.
with the former import dialog i was able to quickly import only images shoot on a certain day…..
now after 5 minutes of looking and searching. i see no way to do that with the new import dialog.
is there a way…. or is this “streamlined” too?
honestly .. if this is the case.. how can someone think that removing this usefull feature is improving lightroom?
are there any coders or decision makers at adobe who actually work with LR?
Whatever you did, you broke more than import. I’m unable to drag folders to new locations on my C drive because it shows them as grayed out. Not missing. If you choose to locate the folder, it shows the current, correct location, yet when you click ok it is still grayed out.
Import is also very, very annoying now. Poor decisions were made. When is Adobe going to learn to put out public betas before releasing changes of this magnitude? This is like what happened on the print side with the new version of Acrobat.
Hello there!
I can’t even click on Preferences. Lightroom displays an error message (LoadLibrary failed with error 1114).
This doesn’t happen with 2015.1.1
Anyone experiencing the same problem?
Regards
Julien
adobe released a hotfix 6.2.1 today…..
synchronize folders bug is NOT fixed.
import dialog is UNCHANGED.. still the dumb version.
my lightroom CRASHED 4 minutes after start.
and i have the latest drivers installed and the “add photo” screen is disabled.. good work adobe!!!
//sarcasm off….
Dear Adobe,
we want the classic « LR Import Dialog » back ! Please give us the Choice : in the Preference Panel please. Thanks.
PLEASE ADOBE…give us a choice!
While developing and exporting to JPG I got 3 Crashes…
Worst Version I’ve see in the last 8 Years.
Every version of Lightroom is getting worse. Bring back the Import features and the card ejection.
As someone who teaches Lightroom for years, I have used the Import from Computer as an option for students who were not organized on their computer with images in different locations. They found that Lightroom could get them organized immediately and make their lives so much better.
Also, since CC has come out, the program has been so slow. You are asking for money from me every month, but end up taking more of my time. When do you start paying me for my time you are wasting?
wacom intous pen + LR 6.2.1 lag when pushing sliders.
it´s next to unusable.. i have installed the latest wacom drivers (WacomTablet_6.3.15-1.exe).
there is, i would say, a 1-2 second lag from when i press down until the slider moves.
win10 64 bit, i7 2600k, 24gb ram, 980 gtx, catalog and caches on intel 750 SSD.
gpu is disabled, add photo dialog is disabled.
and of course….latest gpu drivers are installed.
Updated to 6.2.1 and still having problems with Synchronize Folder. Dialog box shows number of new files and starts to synchronize, but a message comes up saying that there are no new files to import.
The new import dialog is a feature downgrade. This is not what I am expecting for my CC subscription. Please bring the destination folder selection back.
Well, after turning off “Add Photos” and removing third party plugins I can get the import dialog to display, but it doesn’t display anything and the program hangs. OS X Yosemite on a 2009 iMac 27. I can’t even begin to understand how this made it out the door. Going back to the previous release. Good thing I at least have it running on a laptop here. I guess this is one of the “benefits” of Creative Cloud over owning a licence…
I’ve reinstalled the new release and for some reason the import now works. However, I am now experiencing the crash on shutdown problem, even with “Add Photo” disabled.
Good news is that CC LR .2 got Dehaze into Develop Module local tools like adjustment brush
Bad name is that Adobe is willing to ignore the Import workflow and requirements of established LR users to more easily grab new users (folks finally leaving Aperture?). Very mad decision making by Adobe Product Management. Can not emphasize that enough. Then the salt in the wound is that it has terrible design faults that cause crashes and kills some plugins that worked just fine in the .1 release.
To me this is by far the worst LR release ever. Time to cancel the CC subscription and look seriously a C1P.
Hundreds, and perhaps thousands, of enraged current users have posted comments that express their rejection of your changes, sometimes in tones that are just short of obscene. To call this “great feedback” is an insult to those of us who are trying to get your attention; it’s sort of like responding to a drowning man yelling for help with “Thank you for sharing.”
The best thing about the subscription approach is that there is a cost to ignoring current users: We can simply stop paying. If you don’t serve your customers, better competitors will arrive to disrupt and destroy your business.
Didn’t Adobe say that they won’t release any new features to the stand-alone version of LR (that’s why they aren’t giving us the dehaze tool!), but I see they’ve have no problem removing features we already paid for in this “update”!
When I paid for LR6, it was for a known feature set and the promise of bug fixes only.!
I didn’t pay for this crappy import dialog do Adobe you have to to give me back this feature I paid for !!
Do experiment with the perpetual beta testers ( CC subscribers) as you wish but LR6 with bug fixes only !
Changing this import dialog is not bug fixing… it’s feature crippling!!
“Crappy” and “Crippling” is being kind!
This is causing me hours of frustration, trying to figure out how to get my images into my LR Catalog! Synchronize is not working either!
I haven’t installed the 6.2 update and having read the description I don’t intend to do so.
You’ve made an elementary error by getting your feedback from the wrong people! You asked people who don’t use Lightroom already and in so doing you’ve completely ignored and alienated large numbers of people who are already using it. This is no way to treat loyal users.
YES! This is horrible! Worst update ever!
Well said, Jon…….
Make the new basic import screen an option in preferences, to OPT IN!
Keep the old import screen as the default, with all the functions available… simple!
Do it please!
The new import is so bad, how to tell where it should save the pictures, in which folder?
The king is dead, long live the king! Aperture has been replace by a dumbed down Photos and now LR is likely to follow the same route. Like it or not (and I hate it) more photos get taken on iPhones and other smart phones than on DSLRs these days and no doubt that is where the money is coming from. This is likely the first step to oblivion for those long-term users of LR.
Can anyone recommend a sensible alternative to LR and I guess eventually PS please? As for the subscription model, it’s bad for users on every level IMO but I had little option when I bought the D810 as Adobe stopped adding raw converters for new cameras to older versions of PS.
I just saw an update notice. What’s been changed/fixed?
I could write paragraphs about my extreme disappointment with the new import UI, but so many others have registered the same complaint. Adobe claims that there’s no turning back. That logic suggests that the expectation is for current, long-time, loyal users to just suck it up while Adobe pursues a broader user base with a dumbed down product. My hope is that Adobe will see the error of their ways and restore the functionality that has been lost with this current version. That said, please register me as a resounding NO vote for the new interface.
YES!! Well said. This is horrifying! My workflow is now BROKEN!
I do not believe Adobe if they said there is no turning back to the previous Import feature…and if that is the case, I will strongly consider ending my CC account.
I’m running Lightroom CC on Windows 10. After the update I and only launch Lightroom ONE TIME. After I close the program I can not start it again unless I log off my account and log back in. Also of possible interest, after the update my Creative Cloud control panel was just a solid black rectangle. I was able to restore it by logging off and back on. After doing that I discovered the strange behavior of Lightroom. I have turned off Show Add Photos but I still have the problem of only being able to run the program once unless I do the log off/log on thing.
Your explanation for crippling the import dialogue is absurd. Just restore the dam thing!
1. Either you do a complete overhaul of the UI or you don’t touch anything. A completely different look and feel in just one aspect, import, is confusing and counterintuitive: the very things Adobe set out to improve. Bad decision.
2. Whom are you primarily catering for? Existing clients or new ones that have only ever touched an iPhone or maybe iPhoto (or the Windows equivalent)? I increasingly feel the answer is the second group, leaving the existing user base in the dust. Be careful what you wish for, as there are alternatives out there; the folks over at Phase One are laughing their pants off.
3. I have a perpetual license. You promised me no change but bug fixes and new camera support. I didn’t get dehaze (let’s discuss that some other time) yet I do get this import dialog change that I never asked for. Please, either give me all changes or give me none, or at least give me the ones I care about instead of giving me the ones I neither need nor want.
Adobe, from my point of view, you messed up terribly.
Dear Mr. Mangalick,
I really hope that you´ll lose your job soon. From your statement it´s obvious that you are the responsable person for the Mickes Mouse import module. I pray that higher management realizes soon that you seriously harm Adobe. I know that you´ll again censor this post, but it´s important that you read and understand it. You can censor here but you cannot sensor the internet and I realized it´s way more efficient to post my thoughts on your facebook pages.
From the amount of users complaining about the input desaster, it has become very clear that you are not able to do your job. Go to a company that develops software for kids. Maybe you can do that, but keep your fingers away from Lightroom.
Have a nice life
I recently downloaded Lr and Ps to evaluate, and had gotten used to the Lr 2015.1 Import module after some study and usage. After seeing the update notification in the CC app, I went ahead and updated both programs. Have to say that the new look of Import was jarring, to say the least. It does the job, of course, but I don’t perceive a UI improvement. All the “dumbing down” comments are, unfortunately, true.
Adobe, if you’re reading this, please release an update that allows one to optionally revert to the old Import dialog.
Are you guys insane?? You change a vital dialogue in the middle of a version update?? Without the option to switch it back?? Don’t you realize that your customers buy your product version for version so that they can MAINTAIN(!!!) their workflow?? Honestly, what did you expect from seasoned LR users?
At the very least bring back the options as they were before! For Example the FILENAMES!!!
WHAT THE WHAT??!!! Why is IMPORT/SYNCHRONIZE BROKEN!!!
This update SUCKS! WHEN is it going to be fixed??!!! – I will cancel my subscription and go back to 5.1 if IMPORT isn’t fixed ASAP!
My Workflow is BROKEN!! WHY!! WHY?? Windows 10 File Explorer shows 501 JPG files and 1 MP4 file in one specific folder. But LR will only Synchronize 456 JPG files and ignores the MP4 file. This is repeated in other folders.
In another folder, when I select “Synchronize Folder” it shows “Import new photos (935)”, I click ‘Synchronize’, and LR comes back with the message “No photos or videos were found to import.” this = BROKEN!!!
I have a PHONE folder that I add photos to, and LR will NOT SYNCHRONIZE, or Recognize these images after I copy them to the appropriate folder! I have removed the folder from Catalog exit LR, reload LR and still no recognition!! Is my catalog broken? Am I reading I have to import directly from my phone??
NOT GONNA DO IT!!!
WHAT THE HELL!! Who approved this? How can I go back to previous version (THAT WORKS!!)
This is beyond frustrating! Has someone been terminated yet?
Julieanne Kost, HELP US!
MISSING FILES FOUND. (Not missing, just unSynced duplicates)
LR somehow started putting a few of my Phone Files into a folder
C:\Users\ME\Pictures\Lightroom\Mobile Downloads.lrdata\ffe5ff9081280d85d… [truncated]
(Found the duplicated images by using a a Smart Filter and searching Filename)
Issue: I DO NOT even use, nor do I have LR configured to save ANYTHING to my “Pictures” folder!! (Not even my Catalog!) All my photos are on a Dedicated (and Backed up) storage drive, NOT ON MY BOOT DRIVE !!! So I deleted this LR-created folder and the images (above), reSync this “Device” folder. Re-Sync my REAL photo location folder. So obviously LR was not syncing the files it had duplicated in the “Device” section folder. GRRR !!
“The previous Import experience literally made people push back from their computers in frustration. Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.”
If the above statement isn’t changed or modified you can count on me, as a customer of LR from version 1, to be cancelling my subscription with CC and abandoning Adobe entirely as Adobe is arrogantly abandoning loyal users of LR to date. The is NO reason to disable or hide features in the import dialog. You (stupidly) polled non LR users for input but didn’t do the same to current users? Do you care how your paying customers feel at all or are potential new customers more important. If I were a potential buyer of LR and saw the outrage of current users I certainly would not consider signing up. This import dialog functions must be restored. Period. The look could be different or options for “Import Lite” made available for the iPhoto genre of people who feel they need it but for those who depend upon the current functions in the workflow we must see those functions restored. I am not going to upgrade. If I don’t see some restoration at least promised prior to another version then you will see me and thousands of others pay a visit to Capture One, ON!, etc, etc, etc.
AWFUL UPDATE. PLEASE GIVE THE OPTION OF THE “CLASSIC IMPORT” DIALOG BOX BACK.
As a programmer I don’t see the problem of giving us the ability of a classic/professional option for the import dialog. I can understand your reasoning for the change but I cannot see any reason why we cannot have the option to change it to the classic view.
You guys haven’t studied Darwin’s theory on evolution. Survival of the fittest is one key component of evolutionary theory. You are all about to find out what that really means. You guys deserve the Darwin Award for blundering your way into, as you describe it as needing “. . . to evolve the Import experience.” Some species evolved and survived, others weren’t so lucky. How is your new update working for you lately?
Keep your Marketing and accounting people away from your product developers. They have no clue what works and what doesn’t and how changing things will truly affect the bottom line. They needed to issue a comprehensive training video or series of videos and make it available at no cost forever, instead of changing and crippling a great piece of software used by millions of users. Are you guys a subsidiary of Volkswagen? You are certainly behaving like one. . . . Just sayin’
The first time I used Lightroom (v3) it took me about 10 minutes to figure out the import process. I accept a learning curve for powerful software and the online videos are great. Anybody who can’t be bothered with this is probably not going to use Lightroom anyway. By all means make it easier for new people to understand, perhaps with a wizard that guides them through the process, not by removing useful functionality!
As someone said before, confusing as the import screen was, most of the people learned how to use. I understand the evolving idea of new software design, I am happy with that attempt, but I would never get rid of features as you did. People used to have them, create their workflow based on them. Who was the genius that thought that taking away the “Move” or the “Automatic Memory Card Eject” options were going to make people happy. In any case, at least, having been myself a software designer, I would have created a preference to allow people to opt-in or out those features.
Regarding that Import Dialog design… at this moment it seems to be brought from another software as in terms of feel and features has nothing to do with the rest of the software.
I don’t want to mention what happened to me with the crashes as I will really get mad. I almost lost a photoshoot job because of them.
Thank you
Gus
I’ve never been happier about my decision to purchase LR 6 as a permanent licensed product rather than go CC.
Because I wasn’t tricked into installing this update I won’t be subject to the possibility of crashes, and, thank heavens, I won’t have to go through the hell of uninstalling and reinstalling. It also means that I won’t have to suffer the misery of the new import dialog.
Of course, since I didn’t upgrade, my knowledge about the new import interface is from watching videos of folks explaining the thing. Admittedly, this isn’t the same thing as suffering through the process, but my vicarious experience does show me all the missing features and plain stupid changes made. I don’t have to rely on the presenters’ judgments; I can see for myself the greyed pictures, missing move functionality, and ridiculous check marks.
Not being a subscriber also means that I won’t have to cancel a subscription should Adobe fail to acknowledge the insanity of this change. As a long time LR user, I’m not looking forward to changing my workflow, but at least I’m not tied in to Adobe’s business plans.
You can downgrade Lightroom easily enough, within the same dot release range, or otherwise if you back up your Lightroom catalog files, or don’t upgrade them. Just toss the new version (6.2.1 in this case) and reinstall the previous one, 6.2, which you can find at, if you don’t have a copy. It worked for me. I didn’t find this blog thread until after I upgraded to 6.2.1 and was I surprised—and not in a good way.
But you’re right. If there was ever a reason to avoid Adobe’s Creative Cloud, this is a prime example. With CC you cannot not update to the latest version, so you’re stuck with whatever they give you, warts and all.
Like many other big companies, choice is all about doing things their way. Customers can like it or lump it. Or, in this case, downgrade and hope Adobe gets their collective heads out of their collective nether regions and fixes this monstrosity. Like I said before, though, I’m not holding my breath.
Adobe has botched the update to Lightroom. It was poor design to remove the functionality that so many users rely upon and it was poor execution to deliver an update that is crashing on so many user’s computers. In my case, I have rolled Lightroom back to 2015.1.1 and will await an update that restores the deleted features.
Wonder if Adobe wanted to test the Microsoft “update” approach from Win 7 to Win 8 on their “test groups” – pretty much over a Start Menu. Well now Adobe is in the can over an Import module!
Microsoft canned Steven Sinofsky over Windows 8 mess – who is going to take the fall for Adobe mess?
You want to know how to handle downloads? Look at Breezesys for Downloader Pro which allows you to selectively rename files based on camera model AND serial number which is fantastic when you have numerous bodies.
Until then. I vote for it to go back to how it was. It was powerfull AND worked, which is more htan I can say for the IMPROVED version
Because Adobe tells us they made it better because of us, then we are supposed to believe their own self delusion. What a conceited response that they get all this negative feedback and then try an explain why our experience actually must be better than before. Fire whomever is head of customer service. You should be ashamed. I have turned so many people onto your products over the years and now I will try and drive as many away. Adobe you probably feel your too big too fail. Well you just failed.
As a long time user of Lightroom I am afraid that we experience just the beginning of simplification of Lightroom. The way Adobe tries to explain and justify there decisions on the import dialog indicates that the worst had yet to come.
As the “import” dialog is found to be to complex what about Preferences and the Catalog Setting? They are most confusing for people who do not want to know what they are doing. So the next step will be to clean them up too. Lots of things that are going on in Preferences and Catalog Setting do need at least a basic knowledge about file management and photography.
The Develop Module is already mentioned as another candidate for simplification.
But there is more. Lightroom in itself does not need a folder structure to store photos. As a database program Lightroom can store al the photo files in one big “bucket”. The folder structure is a relict from times long ago when you had to organize your photos by yourself. Up till now Lightroom was able to cooperate with a folder structure to organize and store photo’s. But a folder structure is not a necessity. Exif data and keywords are all you need to find photos. So the next step can be an import dialog without any reference to a destination. Lightroom 7 can be made to decide by itself where and how the photos are stored. Maybe you are still allowed to decide to have them stored on the internal hard disk, a external disk or “the cloud”. But that will be all. For new users it is even more convenient not to be bothered by such technical details as where to store the files. Adobe knows what is good for you and for Adobe itself of course.
From a marketing point of view it is even better for Adobe.
Getting rid of the folder structure and moving to one big “bucket” were all your photo’s are dumped will be the next step to prevent existing customers to cancel there subscription. It is far more complicated to abandon Lightroom because you need the database from Lightroom to find your own photos. Or you have to start all over how to organize and find your own photo’s made and imported from the very moment Lightroom started to fill the “bucket”. Imaging going through thousand and thousands of older photo’s to get them organized again.
As Adobe continues to make decisions I do not like and even make it worse, this is the right moment to abandon Lightroom. I have already installed Capture One 8 for processing my photo’s. May be I will ad Photo Mechanics. The combination seems to be a good or even better alternative for Lightroom. I am convinced that Capture One will continue to be software focused on professionals and people who want to know what they are doing.
Just as Adobe tries “to continue to evolve the experience going forward” I do the same.
For me going forward is to abandon Lightroom and to move to Capture One.
Same here, Already was experimenting with CO. Not perfect, interface sometimes seriously flawed. But… professional quality. Something Adobe doesn’t seem to think of importance anymore.
You apparently haven’t been around Lightroom all that long. The original version defaulted to storing photos in a database. You had to make an adjustment in the Import dialog in order to use your own folders. Most of us didn’t like that model and Adobe changed it—back when they actually listened to their professional users. One size does not fit all. The folder metaphor enables us to organize our images the way we want to. We don’t need, and most of us don’t want, Big Brother making those decisions for us.
Keywords and metadata work just as well in a folder structure as they do in a database. Indeed, they often work better because you can constrain you search to specific folders if you want to. And, guess what, not everyone uses keywords and various rating schemes to organize their work. It’s great that you can do so, but it’s also great that you don’t have to.
Apple recently killed Aperture and published the new ultra super super App PHOTOS. It was a change from professionell to consumer needs. And I was forced to change from Aperture to Lightroom.
And now? My worst dreams comes true: Lightroom changed the import Dialog from professional to consumer needs! I can ́t believed it. It is so terrible. Why i can ́t move images anymore? Each point was necessary in the old dialog!
Why there is a new user interface that needed a 30″ monitor for informations that i could formerly seen on 13″ monitor? Terrible. Please give me the old functions back.
And please don ́t use Apple as a role model anymore… it will be worse for professionell photographers…
Nothing more to add to all the remarks above. Just one more appalled and shocked Lightroom user of many, many years. It’s not only the loss of functionality and efficient workflow, it is also the glaring design inconsistency between a sophisticated and pleasing “classical” Lightroom/Adobe trademark look and the hapless attempt of a low resolution borderline fraudulent iPhone App suggesting basic pseudo functionality to lure the completely hopeless into buying.
There really is only one solution, admit the mistake and restore the original import interface.
Never used Import (doesn’t support my directory structure anyway), much easier to copy the files to the correct directory using the file explorer – and then hit Synchronize. Which doesn’t work anymore btw.
Workaround is to tick “Open import dialogue before synch” and let it do its thing without moving the files.
And this “Eject card” thing people are complaining about – is that an Apple idiosyncrasy? Never “ejected” a card in my life, just pull it out when the copying is done.
It sounds like we have a similar workflow. Where is this “Open import dialogue before synch”, that you speak of?
If I can’t Sync folders, then LR is of no use to me.
Also, did they remove the “Skip expected duplicates” (or whatever the verbiage was)?
Oh, “Open import dialogue before synch” in the Synchronize Dialog pop-up. I see and have tried that. but it still doesn’t get all files. I am checking file by file to see what it is missing. Maybe it thinks some files are already in the catalog. Thus the missing option “Skip suspected duplicates”. 🙁
Found a new update to Lightroom today. The Synchronize Folder bug now seems to be fixed. Thank you.
Fortunately, I haven’t updated my LR yet, so haven’t experienced this mess. I rarely update anything till I know it’s going to work!!
Please just bring everything back to the way it was before, and as has been suggested, create a LR Elements.
I personally perform the imports by first creating my directory/folder structure and placing my image files there.
Then I copy the new folder to my backup hard disk, where the directory/file structure is replicated.
Then I open LR – not before. Perhaps this is an old fashioned way, but I haven’t lost any files, and do have backups.
The sample screen shown in Adobe’s original import example doesn’t look like the screen I get when I import using this method,
where all the directory structure is shown on the LH side of the screen in my workflow.
Maybe I’m doing something wrong – but it works!
I’ve added this comment not beacause it has anything original, but every voice should be heard.
You’re not doing anything wrong. I use a similar workflow, and this is what Scott Kelby recommends in his Lightroom books. The advantage is that you can access your photos with other applications like Adobe Bridge, though that is less important now that Lightroom and Photoshop are closely integrated. This wasn’t always the case. Not too long ago, as well, Lightroom acquired the ability to create backups of your files when you import them, which could save you the trouble of doing so as an independent step in your workflow. But I’m not sure there is any real advantage in this, unless you want to use this step to weed out the turkeys before creating your backup files and, perhaps, convert them to Adobe’s DNG format in the process. But it’s nice to have the option.
Adobe could have gone two different ways with this, either of which would have been OK. They could have created an Elements version of Lightroom for people who are intimidated by the regular version, just as they’ve done with Photoshop and Premier. Or, they could have made the simplified interface available as an option in Lightroom for those who want or need it. Instead, they got lazy and tried to fob off this dumbed down version on all of us. As a consequence, this is the first time I’ve ever had reason to downgrade from a Lightroom update.
Here’s the crux of the issue regarding the import changes:
“We visited them in their homes…”
Did they visit anyone in their studios?
Maybe they need a LR-Elements and leave the real LR for power usable!?
Would be better to release a Lightroom “Express” for non-pro users.
This is a tool for the industry not a hobby grade software!
Wow…
Talk about missing the mark! I cannot believe that the usually competent LR team thought this import module change was a good idea. I’m now beginning to have serious reservations about CC in general. After the 2015 update, After Effects CC 2015 now operates at an effective 30% speed and in addition we now have this dreadful LR “improvement”. Not even an option to eject the card after import? No need to detail the long list of problems…it’s pretty much everything that was changed. Incredibly short-sighted is how I would best describe it. If you want to make a product for the iPhone crowd, release a one-button solution for them and restore the functionality of LR for the professional users. You can count me as a very dissatisfied customer!
I am missing “MOVE” feature and ability to turn off “Don’t import suspected duplicates” option. Now I even can’t synchronise my folders if somewhere there are copies of the photos in that folders. Very frustrated. Changes in interface are not a big problem, but missed options are.
In addition 6.2 crashed regularly. Will try to bring back 6.1.1 on my machine.
Dear Adobe,
please kick the marketing idiots from the LR development team. LR isn’t a smartphone photographer tool and certainly not for the masses. In my opinion it is a RAW converter used by people who most of the time know what they are doing. Stop making silly cosmetic changes to the interface. Concentrate on the matters that really matter to the majority of professional users: speed, usability and above all quality. The last upgrade certainly didn’t do that.
Hans
Personally, I feel that the new Import Module has been dumbed down for mobile users and the like and I don’t like it.
It is logical to fear that the next thing to be dumbed down will be the whole Library and Develop modules and will not be good.
How about bringing the old Import page back as an Advanced user option?
Don’t forget that LR is just a tool, photographers use it because it is good and not for a life changing experience.
For the first time I am seriously looking at CaptureOne as an alternative to LR
Why don’t you make a consumer LR? “Lightroom Elements” and keep the real Lightroom aimed at professionals? So silly to crap on your exisitng clients.
This so called upgrade of the import window is a disaster for me and means that I can’t upgrade to the latest version until the old format is brought back for those of us that need. Why Adobe Why?
Why change the import process?
If it was genuinely too difficult for beginners then by all means create a simplified import process as an alternative, but DO NOT remove the original option which works for all existing users. Surely it is not beyond the capability of the software development team to make the import interface an option in Preferences. The original interface was clear, easily navigable, and most importantly, what everyone was used to. When using the new interface I was horrified by such a dumbed down option.
I do not object to change if it is well thought out but in this case it was something that is a retrograde step for experienced users. Even the act of selecting the target folder, which the import files are to be sent, is a clumsy process, never mind the other options involved.
I used to work in software development and this version (6.2) is an object lesson on how not to released an upgrade. Very poor system testing, poorly thought out interface changes and undermining of the confidence of the user base.
I have found the perfect alternative software to Lightroom 6.2, it is called Lightroom 6.1.1. I have removed the latest “version” and upgraded to a version that works properly.
While I am here… Why was the “de-haze” functionality not installed in the stand alone version the Lightroom. Given that the latest release was not version 7.0 it should have been included. Perhaps if the development team did not have to spend time creating software which disadvantaged specific customers they could have got the rest of the job right.
On the nose. By not including features like de-haze in the standalone version of Lightroom, Adobe was trying to incentivize moving to CC. Then they come out with this update and de-incentivize it. Someone there (or maybe several someones) got hit with the stupid stick. They really belong on the unemployment line—not in a corner office. But who at Adobe is accountable any more?
This comment was supposed to be in response to Paul King, below, but for some reason it won’t post. Maybe it’s too many comment levels.
Absurd. I aam okay adding a new “easier” screen for novice users but to remove all the useful tools we have been very comfortable with is simply dumb. Sure, add the new screen so we can have a “Lightroom Import for Novice Users” but why take away what we have all come to love. This is not an improvement to make Lightroom better – it is simply designed to get more money by making it easier for new users. I am starting to really worry about Adobe. After the tremendous disaster with the GPU, now they throw this mess at all the loyal users. What are you guys thinking? Or, are you not thinking at all?
As I read more and more comments, I have a suggestion that might work for everyone. Adobe already made it clear that LR 6 would be the last stand alone version and most of the updates will be made to the cloud version, CC. Adobe has been successful with Elements for “home” usage and here is a great opportunity to create a new product (perhaps called Lightroom Light) and here you can make the screens and dialogs pretty and easy to use for those whose homes you visited and leave the power tools in Lightroom for the rest of us power users who do not need pretty, do not need easy to figure out, and frankly do not have a workflow that in any way matches those people at home you were so concerned about. Time to Wake Up!!!
Where are are all the rebuttals from the beta testers that reportedly loved these changes to the Import dialogue? I have spent the morning looking on the web for possible hidden fixes where one can restore Lightroom to a functional state and have only found negative comments.
I was hoping these changes could be at least controlled with check boxes but to my dismay they are mandated.
Adobe didn’t state their beta testers loved it – the reverse is probably true, but no one is to know due to nd agreements. I understand what Adobe did say completely new users found it easier to use – and that by definition excludes any existing pre-release testers.
Think about it: If Adobe hopes to get 2 new LR users for every 1 former user that abandons it, what will be the decision? Plus the people complaining have nowhere to turn anyway, so most threats to cancel CC will keep using it anyway so it’s win-win for Adobe.
Reading about Adobe’s experiences with new users, In hindsight, you have to wonder how anybody managed to import shots with the old-school import dialog at all! After all, every LR user was “new” once and had to face the impossible challenge.
It’s inconceivable that Adobe would make such a radical change and not provide a “Classic” or “Advanced” mode for all of us who were happy with the way it was. Congratulations Adobe, you’ve broken the way we work. Adobe, are you just trying to frustrate your loyal users in an attempt to gain new users?! Why should I have to waste my time fighting with what used to work?! It’s a well known fact that a company’s “best customers are the ones they already have.” Great job LR marketing, you’ve just lost our trust….
Adobe…I am waiting for instructions to delete Lightroom 6.2 and go back to previous Lightroom 6.1.
Simple. Delete the update and download and install the previous version. That’s what I did, with no problem—once I found the proper update at.
The remodeled version is 6.2.1. Version 6.2 does not include the updated interface and I found it to be a safe update. Though some are going back to 6.1.1, which is also still available. I found 6.1.1 to have some stability issues that don’t seem to plague 6.2 as much. YMMV.
In your rush to appeal to new users, and an apparent rush to get the product out for marketing, you have betrayed the trust of long time professionals and devoted amateurs. Did you think that perhaps our workflow is important? If you must make a mass market version, at least leave the rest of us an option to keep the old features and plugins. Were you intentionally trying to break the On1 Perfect Photo set of plugins?
For those that want to roll back to the previous version, there are clear instructions here:
As a longtime Lightroom and Photoshop user, I became complacent about their competitor’s products. A situation I’ve spent the last few days rectifying. There are many, and some better than Adobe. Now, like most PS/LR users I have a lot of time and money invested in plugins, presets, etc. for PS/LR. That will be the big dissuader that keeps many, if not most, users from switching. But, I believe this is just the beginning. I believe Adobe, in pursuit of the almighty $, is not going to stop raping Lightroom until it becomes the Adobe version of iPhoto or Apple’s new Photos. I believe this because if a person is too ignorant to even figure out how to import photos into LR, how is that person going to know how to use the software’s other capabilities? Answer: those capabilities will be downgraded just like the Import module. And, Adobe knows that while many users may gripe and grumble and/or find workarounds to the import process, few will actually cancel their subscriptions. And that’s how big companies like Adobe keep control over the majority of their current user base while screwing them to entice new users. The only way Adobe might listen to its current users is if current users start affecting its bottom line by cancelling their subscriptions and stop using their products. It’s hard to humble a 500 pound gorilla, but not impossible.
I will cancel my subscription for sure if there is no corrections to this functionalities. There are other options available. I think Adobe should underestimate their end users period!
I will cancel my subscription for sure if there is no corrections to this functionalities. There are other options available. I think Adobe should NOT underestimate their end users – period!
If a simply import routine was needed for new/novice/basic users just add a “wizard” option for them and leave the the 6.1 version for existing/advanced users. SIMPLE
From a software engineering perspective, it’s not so simple: Having multiple choices for the user interface makes maintaining code quality and testing releases much more difficult (i.e. expensive), or Adobe would of course have “just” left the old interface as an option.
I’m sure the thought crossed their minds that some old-school users could be less than happy by cutting features – but the decision was made anyway. This tells us, that from a business standpoint gaining new users and cutting development costs beats getting some bad replies to blog posts.
If including the simplified interface as an option in Lightroom is too complex or problematic, then they should have created a lite version, as they did with Photoshop and Premier. Instead they chose to dumb-down the program. Whoever is making decisions like this at Adobe needs to find someplace else to work, where stupidity is the norm. Until now the Lightroom team at Adobe was among their best. I suspect it was not the frontline engineers who made the design choices here. I notice none of them have responded to this thread, nor have any of the usual power users who routinely offer support on these forums. I suspect they’re all waiting for the weight of our protests to reach critical mass in order to convince the powers that be how wrong they were on this one.
Apropos of which, Apple picked exactly the wrong time to abandon Aperture. No doubt they did not expect Adobe to drive Lightroom into a ditch. Frankly, neither did I.
Creative Cloud, as an initial concept, was wonderful and very helpful for the professional photographer. But, the mess it has become has become a complete hindrance to my business. I have four projects started in Lightroom and I’m unable to complete them (my apologies to my clients) until Lightroom gets fixed. Was this what Adobe had in mind when they created CC? Time and money, kids…and I’m panicking for my clients as I type this.
Is it possible to restore the following Import dialog settings (as an option in Preferences or Catalog settings?
* Move is gone. You can only Add the photos at their existing location or Copy the photos to a new location.
*.
I use some of these from time to time, and I use filename rename preview *every* import!
I would agree that the loss of these “pro” features would be detrimental to a significant portion of the Lightroom user community — and a lot of us go back to the pre-release public beta. Especially, now that Aperture is gone (which I owned but only dabbled with), maintaining these pro features in Lightroom is critically important.
Those of us who use these pro features can probably wait and not upgrade, until they return, even until Lightroom 7. Well, at least I could. Lightroom 6.1 has been fine for me.
If there would be a multiple dot-release delay before these pro features can be restored, could there be a way in Creative Cloud to update Photoshop but not Lightroom, so we don’t accidentally update?
Thanks for your consideration. Lightroom has been an amazing product — let’s keep it that way.
To make it very clearly, I’m a photographer, this is my job! I’m working with lr since verson 1.1. I thought lr is an professional, effective, high quality software! But now your begging for amateurs!
Of course adobe has to earn money.
But what about this: You can make a Import-GUI with a switch. First one: Simple – Second one: Advanced
In this case everybody, depending on his knowledge can use his favourite import-dialog.
Best greetings from Germany
The new, dumbed-down version of Import is impossible to use. My whole filing system is based on the previous LR Import. I am going to have to revert to the older version. This is a disaster, Adobe. Please listen to your professional users.
Nightmare, just made importing more difficult plus more mouse clicks to do so.
Some of us like to put images in specific folders and not just all in “Pictures”
Adobe, if it ain’t broke don’t fix it!!!!!
Like many people on here, I would like to see the next update (ASAP please) reintroduce the ‘eject after import’ option. This is (was) very important to me for speeding workflow when importing photos that need to be quickly checked and exported ready to send off to various clients.
Also, I don’t seem to be able to see which file type or original file name I am importing in the grid thumbnail view as before. Personally, I have no idea why the import function needed changing, as I thought it was perfectly suitable the way it was. There is a saying I think most people will be thinking of whilst they get frustrated with the update – If it ain’t broke, don’t fix it!
I have to agree that the new Import dialog is a big step backwards for anyone who’s used the product before. I also don’t see why the old Import dialog is not an option.
Frankly, I just want to be able to put the directory where the images are and tell Lightroom to import it. I’m not interested in previewing the images before I’ve imported them; I’ve never used that in the roughly seven years that I’ve used Lightroom. I want to manage where my images are stored (although Lightroom does a perfectly fine job of doing this).
I’m also going to note that changing the Import dialog changes workflow for many of your users–including many people who use Adobe products to earn their living. It takes time to adjust, which can cost them money. And it’s annoying as hell for the rest of us.
You desperately need *both* “Simple” and “Expert” Import dialogs.
I just installed the update. Please note that Lightroom will still only run ONCE. If I close the program I can NOT restart it unless I log out of my account and then log back in. I am running Windows 10.
That’s just one of many bugs. Downgrade as soon as possible. Don’t wait for 6.2.1 to work because it won’t. It’s a train wreck. I haven’t seen a single post here by anyone for whom the updated version actually runs properly.
Another voice to bring back the legacy import GUI and functions. Oh, and, lose the arrogance, please.
Ok, just ran up LR6.2.1 and it seems fine.
Performance across my modest 30,000 images is ok. Editing ok.
Import box…. might take some getting used to but I get it (I dont *get* how it’s any easier – It seems to be the same function but more clicks to set it up how you like it the first time).
So, fine.
I managed to miss the ‘excitement’ around 6.2.0!
A short while ago I posted the information below. The problem now seems to have corrected itself, much to my delight (and embarrassment). I logged off, logged on, ran Lightroom, and let the catalog backup run this time (I didn’t previously to save time since I was just testing). Perhaps that is what made the difference. (I normally run automatic backup daily.) Anyway, fingers crossed, all is well now and program startup seems to be much faster. My previous comment:
“I just installed the update. Please note that Lightroom will still only run ONCE. If I close the program I can NOT restart it unless I log out of my account and then log back in. I am running Windows 10.”
If this is a solution to the stability problems with 6.2.1, it’s the first time a Lightroom update has required such an effort. Most of us gave up before reaching that point. And, given how buggy the update seems, I would hesitate to let it update my catalogue for fear I could not revert afterwards. In any case, the new Import dialogue and discarded features are a deal breaker for many, even if the app could be persuaded to run without freezing or crashing.
Since updating lightroom I can not export any of my work! This is ridiculous!!
Sabrina,
Can you post more information in our support forum, including your OS Version, Lightroom Version (Check Help>System Info so we can make sure you are on .2.1) and any error messages you are receiving or screen captures. Please post here:
While I might get used to the new Import dialog, I cannot get used to the instability. 6.2.1 is the worst version of Lightroom I’ve seen, and I’ve used every one, including the original beta. I, too, reverted to 6.2. Clearly, not only did Adobe consult too limited a sample of users (new users only—what’s up with that?) but they didn’t test it thoroughly. I’ve quibbled with the development team before, but this is more than a quibble. This is a deal breaker. Turning off the Add Photos Screen doesn’t solve the problem. And, since it is a temporary screen, I don’t see how it could.
That said, I’d rather not get used to the new Import dialog. All those big checkmarks? Please. I’m visually impaired and I’ve never had a problem seeing or understanding the checkmarks in the upper-left corner of the thumbnails. I agree with the person who said the new checkmarks obscure the thumbnails and make them harder to use. They look childish and unprofessional besides. Clearly the people responsible for this update didn’t think it through. They could have added the simplicity new users want without eliminating the complexity veteran users need. As obvious as that solution should be, it clearly did not occur to them. Or perhaps they were just too lazy to do it. Either way they failed big time.
They say they welcome feedback. We’ll see about that. How long will it take them to fix this monstrosity? Will they even do so? I’m not holding my breath. Yes, Lightroom 6.1.1 has some stability issues, but rather than fix those, Adobe decided to add even more instability and a batch of half-baked interface changes as well. They should focus on getting Lightroom 6 bugs fixed. Once that’s done they can look at changing the UI. In any case, dramatic interface changes belong in an upgrade, not in a dot update. Currently they are trying to do too much and the result is shameful. Whoever planned this should be given his walking papers. He’s clearly followed the Peter Principle to the level of his incompetence.
I can’t believe this is even an update.
This is really the stupidest thing could happen to LR.
Importing picture is an active part of our job as photographers, and a very important one in term of productivity and being efficient.
This new import dialog looks dumb, doesn’t follow even any of the simplest UI composition rules and doesn’t add anything (in fact remove lots).
People who couldn’t use the import dialog before should just use Microsoft Paint.
I paid for WORKING with this SW, not for PLAYING with it.
I totally agree with you
I’ve downgraded again. I thought the creative suite is a suite for professionals. First I got face recognition, which made my CPU and harddrives freak out. Luckily it can be disabled. Now a toyish import dialog.
All I want is a rock solid, stable and fast LR. Stop adding unnecessary crap. And just roll back from the last update and start over. If you are targeting at users that have trouble with lightroom as it is – please make two lightroom versions. One for pro and one for other people. Also use two different audiences when asking for feature requests.
I just hope Adobe has the guts to roll this back. My fear is, that it will be tweaked a little and agued a bit and that’s it.
One thing is for sure – as a IT professional and photography enthusiastic I am NOT going to update my LR to this new version before there is a possibility for the end user to control the Import process fully and completely. I think now LR creators need to re-think whether they want to get to the commercial markets with “easy to use” functionality OR keep their more advance users and professional. Please note that in in this “easy to use – commercial side” there a lot of free tools available and competition is much harder than in professional side. As an IT professional I know that it is only about the will and money to create a satisfactory functionalities for both of the user groups. You can enable the old functionality to more advanced users and have this new to those who touch base the LR for the first time with very little money involved. I am really disappointed with the latest release.
In this instance It appears that Adobe chose too many inappropriate people for their focus group.
As many folk have already requested, please give us back the old Import dialog with auto eject once memory cards have been read! Your new ‘user friendly’ interface could have been made the default for a scratch installation, with the old import interface retained for folk updating from an earlier version of LR.
This new import window make me think I’m using iphoto or some amateur software. I’m using lightroom because it is supposed to be a professionnal sotware that permits you to configurate and import the software the way you want. Learn the software or use photoshop Elements dedicated to amateurs.
My apologies if I missed this in the discussion and if it has already been answered.
My workflow depends on the file names being shown in the import dialogue along with the thumbnails. I can not find an option that allows me to automatically view file names with the thumbnails. I see them when I hover over the photo, but that is not acceptable workflow. I cannot hover over each photo to identify it by name. It increases my time spent at least tenfold.
I have tried disabling the ‘Add Photos’ screen in general preferences but that does not resolve the issue.
This has me dead in the water. I’m a CC user so going back to an older version isn’t an option.
Thanks for any help that you can provide!
Photoshop elements has it’s devotees. Why not Lightroom Elements for casual users?
I just encountered the new Import dialogue and I hate it. I’m with all of the other professionals. 7 of my photos are “corrupt” and I tried re-importing them and cannot find where to tell LR to reimport them because it thinks they are duplicates. How do I tell LR they are not duplicates. I don’t want to lose what work I’ve done on them.. Aaargh! Bring back the old import, please and tell me how import duplicates. And your “captcha” wont work for me. WTH is -two – 1 ???
One more thing, once I renamed my photos today, they became “corrupt or unsupported.” Why? !!
HELP! When I rename my photos, LR is telling me that the file is unavailable or corrupt and I cannot make changes on them. This is serious!
Commiserations to the Adobe employees who may not have slept much recently following this mess.
Perhaps the next time the management, or marketing people demand that you meet some arbitrary deadline, you will have the courage to put a different perspective to them to help with their decision making.
Fortunately, I haven’t updated yet. All I see is a a large number of negative responses to the new import method, and not a single positive response, which makes me think that Adobe got this completely wrong. If this is an attempt by Adobe to dumb down the program for casual users at the expense of advanced users, I do not welcome this. Of course it is nice to have things be easier and more intuitive, but not at the expense of functionality.
Don’t do it. Seriously. I’ve lost so much productivity time since I did.
Three words… RUN.AWAY.NOW
Epic fail, and, when Adobe haughtily sniffs “Keeping the existing Import experience isn’t an option,” one cannot help but wonder when, after again consulting the easily confused and again ignoring their professional/serious user base, “Keeping the existing Develop experience isn’t an option” is coming.
The folks at Capture One Pro have got to be loving this…
Ever since this update to 6.2 – Lightroom won’t let me do anything except wait for it to finish importing. The “dumbing down” is more confusing than the previous version. But my major complaint is that the update made Lightroom 6 WAY WAY WAY slower. NOT better. Super frustrated and wish I had stuck with 5.
Seeing a lot of complaint on newly update of LR. But none of them same as what I encounted after update 2 days before. I could not see the new photos with updated LR correctly. Photos are initially able to see in lower resolution (in Library or Develop mode) but turns to black once fully loaded. That problem does not affect to old photos in LR, but only to new one. Another issue with my LR is IMPORT button doesn’t work when I press it. I only can use Folder +/- to add and remove photos from folders. Not sure if someone here can give me tips to fix it. Or any way I can revert my LR to perivous version.
Please see this document regarding the Black Thumbnail issue:
I’m so frustrated Adobe still did not fix this nasty bug [] which really kills the joy of using PS and LR together for me!
You don’t even get the feeling of being noticed in the “support” forum…
I mean… this bug was introduced with the JUNE updates! How long should paying customers wait for an official response (except “try uninstall and reinstall”)?
Nico, please see Jeff T’s comments on this thread:
The new import caused me much more grief than the old one.
What could be simpler than chose source, then destination and check “Eject Card after import”?
It took me a while to figure out that I need to go into settings to find where to copy images to, I still haven’t found out how to eject the card after import. My PC tells me the card is still in use until I quit LR. I don’t want to close LR every time I need to import from another card.
Sorry Adobe your developers should have concentrated on fixing some of the issues we’ve raised over the years. I regret signing up to CC, now I’m stuck with you for 10 more months(:-(
I understand the desire of Adobe to make the program more acceptable for public. This is vein of recent update of Lightroom Mobile that allows to use a Camera Roll and be independent from Desktop version. Essentially Adobe is following Apple’s route attracting new customers and paying less attention to the group of professionals/advanced users. Now I start really worrying about the future of Lightroom. I switched from Aperture to LR about a year ago and now I see the same thing happens with LR…..
Adobe – please show us respect and return back all the Import features. I think it is not hard to make two versions for simple and advanced import that will work for everyone.
One BIG disaster for Adobe. Words to management “never take your clients for granted remember Kodak, Nokia, Polariod”.
Sharad – let me comment on each line of the two paragraphs (6 & 7) to illustrate Adobe’s misunderstanding of the LR user (not the ones Adobe supposedly visited in their testing):
“Customers were universally unable to decipher the Import dialog without getting frustrated.”
Which customers? Universal is a very strong word suggesting it was a failure. So why did it last so long? The old import dialogue had some minor issues, but it worked very well. The initial learning curve was not that extreme.
“Some people pushed forward, bolstered by spending time searching the web for help. ”
And many people then searched the web trying to find out what Adobe had done to the import dialogue!
” They might have been successful in importing files, but they didn’t feel successful.”
How do you gauge success? The image is imported and therefore can be manipulated? The image was not lost? This is a statement with nothing to illustrate its premise.
“Others gave up, deciding that Lightroom might not be the right product for them.”
How many customers did Adobe actually lose? Be specific in the numbers – if its under 10% compared to the 50% your about to lose with this change then it’s not a positive is it?
“The previous Import experience literally made people push back from their computers in frustration.”
Marketing speak. Again I ask how many?
“Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience.”
Why not? Many applications allow different levels of user – basic, intermediate, advanced. Is there something Adobe knows about real LR users that the users don’t? Some are even literate enough to read the preferences dialogues and adjust the settings to suit themselves.
I’m sure others have looked at these two paragraphs and wondered if Adobe actually talk to REAL users rather than focus groups.
The mea culpa from Tom Hogarty suggests REAL users are not happy. See if you can change that.
I really don’t like to say: I don’t like the new way to import photos. A disaster. I liked lightroom as it was very much. It is very confusing. (Its like om on a Windows system) And it even doen’t work well. For instance. Can not import folders. Lightroom does find new files but can not import them. I know its a diffent subject. I use Lightroom a lot. Now I need time and effort to find a solution. rrrrrrrrr.
I’m sorry that you’ve reduced the functionality of the import and move options, these were very important to me. I’m not updating until you’ve fixed them. You’ve let existing users down, shame on you Adobe
Adobe: How do I uninstall 6.2.1 and revert back to 6.1? The new update is horrid. Shame on you for ruining the import process.
I second that. Reversion instructions so we can “upgrade” to the old/better version.
I understand the need to simplify the import experience for new users. However, I can not understand why features were completely removed from this module at the expense of experienced users and loyal customers. I am a power user and rely on being able to see exaclty where my photos are being imported. I do not want to import suspected duplicates, I may not want to import all the images from my card. Sometimes I forget to reformat a card after a shoot, and need to import photos from a certain date only, I can’t do this quickly any more. And don’t get me going about no “move” button or “eject after import”, or the instability. I am reverting back to version 2015.1.1 immediatly. Adobe, I hope you are man enough to realize that you made a major mistake. Apologize to your current users, and fix the problem by reinstating all the features you just blindly removed. I have never complained about a product before, but this has made me so angry. I had 10min yesterday to import some images for a client. I hit import and was completely lost. I looked like an idiot in front of my client. Thanks Adobe!
Re-reading some of the comments here it occurs to me that the NEW “Add Photo” option might have been sufficiently useful for neophyte/amateur/hobbyist users (hard to tell, since it crashed Lightroom and we were advised to turn it off.) if this is the case, then why futz around with the existing import function? I’ve used Lightroom since it started out, didn’t find the existing import function overly difficult and am, like others, dismayed to see useful features eliminated. The prospect of paying monthly fee for a release that is, in essence, a downgrade doesn’t make me feel particularly confident in Adobe’s ability to deliver.
I have spent a considerable amount of time investigating the new import and will not be continuing. Adobe take note that there are an enormous amount of disgruntled user who will treat you with the same disrespect you are treating your customers. The proof will be wether others follow those who will move away. One of the strengths of Lightroom was that the import program suited everybody except those who would not take the trouble to learn it. It was very flexible and cover almost every situation.
On another Lightroom con; I cannot wait for the Class Action of forcing users who do not want to pay your rent from being denied the updates.
I will just revert back to one of the five versions of Photoshop I have and use Bridge. I can still remember the work flow.
The utter stupidity of degrading what was turning out to be a classic leaves me dumbfounded,
The new interface is horrible. You can barely see the images you are trying to import…what’s with the giant check over the image? To me, you are saying that the most important thing is to know the image is checked and not what the image is, information about the image, or how I want to handle the image….definitely showing partiality to beginners and not pros using this as a part of their business. I need the options that you removed to keep my workflow. Removing this is horrible and the lack of communication is even worse. I wanted to stay on my older version but I am forced to upgrade to maintain compatibility with new cameras. You force us to upgrade to gain RAW support for new cameras but introduce major bugs, functionality changes, and remove features with barely any notice. This is not what I expect from professional software. It needs to work and work like it used to….my business depends on it.
While I am relatively knew to Lightroom, I must say that the old Import interface was much better than this new one. I agree that their should be an option to switch back. In fact, I might just switch back to using Aftershot Pro.
I am a brand new user of Lightroom, and I really appreciated the old (pre-update) import interface. The ability to designate the photos’ destination before import is powerful. The need under the new import screen to relegate the photos to a temporary ‘collection’ is inconvenient, as it requires additional steps (if I understand it correctly). I too would like to have the option to use the pre-update interface. Two observations: First, it appears to me that not only is the new import dialogue designed to ‘simplify’ for new users, it is also meant to look pretty and easy to click on an iDevice, and if this is the first of planned similar changes to other parts of the interface, it is regrettable. Second, the explanation for the change is one of the most condescending and deceitful bits of marketing hype I have seen. In summary, my opinion: old import interface good, new import interface bad.
I am a FT Commercial Photographer, LR is as important as my other gear, been using LR since v1. When I saw the new interface I thought I was in the wrong program!.
There is a whole bunch of us working photogs that rely heavily on LR, don’t mess with our workflows unless you really have tested it. I don’t know about this interface, maybe I will get used to it, but I like having my folders laid out before me.
Where did the eject card after import go? Is it really gone? That was a great feature since I ingest multiple cards and have to move quick..
I noticed also that 2 of my camera’s don’t show up in the devices properly (nikon d810 and df), my D4s is fine. I have to “browse computer” to find them.
My old FTP settings don’t work, I had to change a setting I have used for years to sftp, and sometimes it times out.
So covering up the images with GIANT check marks is helpful? How’s that? Obscuring the very thing that I’m trying to work with – are you kidding me? It looks like you hired children to redesign this thing for children. There are no material improvements despite the explanation above – which is so glib it borders on insulting. What there are are feature omissions and a full page display of cards and drives that merits no more space that the former list that was more than sufficient. Argghh….
I am nonplussed.
Hate the new import. Please restore the old one. The new import is horrible!!!
Sharon
Please give the option of using the old import. The new version is terrible! I’ve been using LR since V2. Is there an easy way to revert the update?.
The experience that you wouldn’t even tell us what you were going to do. I can’t fathom that. Is it that you think your customers are dumb and can’t take change? Therefore, you being much smarter, of course your much smarter. So, you will just force your low brow customers to ‘take’ what you give them. Customers be damned, full speed ahead. You’re lucky. I don’t really see that you have any competition. So you are right: “stick it” to the customer. The downside to your megalith mentality is that you are becoming the only one in the business. Government types love to break up companies like that. Is this where you are heading?
I am a longtime user of these products. Fortunately I have not installed the bad LR update yet but I am concerned about this “simplification” of the import process. Are you telling me after getting used to (and loving) importing directly to a named collection, that is going away?! Leaving that option there is confusing? Really? I don’t see it in the attachment above.
And then I read how Adobe is really interested in listening to customer’s input, then in the same breath said they are not putting features back into the import process. This kind of response reminds me of the decision to not update Encore to “creative cloud status” even though many customers at the time gave “feedback” that it was still needed out here in the real world.
I am glad the bugs are being fixed. But please do not take away features we are already using. How about designing a GUI that makes it less confusing? How about big “beginner” and “advanced” buttons to start the process and bring up the different interfaces?
If this is going away I probably just won’t update for months until the “feedback” hopefully gets some features back.
Bill
Can we have the “Move” Import Option back please?
Thanks, Oliver
(hobby photographer)
“Customers were universally unable to decipher the Import dialog without getting frustrated.” Please make sure you don’t let these people loose anywhere near the develop module. “Others gave up, deciding that Lightroom might not be the right product for them” . They’re right, clearly it isn’t! It’s for professionals / enthusiasts, not people unable to comprehend the distinction between adding images to the catalog where they are or moving them to another folder, or for whom ‘eject card on import’ represents an impossible conundrum. Give them a selfie stick for their trouble and send them on their way! Above all, there’s a difference between putting functionality the brain dead find confusing behind an advanced tab, where it won’t trouble them, and actually taking out stuff the initiated, your loyal customers, have made abundantly clear they crucially depend on. Is it so difficult for you to understand this?
“… we’ve always evolved the Lightroom product with feedback from photographers and look forward to continue to evolve the experience going forward with your feedback in mind.” This statement, if sincerely meant, is incompatible with ignoring the pages of feedback from your consumer base now available to you asking you to restore the previous import functionality. There is an unbridgeable gulf between those unable to understand this functionality and those who do. Don’t look to the former to determine the future trajectory of LR.
Lightroom has always been my first choice, because it’s perfect way to adapt the ‘professionlal’ workflow. and now, Adobe just blew it.
The Import is the first step on my work with pictures. And just the key point has become more or less unusable now.
I welcome Adobes effort to meet new usergroups with less requirements to an clear workflow, and maybe also less experience and expectations. There’s nothing wrong with that.
But the way, they did it here, is the way to loose previous customrers.
We’ve heard great feedback on the changes, and we’ve always evolved the Lightroom product with feedback from photographers and look forward to continue to evolve the experience going forward with your feedback in mind.
Please keep the feedback coming!
BUT ADOBE YOU DON’T LISTEN OR RESPOND TO EVERYONES FEEDBACK!!!!!
SHOW US WHERE YOU”RE FINDING THE GREAT FEEDBACK……..
We can’t find any …………………….
When will you respond and answer to your errors ………….
I found no difficulty in using the import dialogue when I first started to use Lightroom. I customized my import processs and saved different processes for two different cameras. Now, all that seems to have gone. This is a major loss of functionality and is very disappointing.
Microsoft made similar mistakes with Windows 8 – thinking of their marketing strategy rather than the satisfaction of existing customers. I will unsubscribe from CC as soon as my subscription period ends
Have to agree with all the comments above. This new import dialog is horrible. I especially liked the option to move my images from their existing location and that’s not even available which causes me more time to have to remember to go back and remove the images I copied. Adobe this needs to be fixed, period. As you can see this is not just a couple people complaining, it’s a lot! At least offer the option for a simple or advanced import dialog, and let us who like having the options choose the advanced.
I agree!
I cannot work as i did for years now anymore. My workflow includes moving of the files during the import. Without the option, i have to find some other way for a nice and lean workflow.
Since Importing of new pictures, is the very first step using tools like lightroom, i really cannot understand, why adobe gives all his loyal users such a bad feeling, each time, the have to work with Lightroom.
I realy hope, they understand very soon, that replacing the import dialog was a big mistake!
I appreciate adobes effort to address less expecriensed users as well – but please not a the cost of letting previous users down.
Just bring back the old dialog. A makeover here and there… why not. there is allways room for improvment. But the new dialog is simply not a alternative for those who used all it’s options and functionalities.
Adobe does not have to put the new dialog in the trash – some users will be happy with it.
But give us the option to choose.
Well, that did nothing as far as unchecking “add photos screen”. My images are still Black in Library and Blue in Develop. Need a fix to this as my import is useless.
hi Barbara, see this document:
Pulled this quote from Sharad’s note at the top:
“The previous Import experience literally made people push back from their computers in frustration. Keeping the existing Import experience isn’t an option, and we needed to evolve the Import experience”
Well, the NEW import interface has me pushing back from my computer in frustration.
Keeping the NEW on is not an option as it is a move backwards not forwards.
Who says you need to evolve the import experience? It clearly is not your established user base. I know I did not as for this.
I have rolled back to 6.1.1 after investing several hours.
Adobe I hope you learn from this mistake….. every day that goes by where you don’t restore LR to the way it was you will be loosing previously loyal users.
How can i go back to 6.1.1?
I have tried to roll back without success…but I will keep trying. I hate the new Import and will gladly give up other updates and go back to 6.1.1 if I can.
Unhappily, I have to join the chorus. The main complaint is loss of functionality. Neither is the new import dialog easier to use. From the design point of view it looks and feels like a incongruous bolt-on to a good piece of professional software. I don’t know whose and how many homes Adobe researchers/designers visited but the comments posted here should give Adobe at least some food for thought. To use your own language, this focus group has “universally” condemned the changes. Please, draw conclusions.
I am very disappointed in the removal of features from import — I am thinking that I may have to stop using Lightroom altogether. The new import dialog is much harder to use than the previous version, and right now I *need* to import “suspected duplicates,” but it won’t let me. The default behavior is not what I need as a working professional, and Lightroom CC 2015 seems (so far) a disaster to me. I am astonished at how many problems I am having with a program that I’ve been using since version one. I will definitely be voicing my opinion to Adobe next week at PhotoPlus Expo in NYC.
I am disappointed with the ‘upgrade’ especially the import dialog. I have moved from Aperture as Apple have abandoned it, do I have to start looking at other alternatives again?
Remember this: Lightroom is a tool that was initially marketed to professionals and beat out Apple’s Aperture software because you cared about Pros! But, now that you want to expand your consumer base you remove pro features because of “frustrated” newbies!?
Bad move. We pay enough in licensing for you to keep a pro mode and a consumer/hobbiest mode. Even a small software vendor like Camerabits with their PhotoMechanic product has preferences for dialogs to make legacy users happy–because they CARE about their established customer base.
Go make Lightroom Elements for the “frustrated” instead of screwing up a tool that pros use on a daily basis!
And, if that is not on your “roadmap”, make pro features an option in your preferences panel if you are so concerned about bringing in more users who are accustomed to dumbed-down iOS style apps. If you want to be instragram, build another app for that crowd.
That new import – awful, just awful.
Am I missing the move function? I upgraded to LR6 to organize previous catalogs and new photos and want to move to a new Drobo drive. I don’t see the move function that was previously shown on the TOP of the import screen! File handling now only has Add or Copy!
I’ve deinstalled the downgrade and upgraded to the previous release…. Enough said.
Not much to add to what has already been said except count me as another voice against the new import. All of us took the time to learn the old system and now depend on it’s features. To me it is obvious that if new user cannot learn it they are using the wrong product. What’s going to happen when they try to use Photoshop which comes with Lightroom CC? At least they will have successfully imported the photos. Good luck from there.
I agree with most of the other comments. I was shocked when first using the new interface. It no longer launches automatically when a card is inserted and the options are hidden by default. When exposed the options are in a tiny typeface as opposed to the giant check marks. The view of file structure has been eliminated. I understand that Lightroom is database-centric but many of us still use the file system for basic organization and backup. The import process now takes longer.
Please revise this interface or offer the old interface as an option.
New interface is terrible and even with the updated fix, my computer keeps crashing. Very frustrated with Adobe right now. The most unprofessional and inept update I’ve ever encountered.
I saw a post up there saying there should be a choice as to which user interface to use – like a BASIC and ADVANCED layout. If Lightroom is going down that lane of trying to be some kind of Lightroom Elements, then consider me gone. I don’t think the old import dialog was too complicated and there are enough even free resources on the web to learn it quickly. And if you don’t want to invest the time to learn such a powerful program that Lightroom at least used to be, maybe it isn’t for you anyway. Maybe Photoshop Elements is good enough then. I still have Lightroom 5 and if this import dialog is not changed, i’ll cancel my subscription and go back to that as long as i am looking into Capture One or Photo Mechanic.
I don’t blame Adobe, it is their right to make a decision which way to go. But with a rection like this from waht i feel is the majority of photographers using Lightroom it makes you wonder whether the decision was the right one. Oh well, we’ll see.
New Import Dialogue = Disaster
this poppy look&feel is something for Apple Users which like those things but not for an average guy who is using his camera as and advanced hobbyist or commercial photographer. All other people are not interested in professional use of LR and for those who are the old dialogue was simply perfect.
As a commercial photog I can’t express how disappointing it is to be presented with this dumbed down version for import as my only option. This is ridiculous. I expect more form Adobe. It won’t take much more to push the pros to CaptureOne.
Did you keep ANY of the features directed at professionals or is this a wholesale shift to the consumer market.
I can’t eject card upon completion.
I can’t tell the RAW from the JPEGs
My Copyright presets aren’t saved.
The new import is the worst new feature I’ve seen in LR ever. No one likes it. It’s even less intuitive than before. And if someone can’t decipher a simple import like the one before then may be should not be using a conputer or do something else other than photography. Camera menu are way more complicated and still people use them. Hope all the negative feedback here and around the net let you see the error you made.
Like may others, even with the most recent update I am still having issues with the new import dialog. I have unchecked the Add Photos Screen option and restarted. Every selection I then make once I am in the import dialog locks up the program completely leaving my unable to import photos.
Windows 10
Core i7
I’m adding my voice to those of others in an effort to get Adobe to change their minds. I have used Lightroom in my professional practice since LR1 and DEPEND on it for rapid, reliable processing of the thousands of images I take in a year. The original import did everything that I needed. The current version doesn’t. If Microsoft can learn from their mistakes and move on from Windows 8 and offer a usable Windows 10, Adobe ought to be able to amend this absurd marketing driven error and at the very least make available a “classic” or “advanced” Import dialog for those thousands of its customers who have come to depend on it.
Kudos to Victoria Bampton for sharing the information that made it possible for me to revert to the earlier version. SHAME on Adobe for letting its customers down so badly.
So you make changes to benefit people who might possibly decide to use Lightroom at the expense of those who already are your customers? Absolutely hate the new Import for Idiots – first time I’ve seen an Adobe update and wanted to back to the old version, but I’d happily bin this one.
I love Lightroom. Photography is my profession and I don’t know how anyone works without it. So to hear this news, about a sloppy release and such a cavalier attitude toward feature removal, is quite upsetting. Clearly, you owe your client base fixes to all of the bugs that were introduced, but you also owe your loyal customer base respect and gratitude. We pay your salary. No one wants to deny you the right to go after less experienced customers, but to remove functionality on which current customers have become reliant is unprofessional and arrogant, to say the least.
Give us an option on the Import dialog, or the preferences, that allows us to make the currently missing functionality available.
I agree with the majority who hate the changes in importing. On top of everything else, I’m talking with an Adobe Customer Service right now and I just discovered that the new version no longer identifies duplicates. I’m not sure why Adobe made these changes but they are a huge step backwards!
AAAAARGH! I’ve just updated! Didn’t want to do it… IT’s AWFUL! I had everything so nicely done with copyright presets and everything. Never thought the import dialogue window would be problem for anyone willing enough to learn about it a little. Now we’ve got this dumbing down process started in the import dialogue, where is it going to appear next? What a dumb move.
Never thought I’d actually post a complaint here! I’m very disappointed. If this is the way Adobe is going to take Lightroom I’ll be heading over to Capture One Pro…
i’m still completely dead in the water with lightroom. it crashes immediately upon startup. every time. it works on my desktop.. very slow.. and still crashes speradically but on my main computer (mac laptop) it wont run at all.
i hope the next update fixes this. I’m sure you (the adobe team) is working hard on fixing this.. but it really needs to be fixed soon.
Please reinstate the file directory, and the do not import suspected duplicates, and please, please, please reinstate the eject after import option.
After downloading 2.1, my imported pictures turn totally dark during the creation of the preview. I can restore them by applying Auto Tone on a 1 by 1 basis, but this is obviously not a workable solution. Has anyone had this problem and found a satisfactory solution?
See the workarounds here:
Thank you
So, I have two macs (iMac and Retina Macbook) both running El Capitan and I foolishly upgraded them to the 2015.2.1 release and I now can no longer import photos in to Lightroom from memory cards (both machines, different cards, different cameras). I can live with the UI change, but i do think it is a massive step back, but this thing is now so buggy it is unusable – did anyone test this?
This really needs to be fixed. And rolling back to the previous import is an acceptable outcome.
google analysis shows, that searching for the term ‘capture one’ has increased significant in the last week.
i realy hope, adobe will bring back the old import dialog asap, before frustrated users – as i am at that very moment – will consider to change.
I think Lightroom is a perfect tool. and i realy like it – or i did until the new import has been introduced.
days since concerned users copmlain – and still no real word from adobe. that is sad.
the analysis from google:
I’ll try to post this again…..As far as a “basic” and “advanced” button, I suggested that ONLY if Adobe is so committed to dumbing the interface down, to at least give advanced users the option to keep what we used to have.
My preference is to just keep it designed for more power users. Last time I checked, Elements was for the more basic crowd. Out of all the people I have helped with Lightroom over the years (and it is many) the import dialogue box NEVER came up. Not once….
Bill
Adding my voice to the choir –
The original import dialog is better in every way than the new ‘improved’ one. Put it back the way it was!!!!!
Unless you are a moron, then the old import dialog box was not that hard to understand. As long as you are able to comprehend language and the words copy, move, add. I mean really. Did you all find the stupidest people on the planet to study and then force the rest of us to accept a dumb down version of the import function. I mean really? What else are you going to dumb down? I am just at a loss of words over the stupid excuse you are giving for the most idiotic plan to do away with the old import and implement the new import. And then you don’t even make a stable update to boot, to make matters worse. I mean really? What were you thinking or maybe that is the problem you were not thinking at all…
I am so sorry for those who can not or do not choose to learn the concept of file organization. Give them a “guided import” box to select to make it a mindless process.
But for the rest of us who have spent the time to learn and know what they are doing, PLEASE GIVE US BACK ASAP OUR OPTIONS TO DETERMINE WHAT WORKS FOR US!!! I DO NOT WANT TO BE RESTRICTED IN HOW I DO MY WORK!
This is plain horrible. I HATE IT! More steps and while it’s loading always seems to select the photos I don’t want to import. I use this on a daily basis for my professional business. PLEASE GIVE YOUR LOYAL CUSTOMERS AN OPTION. Create a Lightroom Elements for the hobbyist and the soccer moms.
I don’t know what homes you went into, but from the length of this post, you made the wrong call.
CHANGE IT
CHANGE IT
CHANGE IT
IT’S HORRIBLE!!!
See here:
“We can now confirm that, in our next dot release, we will restore the previous import experience. We are still working on details and timing.”
Thankyou! I’ve been a user since day one.
That’s great news. So they really are listening. Too bad they didn’t talk to real users before creating this mess in the first place. I suspect it wasn’t the engineers’ fault. This kind of stupidity is a top down sort of thing.
This update would of been fine, had it of worked. Where as now my whole lightroom experience is me sitting in front of my computer for ages waiting for my images to upload. It was way faster before, so my question is how is this an improvement. I don’t want to have to buy a new computer with a ton of RAM just so I can upload my photos!
See this post. You can roll back to the prior 6.1.1 update until things are reverted and corrected:
This version of import has so many bugs, it is unstable and extremely confusing. Revert back to the previous version of import SOON! please?
See this post. You can roll back to the prior 6.1.1 update until things are reverted and corrected:
The new import dialog is a big step backward for experienced users.
The new design might be friendlier for first-timers, but I’m not a first-timer, and I need Lightroom to be efficient and productive for me as well. Please provide a “pro” mode.
See this post. You can roll back to the prior 6.1.1 update until things are reverted and corrected:
Count me as another longtime user of Lightroom who finds the new import window/dialog a huge step backward. I always used ‘eject after import’ and formatted in the camera. Not all cameras set up cards formatted in them the same way, and formatting in camera after making sure that the backup was correct before formatting gave me an extra bit of comfort. Ejecting the card automatically after import is just so much more convenient than going to the finder (MacOS) and ejecting from there after every card. Also options like ‘move’ are definitely useful at times.
On the one hand every new release of an Adobe product includes new features – some great, some not useful to me, but taking away features I’ve used for years is much more aggravating than having a new feature I don’t use.
Please fix this import window, and at least include the features you had previously. It’s fine to include or have the window come up the first time in a ‘simple minded’ mode for newbies, but I’ve been using LR since before the official release and PS before that since version 1 and I’m not a newbie, and depend on tools to keep functioning properly.
See this post. You can roll back to the prior 6.1.1 update until things are reverted and corrected:
How the heck do i get the update for the stand alone everything I’ve downloaded has failed, says its not applicable, only for cc, really aggroicavingu. I feel like I’m on a merry go round
Are you following the instructions here:
You need to install the base installer: The base installer is 727 MB Mac or 744 MB. Install that first, then install the smaller patch files from the same page.
I’ve just got a subscription license to Capture One Pro. I’ve been trialling it because I don’t like the whole Adobe setup and the junk it keeps sending (CC stuff I’m never going to need or want). I have a standalone version of LR (and PS) and for the time being I’m sticking with it until I get Capture 1 up and running the way I like it.
My best stuff is going to a new Catalogue in Capture 1 and from now on, this will get built on.
This latest change to the import dialogue box in LR has pushed me over the edge. I had quite a number of import presets set up specifically for different kinds of shoots, to save time, and now things are a mess.
I’m looking at heading away from Adobe products all together and am finding some interesting programs out there, and Affinity Photo is looking pretty darn good as a substitute for Photoshop.
When is this going to be fixed, We are still paying for a Subscription aren’t we, I’d hate to get to the point where another Application Has to be sought out, though after install and uninstall and laptop Refresh to rid myself of the mess I was suddenly in, maybe the time is now.
I wish I wouldn’t have updated. I was hoping to find a preference to switch back to the older importer
Roll back instructions:
How do I filter out video files now? In the old import you could press ALT and the button would change, allowing you to deselect all video files. I don’t see that anymore. A sticky filter checkbox called “Exclude Videos” would be even better!
Please revert. The new import dialogue is not easier, it’s way more confusing, it was perfect before. I’m so disappointed. It’s like I had a friend who’s now a drug addict. Lightroom was that friend, now my friend is all messed up.
$%$#%^
Each time I try to import is a slow, painful process that causes me to curse Adobe.
Really, you can’t issue a quick fix for import.
You hate professional photographers and want us all to die, don’t you? | http://blogs.adobe.com/lightroomjournal/2015/10/update-on-lightroom-2015-2-lightroom-6-2-release.html | CC-MAIN-2016-50 | refinedweb | 40,525 | 72.16 |
Hi,
I want to know how can I replicate this timeline :
I want create a personnal timeline but I don't where I can't start to search in all the "Editor" classes :/
If someone know where I can start to search this ?
And is it possible to change progress bar color without using gui.background cause the result is not really nice :/
Answer by Bunny83
·
Dec 08, 2012 at 03:46 PM
I'm not sure what you actually mean. For what purpose do you want this timeline? Creating a robust GUI is not easy. However almost the whole UnityEditor is made with what you find in GUI / GUILayout and EditorGUI / EditorGUILayout. Such a timeline editor is quite complex especially when it comes to user interactions. I've made a demo some time ago to visualize how FixedUpdate works. This is completely done in OnGUI and even without the editor stuff (since that's not available at runtime). It's even made in the indy-version of Unity. I used my own bezier calculation (as far as i remember that was before Handles.DrawBezier exists).
As I said, i'm not sure what you expect as answer. The timeline editor in your screenshot is quite complex. It's like you ask how to build a car from scratch. You should start by defining what's the purpose of your timeline. If it should be an editor for something you should consider how and where you store the data you want to edit.
I could write another 3 pages of general stuff you should consider when you plan such a tool.
Can you be a bit more specific?
edit
Since UnityAnswers does no longer display markdown propertly, I've mirrored my article on Github which displays them properly. IMGUI crash course
editSo another GUI crash course ;)Unity's GUI system is quite simple but very powerful. The main parts are:
The OnGUI callback. This callback is used to handle everything that has to do with GUI.
The Event class which is tightly connected to OnGUI.
The GUI controls defined in GUI, GUILayout and additional controls which are only available in the editor in EditorGUI and EditorGUILayout.
The GUIStyle class which defines how a single control looks like. It's actually responsible for any GUI drawing.
The GUISkin class which is basically just a collection of predefined default styles for all built in controls and has an array for unlimited custom styles at the end.
The utility classes GUIUtility and in the editor the EditorGUIUtility. Not to forget the tiny but important GUILayoutUtility class when it comes to using GUILayout classes.
OnGUI is a callback that is called automatically by the engine for several purposes. It's usually called at least two times per frame but might be called several times a frame when other events happens.
OnGUI is, in my opinion, a bad name. Of course it's main purpose is to "do GUI stuff", but it's actually an event processor callback. I will explain that in the next section.
The event class holds information about the event that's currently processed in OnGUI. It's only static member current. This holds an instance of the Event class and is only valid in OnGUI.
The type property holds the current EventType that is processed.
Here's a quick overview of the different events:
Mouse events like MouseDown, MouseUp, MouseMove(editor only), MouseDrag, ScrollWheel. I should add that Unity will emulate those events on mobile touch devices. It calculates the mouseposition by taking the arithmetic mean of all touches.
Keyboard events like KeyDown and KeyUp. Note: unlike Input.GetKeyDown / Up those events map the system's OS keyboard events. So when you hold down a key, the keydown event is repeated by the systems repeat rate. This is of course important for text editor GUIs.
The Layout event. This is a special event that is always executed before all other eventa and is used to determine the size and position for automatic layouted controls. Note: This event can be disabled with useGUILayout but keep in mind that all GUILayout stuff won't work in this case.
The Repaint event. This event will actually draw the GUI elements.
The Used event type. Any control that processes an event and don't want others to get this event can use the Use function to "eat" the event. When Use is called the event type will be set to Used and every control should just ignore this event.
Beside the type of event, it holds additional information for the event.
mousePosition holds the mouse position in GUI coordinates. GUI coordinates are different from screen coordinates. The GUI has it's origin at the top left corner, screen coordinates has it's origin at the bottom left corner. The GUIUtility class has functions to convert those coordinates.
button. Only valid for mouse events and contains the mouse button index (0 - left button, 1 - right button, 2 - middle button)
modifiers hold information about Shift, Alt, Ctrl keys
keyCode. Only valid for keyboard events. Holds the KeyCode of the key that has been pressed / released.
Some additional things like shortcuts for modifier keys.
As already mentioned this class is responsible for rendering a control to the screen. A GUI control function will call one of the Draw functions when the repaint event is "detected". An GUIStyle consists of different GUIStyleStates where only one is "active" at a time. Which state is used is determined by what Draw function is called, which parameters are passed and if the control has currently the keyboard focus or not.
When a single GUIStyle is drawn it can produce 0 to 3 draw calls. That's why very complicated GUIs are considered bad for mobile development, however we used the GUI system a lot on Android and iOS and hadn't much problems on more or less modern devices.
The things a GUIStyle might draw are:
The background image from the GUIStyleState. This is usually used to define how the button / textfield / ... generally looks like. If a background image is set it's always drawn first.
An content image defined in the GUIContent class that is passed to Dram.
The content's Text also defined in the GUIContent.
The ImagePosition in the GUIStyle defines where the image is displayed in relation to the text or to only draw the image and ignore the text or the other way round.
A GUIStyle has 8 GUIStyleStates where each state allows you to specify a background image as well as a text color. Note: A state is only used when it has a Background image. So unfortunately it's not possible to just setup text colors without an background image.
The different states are:
normal
hover
active
focused
onNormal
onHover
onSctive
onFocused
normal is the stylestate that is used in most cases. A label for example will only use this state.hover is used by buttons, toggles and most other interactive elements when you hover over the element.active is used for interactive elements while you click-and-hold on the element. It's the button down state.focused is used by TextFields and TextAreas when the editor is active and you can edit the text.
All the onXXX states have the same function as the other 4 above, but are used for elements that have an "on" state like a Toggle. So if the toggle is unchecked and you click on it you will see the active state. When the toggle is already checked you will see the onActive state.
As mentioned above states without a background image are ignored. So if your button style has a "normal" and "active" state with a texture but no hover state, Unity will use the normal state when you hover over your button. If you want to just change the text color when you hover you have to use the same background image for "hover" as you used for "normal" otherwise the hover state will be ignored.
As last note: Unity has implemented an implicit casting operator (sounds complicated, but it isn't :D) that will automatically convert a string to a GUIStyle by using the GetStyle function of the current GUISkin.
The GUISkin is, like mentioned above, just a collection of GUIStyles. Unlike GUIStyles a GUISkin can easily be stored as Asset in your project. You can create one in the Assets/Create menu (same as context menu in the project window).
To use a GUISkin it just has to be assigned to GUI.skin before you draw a control. The usual way is to place the assignment at the top of OnGUI. It has to be assigned everytime OnGUI is called. The assignment is only valid for the current execution of OnGUI. If you want to use the skin in other scripts as well you have to place the assignment in those as well.
Most controls have optional parameters to specify a GUIStyle which should be used to draw the control. At this place you can simply use a string (thanks to the implicit cast) with the name of the style you want to use. If no style is passed each builtin control has it's own default style.
The above mentioned classes define the basis of the GUI system. They can be used to create custom controls or can be directly used in some way.
Unity however provides premade control functions which simplifies the usage a lot. For example the Button function. It uses the default style "button" to draw itself to the screen. This function also processes MouseDown and MouseUp events. It uses the controls Rect to determine if the mouse position is within it's Rect and make itself the hotControl. The function returns a boolean value which will be always false except in the MouseUp event when it's the hotcontrol and released inside it's Rect.
That's how the click event is passed back to the caller.
Some controls, like scrollbars and sliders use more than one GUIStyle. They usually have one main style and additional "child styles" which are determined by adding something to the name of the main style. The horizontalScrollbar literally does this internally:
GUI.skin.GetStyle(style.name + "thumb")
GUI.skin.GetStyle(style.name + "leftbutton")
GUI.skin.GetStyle(style.name + "rightbutton")
to get the other styles. this is a suboptimal way since if you don't have the source code of the scrollbar function (or a reflector) you don't know that.
Some hate GUILayout some like it. Personally i really like it even when it's sometimes a bit tricky it's much easier in the long run.
Basically GUILayout is just an extension of the GUI controls. Most GUILayout functions just call the equivalent GUI function but adds the layouting around it. The "normal" GUI functions completely ignores the Layout event. The GUILayout functions use an internal system that builds up layout groups which collect all controls in a group during the Layout event and before the Repaint event is invoked Unity distributes the available space according to how much space each single control has requested.
Here are the basic things about GUILayout:
Basically all controls that exists in GUI does also exist in GUILayout, but they lack of an position parameter where you usually specify it's position and size.
All the built-in control functions inside GUILayout simply uses one of the many overloads of GUILayoutUtility.GetRect to reserve a Rect for the control. The layout controls just get a rect from the layout system and in turn call the GUI.XXX equivalent with that rect.
Instead of a position they have an additional parameter array at the end which allows you to add no, one or more "GUILayoutOptions". Those option "objects" can't be directly created. Unity has implemented functions that initializes such an instance and returns it. Those "Options" are used to override certains GUIStyle settings like stretching, fixedsize, min and max size.
Instead of the GUI Groups there are Areas. This is the only thing where you have to specify a Rect. Areas can't be cascaded, so the Rect is always relative to the screen. While you are inside an area the whole layouting will be restricted to this screen area.
The most important two function pairs are Begin / EndHorizontal and Begin / EndVertical. Those can be cascaded. So the actual layout will be defined with stacking these groups together.
The next two helpers are Space and FlexibleSpace. Space acts like a control without drawing anything. It just reserves a fix amount of pixels in the current group. FlexibleSpace eats up all left over space. Generally there are two types of controls, "fixedsized" and "stretching" controls. Fixedsized doesn't mean they aren't able to change size. They just take as much space they need. All stretching controls (like FlexibleSpace) will share the left over space and distribute it according to their content sizes.
Some notes:The horizontal and vertical layout groups usually don't have a GUIStyle and are pure grouping elements, however you can simply specify a style in the parameters to draw it as box / button / customstyle.
You can change the appearance of an element by just specify a different style. This will display a toggle which looks like a normal button:
togglestate = GUILayout.Toggle(togglestate, "Toggle Text", "button");
update(2016.02.18)
EditorGUI and EditorGUILayout are simply "extensions" of the GUI and GUILayout classes which are only available inside editor script as those are located in the "UnityEditor.dll". Those two classes aren't ment as a replacement of GUI and GUILayout. They simply provide additional controls which are useful in editor script like custom inspectors or EditorWindows. In editor script the normal GUI and GUILayout controls work just fine.
Before someone asks, no, you can't use any controls from EditorGUI or EditorGUILayout at runtime as they don't exist in the engine. They belong to the editor.
Since the release of the new UGUI system the Event class has now two additional static methods:
Event.GetEventCount
Event.PopEvent
Those are not really related to the old GUI system but are used by some of the new GUI behaviour scripts to process input events. Those methods allow you to process all events that are waiting in the event queue for the current frame. It will return the same events as those send to OnGUI except it only returns input events. So no layout or repaint events are generated.
Though you have to be careful when using those yourself. Once you "popped" an event from the queue, it's gone. Each event exists only once in the queue. So if two scripts try to read events that way it won't work since the first script will remove the event from the queue.
update(2016.11.28)
Even though they are not required for every GUI control, most of them internally allocate a so called "control ID". This ID is ment to identify a certain control across multiple calls of OnGUI / OnInspectorGUI. A control can allocate itself one or multiple control IDs by using the function GUIUtility.GetControlID. That method takes some parameters which should help so each control gets always the same ID. For this purpose one can pass an arbitrary "hash" value (and int value) that should represent your control's "type". Usually most controls use a cached hashcode based on some string constant:
static int m_MyControlHash = "MyControlTypeNameHere".GetHashCode();
Using this method makes it unlikely to accidentally pick the same int as another control type. In the past GUI.Button used this hash stored in the internal static "buttonHash" variable:
GUI.buttonHash = "Button".GetHashCode();
The actual purpose of those IDs is to track the state for a control if it needs it.
Note: while it's possible to call some controls conditionally, it's very important to not change the count and order of controls between the Layout event and the following event. As mentioned above every event that is processed by OnGUI is always paired with a Layout event that always comes before the actual event. If you change something in between it will mess up the layouting system and could "corrupt" the controlID stack. Keep in mind the control IDs are generated every OnGUI call. So each time OnGUI is called Unity starts with an empty stack It tries to match the generated IDs with the IDs from the old stack based on the different "hints" that has been passed.
GUIUtility.hotControl as well as GUIUtility.keyboardControl can mark a special state for a control. Both are public static int fields which any control might read or write to. Both are ment to hold the control ID of a control which is currently "hot" or currently has the keyboard focus. hotControl is used by most clickable controls like Button / Toggle. The process is usually the following:
When a MouseDown event is received, and hotControl is currently "0" a control might want to check if the mouse is over it's Rect / clickable area and if that's the case it will set the hotControl to it's control ID. That prevents other control from reacting to certain events since they also check their ID against the hotControl variable.
When later a MouseUp event is received a control will check if itself is currently the hot control. In that case it will reset hotControl back to "0". This is important as controls are only "allowed" to put themselfs up as hotControl when it's currently 0. A button usually repeats the area check and if both is true, so the button is hot and the mouse was still over the button, the control will return "true" which will cause the if block, in which the button is used, to execute.
A similar process is used for keyboardControl. Though it's usually not reset on MouseUp but on MouseDown when the mouse is no longer inside the controls area.
Event.GetTypeForControl basically does the same as the Event.type property, but applies some filtering based on what event actualy happened and based on the state of hotControl and keyboardControl. If no control is hot it basically returns the current event unfiltered. This gives each control the chance to make them hot in the first place. Once a hotControl is set, "GetTypeForControl" will only return the event when the passed control id is currently hot or has the keyboard focus. hotControl mainly filters mouse events while keyboardControl filters key events. Well, that's kinda obvious, right ^^.
So what does it do. This method basicalls is capable of creating an arbitrary class instance for your and link that object to the given control id. The class instance will persist. Note that the class must be a normal class, so no MonoBehaviour or ScriptableObject derived class. It also need to have a parameterless constructor so GetStateObject can actually create an instance. As you might remember as long as you don't declare any parameterized constructor every class automatically has a parameter-less constructor by default.
Those "state classes" are ment to hold custom state information per control instance that need to be carried over to the next OnGUI calls. On example i remember was the GUI.DragWindow control. Yes, it's also a control and allocates a control ID even though it's not a "visual" control. In the past DragWindow used a small internal class (GUI.DragWindowState) to hold the initial window rect and an offset Vector2 so the drag movement can be calculated correctly.
The TextField also uses an instance of the TextEditor class which is a bit more then only a state class. The TextEditor class actually implements the whole editing functionality that you know from any inputfield. So it handles keypresses, moves the cursor with the arrow keys, handles the text selection, ...
When it comes to editor programming, the SceneView is one of the most powerful one but can also be a bit tricky to handle it right. Generally there are two ways how to draw or handle GUI events in the SceneView:
An active CustomEditor (custom inspector) can implement a method called OnSceneGUI
Any other editor class (like EditorWindows or classes marked with InitializeOnLoad) can subscribe a method to the static SceneView.onSceneGUIDelegate event.
SceneView.onSceneGUIDelegate
In case it wasn't clear yet, every actual window of the Unity editor has it's own graphics context and everything is driven by the IMGUI system. Only a few things in the Unity main editor window are implemented in native code (such as the main menu).
So once you have an actual callback of the SceneView you can do whatever you want. Unlike normal EditorWindows (which includes the inspector, hierarchy, project panel) the SceneView usually works with a 3d projection and uses a camera to draw most things. Due to this 2d / 3d hybrid state things work a bit different in the sceneview as opposed to other EditorWindows.
Usually you deal with 3d coordinates inside the SceneView therefore for most things all the GUI controls are pretty useless. That's why there is the Handles class. SceneView and the Handles class belong to each other. It provides some 3d controls like the PositionHandle, FreeMoveHandle, ScaleSlider and RadiusHandle just to name a few.
Even the sceneview is mainly a 3d context you can still use plain 2d GUI inside the sceneview, but you have to wrap 2d gui stuff between Handles.BeginGUI() and Handles.EndGUI(). This allows you to directly display and GUI controls inside the sceneview. A quite important method is located in the HandleUtility class and is called WorldToGUIPoint. It does all the nasty conversions at once (3d->screenspace->guispace->current cliparea). Kind of the opposite does GUIPointToWorldRay. There are many other useful methods in there but it of course depends on the needs. Even drawing 2d controls is possible you should use it sparsely. Settings and options should be displayed either in the inspector or in a seperate EditorWindow.
When you want to implement your own tool to somehow edit the scene this is a quite important little class. It doesn't provide much but controls an important feature. The static Tools.current property is an enum of type "Tool". Tool defines currently those values: View, Move, Rotate, Scale, Rect, None. Those should be familiar as they are the standard tools you have in the editor which can be switched with the tool buttons at the top left. The only really important value here for us is "None". Setting Tools.current to Tool.None disables all default tools which allows you to implement your own tool. The same does the Terrain inspector. When you select one of the "painting modes" in the inspector you might notice that all tool buttons at the top left will be toggled "off". That means the current tool is "None".
Tools.current
View, Move, Rotate, Scale, Rect, None
Another important thing you most likely need when implementing your own tool is to prevent the deselection of the current object. This is done by allocating a passive control id and pass it to HandleUtility.AddDefaultControl:
HandleUtility.AddDefaultControl
int myID = GUIUtility.GetControlID(FocusType.Passive);
HandleUtility.AddDefaultControl(myID);
That's all for now about sceneview, handles and custom tools.
To be continued ...
... omg 57 links ^^
The main purpose of my timeline editor is to display some events graphically.
It's for my level designer to create the event that happen all along the level.
Currently he can do this but only with some field and it's not really nice and intuitive. The parameters are the time, the type of gameobject based on a serialized enumeration and some others thing that don't need to be displayed in the timeline editor but in another part of the inspector.
The color of one timeline bar must be different function of the gameobject type contained in the enum, so I hope I can change the bar's color without use the "GUI.BackgroundColor".
Each bar size shows the duration of each event, some are one-time events and others can take some time.
I can explain more if it's necessary but I don't think it's usefull ^^. But if it's really necessary just ask me and I say you more ;)
The FixedRate is the physics update rate (FixedUpdate). This rate is indirectly set in your time settings(Fixed Timestep). You actually set the fixedDeltaTime in the time settings which is the reciprocal of the fixed-frame-rate.
That's always true for each fps-deltaTime pair:
fps = 1/dt
// and
dt = 1/fps
So the FixedRate is just another way to express the fixed timestep.
$$anonymous$$eep in mind that i don't use the real fixedDeltaTime in the demo. It's just a simulation of how FixedUpdate is processed.
You usually don't change the FixedRate at runtime since that would change the result of your physics calculations. The point of the fixedRate is to by constant ;)
@ZammyIsOnFire:Well the way OnGUI works is that the a gui control is managed in one place. Those "controls" aren't real objects as it's an immediate mode. So you can't really seperate those two things.
However you can simply wrap all controls in a class-based system and use delegates to process events. I've done something like that a couple of times. It's just a little bit of work. Just use something like this:
public abstract class GUIControl
{
public Rect position;
public GUIContent content = GUIContent.none;
public GUIStyle style = null;
public abstract void OnGUI();
}
public class GUIButton : GUIControl
{
public event System.Action<GUIControl> OnClick;
public override void OnGUI()
{
if (style == null)
style = "button";
if (GUI.Button(position, content, style) && OnClick != null)
OnClick(this);
}
}
public class GUIGroup : GUIControl
{
public List<GUIControl> childs = new List<GUIControl>();
public override void OnGUI()
{
if (style == null)
style = GUIStyle.none;
GUI.BeginGroup(position, content, style);
for (int i = 0; i < childs.Count; i++)
childs[i].OnGUI();
GUI.EndGroup();
}
}
And so on...
You can create wrapper classes like this for ell "control functions" you need or even create new more complex controls. Finally you might want to add some useful constructors to those classes and create a tree of controls. You might end up with a single GUIGroup as root object. This one you would handle in an actual OnGUI method of an EditorWindow or whereever you need it. As long as those are called from an actual OnGUI method (or OnInspectorGUI / OnSceneGUI) it should work fine.
@Questioning: The source? The source of the answer text? I'm not sure in which way this would be helpful^^. Since it's just text with some markup tags. If that's just want you wanted here it is. If you ask for an offline viewable version like a pdf or something the answer is: no, i don't have something like that ^^.
@Questioning:Oh you mean the FixedUpdate demo? Well, that actually wasn't related to this question. It was just an example ^^.
The project is quite old and i thought to implement more "modules" / levels to explain various things about Unity. That demo in particular is actually just a single script with about 400 lines. There are some small "helper" files.
I don't really keep that thing up-to-date so some things will no longer work in the current Unity version. Anyways here are 3 essential files:
ExplainFixedUpdate.cs
Drawing.cs
Extentions.cs
I'm not sure if i actually used anything from the Extensions files. I didn't clean up any code. It's just the last stand ^^. The test scene literally is simply an empty scene with the ExplainFixedUpdate script attached.
Custom Timeline Playable - GUI Override
0
Answers
Replicate Timeline in Animation window
1
Answer
EditorGUI elements require minimum size of 24px?
0
Answers
Are there any Editor fields which are Drag and Drop?
0
Answers
uGUI - aligning to the bottom of another element
0
Answers | https://answers.unity.com/questions/360901/editor-timeline-create-his-personnal-gui-timeline-.html?childToView=360910 | CC-MAIN-2020-16 | refinedweb | 4,679 | 65.22 |
Fast user-space locking
#include <linux/futex.h> #include <sys/time.h> int futex(int *uaddr, int op, int val, const struct timespec *timeout, int *uaddr2, int val3);
Note: There is no glibc wrapper for this system call; see NOTES. specify the duration of the wait. (This interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount.) If timeout is NULL, the call blocks indefinitely. onward...
This system call is Linux-specific..
restart_syscall(2), futex(7)
Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux (proceedings of the Ottawa Linux Symposium 2002), online at
Futex example library, futex-*.tar.bz2 at
This page is part of release 3.74 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://www.carta.tech/man-pages/man2/futex.2.html | CC-MAIN-2020-45 | refinedweb | 150 | 58.79 |
A ConstraintSegment2 represents a Constraint Edge. More...
#include <ConstraintSegment2.h>
A ConstraintSegment2 can belong to more than one ConstraintGraph2 object, thus it is unoriented. But the ConstraintGraph knows the orientation of its ConstraintSegment2's.
Splits the ConstraintSegment2 (which must be alive) at
splitPoint.
It may be impossible to represent a point on a certain line segment using floatingpoint arithmetic. Therefore it is highly recommended to split a ConstraintSegment2 object not just be inserting points into the triangulation but using the present method. It does not require that
splitPoint is exactly on the segment.
internal use only (unless you do something very unusual) | https://www.geom.at/fade25d/html/classGEOM__FADE25D_1_1ConstraintSegment2.html | CC-MAIN-2019-22 | refinedweb | 102 | 50.33 |
.
Create file named “.pythonrc” in your home directory by running the following command on your terminal:
$ vim ~/.pythonrc
Add the following lines in that file:
import rlcompleter, readline readline.parse_and_bind("tab: complete")
Save and close the file. Now open your “~/.profile” file if you are on OS X (“~/.bashrc” file if you are on Ubuntu), go to the last line, and add the following line after that:
export PYTHONSTARTUP="~/.pythonrc"
Save and close this file. We need to tell our “.profile” file that we have updated the environment variables. So let’s restart it by running the following command:
$ source ~/.profile
We are now ready to give it a spin. Open up the Python shell by typing “python” on your terminal. Let’s declare a string variable:
>>>>> my
In the second line, if you type “my” and hit “tab”, it will autocomplete it to “my_variable”. You can type “my_variable.” (notice the trailing “.”) and hit tab twice, it will display all the inbuilt methods that can be applied to a string variable.
If you import a module, you can see a list of all its methods as well:
>>> import os >>> os. Display all 234 possibilities? (y or n)
It will display a list of all the methods you can use with the “os” module.
———————————————————————————————————
Great post, if you are using zsh
add the following to ~/.zshrc file
export PYTHONSTARTUP=”$HOME/.pythonrc”
Thanks!
Pingback: Getting Started With Apache Spark In Python | Perpetual Enigma | https://prateekvjoshi.com/2015/10/27/enabling-tab-autocomplete-in-python-shell/?replytocom=16588 | CC-MAIN-2021-39 | refinedweb | 241 | 78.04 |
O'Reilly Book Excerpts: Palm OS Programming, 2nd Edition
Structure of a Palm Application, Part 2by Neil Rhodes and Julie McKeehan
A Simple Application
Now it's time to apply what you just learned about an application's interaction with the OS, its
PilotMain routine, and the event loop to an actual application. We are using OReilly Starter, the application we first discussed in Chapter 4.
What the Application Does--Its User Interface
Our OReilly Starter application has two forms. On the first form, there are two buttons. Pressing the first one causes the Palm device to beep. Pressing the second button switches the view to the second form. The second form has a single button that returns to the previous form (see Figure 5-3). This is all there is to our simple application.
An Overview of the Source Files
Here are the source files that make up this application (as opposed to the tools-specific files like CodeWarrior .mcp files or PRC-Tools .def files).
- Main.c
- This file contains the main entry point (PilotMain) of the application. It also includes the event loop, application startup and shutdown code, and the code to load forms as needed.
- MainForm.c
- This contains the code that handles everything that occurs in the first form.
- SecondForm.c
- This contains the code for the second form.
- Utils.c
- This contains some utility routines that can be used throughout the application. You can include this same source file in all your applications.
- Resources.rcp
- This PilRC file contains the UI elements (the forms, form objects, and the application name).
- ResourceDefines.h
- This file defines constants for all the application's resources. This file is included by the .c files, as well as Resources.rcp.
- MainForm.h
- This declares the event handler for the main form. This is included by both Main.c and MainForm.c.
- SecondForm.h
- This declares the event handler for the second form. It is also included by both Main.c and SecondForm.c.
- Constants.h
- This file contains the defined constants used throughout the application.
- Utils.h
- This declares the utility functions in Utils.c.
The Source File of Main.c
Main.c starts with the #include files (see Example 5-4).
Example 5-4: First part of Main.c: #defines and #includes
#define DO_NOT_ALLOW_ACCESS_TO_INTERNALS_OF_STRUCTS #include <BuildDefines.h> #ifdef DEBUG_BUILD #define ERROR_CHECK_LEVEL ERROR_CHECK_FULL #endif #include <PalmOS.h> #include "ResourceDefines.h" #include "MainForm.h" #include "SecondForm.h" #include "Utils.h" #include "Constants.h"
TIP: PalmOS.h is an include file that contains most of the standard Palm OS include files. By default, it defines an
ERROR_CHECK_LEVELof
ERROR_CHECK_PARTIAL, which is suitable for a release build. It doesn't, however, provide the checking we'd like for a debug build (see Chapter 7 for more information on debug builds). Thus, if we're compiling a
DEBUG_BUILD, we redefine
ERROR_CHECK_LEVEL. We must #include BuildDefines.h first, in order to obtain the definition of
ERROR_CHECK_FULL.
We define
DO_NOT_ALLOW_ACCESS_TO_INTERNALS_OF_STRUCTS to help with good coding practices. This will cause the 4.0 SDK to generate a compile-time error for us if we try to access fields within OS structures directly, rather than through appropriate API calls. You should always use the APIs, rather than fool around within an OS structure directly.
Example 5-5 shows the remainder of Main.c.
Example 5-5: Remaining functions in Main.c); } static Err AppStart(void) { return errNone; } static void AppStop(void) { FrmCloseAllForms( ); } UInt32 PilotMain(UInt16 launchCode, MemPtr launchParameters, UInt16 launchFlags) { #pragma unused(launchParameters) Err error; switch (launchCode) { case sysAppLaunchCmdNormalLaunch: error = RomVersionCompatible (kOurMinVersion, launchFlags); if (error) return error; error = AppStart( ); if (error) rror; FrmGotoForm(MainForm); AppEventLoop( ); AppStop( ); break; default: break; } return errNone; }
kOurMinVersion is defined as Version 3.0 of the Palm OS in Constants.h.
The Form Files of the Application
Main.c is the source file containing routines responsible for handling the main form (see Example 5-6).
Example 5-6: Main.c
/* Copyright (c) 2000-2001, Neil Rhodes and Julie McKeehan neil@pobox.com All rights reserved. From the book "Palm OS Programming (2nd edition)" by O'Reilly. Permission granted to use this file however you see fit. */ #define DO_NOT_ALLOW_ACCESS_TO_INTERNALS_OF_STRUCTS #include <BuildDefines.h> #ifdef DEBUG_BUILD #define ERROR_CHECK_LEVEL ERROR_CHECK_FULL #endif #include <PalmOS.h> #include "ResourceDefines.h" #include "MainForm.h" static void MainFormInit(FormPtr form) { #pragma unused(form) // Warning-- don't do any drawing in this routine. // Also, don't call FrmSetFocus from here (it must be called *after* // FrmDrawForm). } static void MainFormDeinit(FormPtr form) { #pragma unused(form) } Boolean MainFormHandleEvent(EventPtr event) { Boolean handled = false; FormPtr form; switch (event->eType) { case frmOpenEvent: form = FrmGetActiveForm( ); MainFormInit(form); FrmDrawForm(form); // Here's where you'd add a call to FrmSetFocus. handled = true; break; case ctlSelectEvent: switch (event->data.ctlSelect.controlID) { case MainBeepButton: SndPlaySystemSound(sndWarning); handled = true; break; case MainGotoSecondFormButton: FrmGotoForm(SecondForm); handled = true; break; } break; case frmCloseEvent: MainFormDeinit(FrmGetActiveForm( )); handled = false; break; default: break; } return handled; }
The event handler for the main form handles three different kinds of events:
- frmOpenEvent
- frmCloseEvent (discussed in Chapter 8, along with the previous event)
ctlSelectEvent(specifies that a control has been chosen)
The MainFormInit and MainFormDeinit routines are there because it is quite common to need to do some initialization when a form opens. You will often need to do some cleanup when a form closes. This is where such things should happen.
The MainFormHandleEvent handles the
ctlSelectEvent by looking to see what control was chosen:
- If the beep button is chosen, it plays a sound.
- If the Goto button is chosen, it calls FrmGotoForm, which closes this form and opens the other one.
| http://www.linuxdevcenter.com/pub/a/wireless/excerpt/palmprog2_ch5/index2.html | CC-MAIN-2016-30 | refinedweb | 930 | 51.24 |
Member
40 Points
Contributor
6716 Points
Jun 26, 2009 03:41 PM|paul.vencill|LINK
I've done it as a member property of an object that is getting model bound, so the DMB can definitely do it that way (in that case, I represented the enum as a dropdownlist). NOt sure if it would work on its own. going from JS might be more complex; I'll have to think about it.
Jun 26, 2009 04:22 PM|Haacked|LINK
Yes, it is possible. You can submit either the integer value or the string name of the enum value. A quick experiment verifies this. For example, in HomeController.cs write this.
public class HomeController : Controller { public ActionResult Index() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(MyEnum value) { ViewData["Message"] = value.ToString(); return View(); } } public enum MyEnum { Foo, Bar, Baz }
Then in Index.aspx include the form:
<% using (Html.BeginForm()) { %> <%= Html.TextBox("value") %> <input type="submit" /> <% } %>
And try submitting the value 0 then try submitting Bar and you'll see they both work.
Phil
2 replies
Last post Jun 26, 2009 04:22 PM by Haacked | http://forums.asp.net/t/1440432.aspx | CC-MAIN-2014-42 | refinedweb | 187 | 68.77 |
Rendering GeoJSON
Before getting into editing, we'll take a look at basic feature rendering with a vector source and layer. The workshop includes a
countries.json GeoJSON file in the
data directory. We'll start by just loading that data up and rendering it on a map.; background-color: #04041b; } </style> </head> <body> <div id="map-container"></div> <script src="./main.js" type="module"></script> </body> </html>
Now we'll import the three important ingredients for working with vector data:
- a format for reading and writing serialized data (GeoJSON in this case)
- a vector source for fetching the data and managing a spatial index of features
- a vector layer for rendering the features on the map
Update your
main.js to load and render a local file containing GeoJSON features:
import GeoJSON from 'ol/format/GeoJSON'; import Map from 'ol/Map'; import VectorLayer from 'ol/layer/Vector'; import VectorSource from 'ol/source/Vector'; import View from 'ol/View'; new Map({ target: 'map-container', layers: [ new VectorLayer({ source: new VectorSource({ format: new GeoJSON(), url: './data/countries.json', }), }), ], view: new View({ center: [0, 0], zoom: 2, }), });
You should now be able to see a map with country borders at.
Since we'll be reloading the page a lot, it would be nice if the map stayed where we left it in a reload. We can bring in the
ol-hashed package to make this work. This package is already installed as part of the workshop dependendencies. If it were not already included, you could install it with
npm install ol-hashed.
Then in our
main.js we'll import the function exported by the package:
import sync from 'ol-hashed';
Now we need to assign our map to a variable (named
map) so we can pass that variable to the
sync function:
const map = new Map({
And now we can call the
sync function with our map:
sync(map);
Now you should see that page reloads keep the map view stable. And the back button works as you might expect. | https://openlayers.org/workshop/en/vector/geojson.html | CC-MAIN-2021-43 | refinedweb | 339 | 59.13 |
import bb.cascades 1.2 import bb.multimedia 1.2 Page { Container { id: customSoundsContainer layout: StackLayout { } attachedObjects: [ MediaPlayer { id: myPlayer } ] DropDown { id: ddlSoundSelector title: "Sound: " Option { text: "Doorbell 1" value: "asset:///sounds/Doorbell_001.wav" selected: true } Option { text: "Doorbell 2" value: "asset:///sounds/Doorbell_002.wav" } } Button { id: btnPlaySound text: "Play Sound" onClicked: { myPlayer.setSourceUrl(ddlSoundSelector.selectedValue); myPlayer.play() } } } }
Tutorial: Custom sounds using Cascades
The sounds you include in your app play a critical role in creating an enhanced user experience. The user performs some action in your app, and the app responds by playing a sound. This sound can be a car engine racing in a driving game, the sound of a doorbell when the user clicks a specific Button, or any other sounds you include to respond to user events in your apps. In short, sounds make your apps come alive.
This tutorial shows you how to play custom sounds in an app. We create the app shown in the image to the right using two controls: a DropDown that's used to choose a custom sound, and a play button that's used to play the sound chosen.
You will learn to:
- Set up your app to play custom sounds
- Play custom sounds in response to UI signals
The image to the right shows the two custom sound files that can be selected from the DropDown control.
custom sounds app from scratch.The complete source code for the finished app is shown at the end of this tutorial and is available for download.
Download the full source code
Set up your project
Let's begin by creating a Cascades project using the template for a standard empty project. For more information about creating a project, see Tutorial: Create your first Cascades app.
Add sound file assets
Let's add two sound files to your project's assets folder. You can use your own custom sound files, or you can download the two sound files from here: custom_sounds_tutorial_assets.zip.
When you've downloaded the custom_sounds_tutorial_assets.zip file, extract the sound files to your desktop (or another folder on your computer) and add them to your app by following these steps:
- In your project's assets folder, create a sounds folder.
- Right-click the sounds folder and click Import.
- In the Import box, select General > File System and click Next.
- Click Browse, locate the folder where your sound files are stored, select it and click OK.
- In the right pane, select the check boxes beside each of the sound files that you want to import.
- Click Finish to import the sound files into your sounds folder.
As you can see, we've added two sound files called Doorbell_001.wav and Doorbell_002.wav to our newly created sounds folder.
After you've successfully imported your custom sound files, it's time to put some QML code into your project's main.qml file to create the app's UI.
Define a MediaPlayer object
You must put an import statement in your main.qml file to import the multimedia library. This import statement allows you to use the MediaPlayer to play your custom sounds. Here's a QML code sample showing the import statement.
import bb.multimedia 1.2
To play custom sounds, you must also define a MediaPlayer object and attach it to the root element (such as the Container) in your main.qml file. Here's a QML code sample showing the import statement and the MediaPlayer object definition.
import bb.cascades 1.2 import bb.multimedia 1.2 Page { Container { attachedObjects: [ MediaPlayer { id: myPlayer } ] } }
Add UI controls
Let's create our app's UI by adding two UI controls that we can use to play custom sounds.
We add a DropDown that's used to select a custom sound, and add our two sounds to the set of options that the user can select.
Note how the paths to our sound files are referenced. The MediaPlayer can play sound files from many locations including remote locations. For example, if sound files are stored on a remote server, then you can use the URL to those sound files to set the sourceUrl of the MediaPlayer, and your app plays the sound files from that location.
In this sample, the sound files are in our assets folder, within the sounds folder. To use these sound resources, you can define their path in the value property of each Option object using the format "asset:///path/to/sound_file", as shown in the code sample below.
// ... Page { Container { // ... DropDown { id: ddlSoundSelector title: "Sound: " Option { text: "Doorbell 1" value: "asset:///sounds/Doorbell_001.wav" selected: true } Option { text: "Doorbell 2" value: "asset:///sounds/Doorbell_002.wav" } } } }
After the DropDown, we add a Button whose onClicked signal handler is used to set the player's sourceUrl property with the setSourceUrl() function, and play the sound selected in the DropDown by calling the play() function of the MediaPlayer class.
// ... Page { Container { // ... Button { id: btnPlaySound text: "Play Sound" onClicked: { myPlayer.setSourceUrl(ddlSoundSelector.selectedValue); myPlayer.play() } } } }
That's it. Build your project and try it out!
Last modified: 2015-07-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/documentation/graphics_multimedia/audio_video/custom_sounds_tut_cascades.html | CC-MAIN-2018-13 | refinedweb | 866 | 64.3 |
One. One of the few things that I give Rails credit for is its well thought-out REST support, both for providing and consuming these APIs (as its been explained by all the Rails fanboys I work with).
Seriously, if you’ve never used REST, but you’ve ever had to work with (or worse, create) a SOAP API, or simply opened a WSDL and had your head explode, boy do I have good news for you!
So, What on Earth is REST? Why Should You Care?
Before we get into writing some code, I want to make sure everyone’s got a good understanding of what REST is and how its great for APIs. First, technically speaking, REST isn’t specific to just APIs, it’s more of a generic concept. However, obviously, for the sake of this article we’ll be talking about it in the context of an API. So, let’s look at the basic needs of an API and how REST addresses them.
Requests
All APIs need to accept requests. Typically, with a RESTful API, you’ll have a well-defined URL scheme. Let’s say you want to provide an API for users on your site (I know, I always use the “users” concept for my examples). Well, your URL structure would probably be something like, “api/users” and “api/users/[id]” depending on the type of operation being requested against your API. You also need to consider how you want to accept data. These days a lot of people are using JSON or XML, and I personally prefer JSON because it works well with JavaScript, and PHP has easy functionality for encoding and decoding it. If you wanted your API to be really robust, you could accept both by sniffing out the content-type of the request (i.e. application/json or application/xml), but it’s perfectly acceptable to restrict things to one content type. Heck, you could even use simple key/value pairs if you wanted.
The other piece of a request is what it’s actually meant to do, such as load, save, etc. Normally, you’d have to come up with some sort of architecture that defines what action the requester (consumer) desires, but REST simplifies that. By using HTTP request methods, or verbs, we don’t need to define anything. We can just use the GET, POST, PUT, and DELETE methods, and that covers every request we’d need. You can equate the verbs to your standard crud-style stuff: GET = load/retrieve, POST = create, PUT = update, DELETE = well, delete. It’s important to note that these verbs don’t directly translate to CRUD, but it is a good way to think about them. So, going back to the above URL examples, let’s take a look at what some possible requests could mean:
- GET request to /api/users – List all users
- GET request to /api/users/1 – List info for user with ID of 1
- POST request to /api/users – Create a new user
- PUT request to /api/users/1 – Update user with ID of 1
- DELETE request to /api/users/1 – Delete user with ID of 1
As you hopefully see, REST has already taken care of a lot of the major headaches of creating your own API through some simple, well-understood standards and protocols, but there’s one other piece to a good API…
Responses
So, REST handles requests very easily, but it also makes generating responses easy. Similar to requests, there are two main components of a RESTful response: the response body, and a status code. The response body is pretty easy to deal with. Like requests, most responses in REST are usually either JSON or XML (perhaps just plain text in the case of POSTs, but we’ll cover that later). And, like requests, the consumer can specify the response type they’d like through another part of the HTTP request spec, “Accept”. If a consumer wishes to receive an XML response, they’d just send an Accept header as a part of their request saying as much (”Accept: application/xml”). Admittedly, this method isn’t as widely adopted (tho it should be), so you have can also use the concept of an extension in the URL. For example, /api/users.xml means the consumer wants XML as a response, similarly /api/users.json means JSON (same for things like /api/users/1.json/xml). Either way you choose (I say do both), you should pick a default response type as a lot of the time people wont’ even tell you what they want. Again, I’d say go with JSON. So, no Accept header or extension (i.e. /api/users) should not fail, it should just fail-over to the default response-type.
But what about errors and other important status messages associated with requests? Easy, use HTTP status codes! This is far and above one of my favorite things about creating RESTful APIs. By using HTTP status codes, you don’t need to come up with a error / success scheme for your API, it’s already done for you. For example, if a consumer POSTS to /api/users and you want to report back a successful creation, simply send a 201 status code (201 = Created). If it failed, send a 500 if it failed on your end (500 = Internal Server Error), or perhaps a 400 if they screwed up (400 = Bad request). Maybe they’re trying to POST against an API endpoint that doesn’t accept posts… send a 501 (Not implemented). Perhaps your MySQL server is down, so your API is temporarily borked… send a 503 (Service unavailable). Hopefully, you get the idea. If you’d like to read up a bit on status codes, check them out on wikipedia: List of HTTP Status Codes.
I’m hoping you see all the advantages you get by leveraging the concepts of REST for your APIs. It really is super-cool, and its a shame its not more widely talked about in the PHP community (at least as far as I can tell). I think this is likely due to the lack of good documentation on how to deal with requests that aren’t GET or POST, namely PUT and DELETE. Admittedly, it is a bit goofy dealing with these, but it certainly isn’t hard. I’m also sure some of the popular frameworks out there probably have some sort of REST implementation, but I’m not a huge framework fan (for a lot of reasons that I won’t get into), and it’s also good to know these things even if somebody’s already created the solution for you.
If you’re still not convinced that this is a useful API paradigm, take a look at what REST has done for Ruby on Rails. One of its major claims to fame is how easy it is to create APIs (through some sort of RoR voodoo, I’m sure), and rightly so. Granted I know very little about RoR, but the fanboys around the office have preached this point to me many times. But, I digress… let’s write some code!
Getting Started with REST and PHP
One last disclaimer: the code we’re about to go over is in no way intended to be used as an example of a robust solution. My main goal here is to show how to deal with the individual components of REST in PHP, and leave creating the final solution up to you.
So, let’s dig in! I think the best way to do something practical is to create a class that will provide all the utility functions we need to create a REST API. We’ll also create a small class for storing our data. You could also then take this, extend it, and apply it to your own needs. So, let’s stub some stuff out:
- class RestUtils
- {
- public static function processRequest()
- {
- }
- public static function sendResponse($status = 200, $body = ”, $content_type = ‘text/html’)
- {
- }
- public static function getStatusCodeMessage($status)
- {
- // these could be stored in a .ini file and loaded
- // via parse_ini_file()… however, this will suffice
- // for an example
- $codes = Array(
- 100 => ‘Continue’,
- 101 => ‘Switching Protocols’,
- 200 => ‘OK’,
- 201 => ‘Created’,
- 202 => ‘Accepted’,
- 203 => ‘Non-Authoritative Information’,
- 204 => ‘No Content’,
- 205 => ‘Reset Content’,
- 206 => ‘Partial Content’,
- 300 => ‘Multiple Choices’,
- 301 => ‘Moved Permanently’,
- 302 => ‘Found’,
- 303 => ‘See Other’,
- 304 => ‘Not Modified’,
- 305 => ‘Use Proxy’,
- 306 => ‘(Unused)’,
- 307 => ‘Temporary Redirect’,
- 400 => ‘Bad Request’,
- 401 => ‘Unauthorized’,
- 402 => ‘Payment Required’,
- 403 => ‘Forbidden’,
- 404 => ‘Not Found’,
- 405 => ‘Method Not Allowed’,
- 406 => ‘Not Acceptable’,
- 407 => ‘Proxy Authentication Required’,
- 408 => ‘Request Timeout’,
- 409 => ‘Conflict’,
- 410 => ‘Gone’,
- 411 => ‘Length Required’,
- 412 => ‘Precondition Failed’,
- 413 => ‘Request Entity Too Large’,
- 414 => ‘Request-URI Too Long’,
- 415 => ‘Unsupported Media Type’,
- 416 => ‘Requested Range Not Satisfiable’,
- 417 => ‘Expectation Failed’,
- 500 => ‘Internal Server Error’,
- 501 => ‘Not Implemented’,
- 502 => ‘Bad Gateway’,
- 503 => ‘Service Unavailable’,
- 504 => ‘Gateway Timeout’,
- 505 => ‘HTTP Version Not Supported’
- );
- return (isset($codes[$status])) ? $codes[$status] : ”;
- }
- }
- class RestRequest
- {
- private $request_vars;
- private $data;
- private $http_accept;
- private $method;
- public function __construct()
- {
- $this->request_vars = array();
- $this->data = ”;
- $this->http_accept = (strpos($_SERVER[‘HTTP_ACCEPT’], ‘json’)) ? ‘json’ : ‘xml’;
- $this->method = ‘get’;
- }
-;
- }
- }
class RestUtils { public static function processRequest() { } public static function sendResponse($status = 200, $body = '', $content_type = 'text/html') { } public static function getStatusCodeMessage($status) { // these could be stored in a .ini //file and loaded // via parse_ini_file()... however, //this will suffice // for an example ] : ''; } } class RestRequest { private $request_vars; private $data; private $http_accept; private $method; public function __construct() { $this->request_vars = array(); $this->data = ''; $this->http_accept = (strpos($_SERVER['HTTP_ACCEPT'], 'json')) ? 'json' : 'xml'; $this->method = 'get'; }; } }
OK, so what we’ve got is a simple class for storing some information about our request (RestRequest), and a class with some static functions we can use to deal with requests and responses. As you can see, we really only have two functions to write… which is the beauty of this whole thing! Right, let’s move on…
Processing the Request
Processing the request is pretty straight-forward, but this is where we can run into a few catches (namely with PUT and DELETE… mostly PUT). We’ll go over those in a moment, but let’s examine the RestRequest class a bit. If you’ll look at the constructor, you’ll see that we’re already interpreting the HTTP_ACCEPT header, and defaulting to JSON if none is provided. With that out of the way, we need only deal with the incoming data.
There are a few ways we could go about doing this, but let’s just assume that we’ll always get a key/value pair in our request: ‘data’ => actual data. Let’s also assume that the actual data will be JSON. As stated in my previous explanation of REST, you could look at the content-type of the request and deal with either JSON or XML, but let’s keep it simple for now. So, our process request function will end up looking something like this:
- public static function processRequest()
- {
- // get our verb
- $request_method = strtolower($_SERVER[‘REQUEST_METHOD’]);
- $return_obj = new RestRequest();
- // we’ll store our data here
- $data = array();
- switch ($request_method)
- {
- // gets are easy…
- case ‘get’:
- $data = $_GET;
- break;
- // so are posts
- case ‘post’:
- $data = $_POST;
- break;
- // here’s the tricky bit…
- case ‘put’:
- //(‘php://input’), $put_vars);
- $data = $put_vars;
- break;
- }
- // store the method
- $return_obj->setMethod($request_method);
- // set the raw data, so we can access it if needed (there may be
- // other pieces to your requests)
- $return_obj->setRequestVars($data);
- if(isset($data[‘data’]))
- {
- // translate the JSON to an Object for use however you want
- $return_obj->setData(json_decode($data[‘data’]));
- }
- return $return_obj;
- }
public static function processRequest() { // get our verb $request_method = strtolower($_SERVER['REQUEST_METHOD']); $return_obj = new RestRequest(); // we'll store our data here $data = array(); switch ($request_method) { // gets are easy... case 'get': $data = $_GET; break; // so are posts case 'post': $data = $_POST; break; // here's the tricky bit... case 'put': //('php://input'), $put_vars); $data = $put_vars; break; } // store the method $return_obj->setMethod($request_method); // set the raw data, so we can access it if needed //(there may be other pieces to your requests) $return_obj->setRequestVars($data); if(isset($data['data'])) { // translate the JSON to an Object //for use however you want $return_obj->setData(json_decode($data['data'])); } return $return_obj; }
Like I said, pretty straight-forward. However, a few things to note… First, you typically don’t accept data for DELETE requests, so we don’t have a case for them in the switch. Second, you’ll notice that we store both the request variables, and the parsed JSON data. This is useful as you may have other stuff as a part of your request (say an API key or something) that isn’t truly the data itself (like a new user’s name, email, etc.).
So, how would we use this? Let’s go back to the user example. Assuming you’ve routed your request to the correct controller for users, we could have some code like this:
- $data = RestUtils::processRequest();
- switch($data->getMethod)
- {
- case ‘get’:
- // retrieve a list of users
- break;
- case ‘post’:
- $user = new User();
- $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
- // and so on…
- $user->save();
- break;
- // etc, etc, etc…
- }
$data = RestUtils::processRequest(); switch($data->getMethod) { case 'get': // retrieve a list of users break; case 'post': $user = new User(); $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner // and so on... $user->save(); break; // etc, etc, etc... }
Please don’t do this in a real app, this is just a quick-and-dirty example. You’d want to wrap this up in a nice control structure with everything abstracted properly, but this should help you get an idea of how to use this stuff. But I digress, let’s move on to sending a response.
Sending the Response
Now that we can interpret the request, let’s move on to sending the response. We already know that all we really need to do is send the correct status code, and maybe some body (if this were a GET request, for example), but there is an important catch to responses that have no body. Say somebody made a request against our sample user API for a user that doesn’t exist (i.e. api/user/123). The appropriate status code to send is a 404 in this case, but simply sending the status code in the headers isn’t enough. If you viewed that page in your web browser, you would get a blank screen. This is because Apache (or whatever your web server runs on) isn’t sending the status code, so there’s no status page. We’ll need to take this into account when we build out our function. Keeping all that in mind, here’s what the code should look like:
- public static function sendResponse($status = 200, $body = ”, $content_type = ‘text/html’)
- {
- $status_header = ‘HTTP/1.1 ‘ . $status . ‘ ‘ . RestUtils::getStatusCodeMessage($status);
- // set the status
- header($status_header);
- // set the content type
- header(‘Content-type: ‘ . $content_type);
- // pages with body are easy
- if($body != ”)
- {
- // send the body
- echo $body;
- exit;
- }
- // we need to create the body if none is passed
- else
- {
- // create some body messages
- // this is purely optional, but makes the pages a little nicer to read
- // for your users. Since you won’t likely send a lot of different status codes,
- // this also shouldn’t be too ponderous to maintain
- switch($status)
- {
- case 401:
- $message = ‘You must be authorized to view this page.’;
- break;
- case 404:
- $message = ‘The requested URL ‘ . $_SERVER[‘REQUEST_URI’] . ‘ was not found.’;
- break;
- case 500:
- $message = ‘The server encountered an error processing your request.’;
- break;
- case 501:
- $message = ‘The requested method is not implemented.’;
- break;
- }
- // servers don’t always have a signature turned on (this is an apache directive “ServerSignature On”)
- $signature = ($_SERVER[‘SERVER_SIGNATURE’] == ”) ? $_SERVER[‘SERVER_SOFTWARE’] . ‘ Server at ‘ . $_SERVER[‘SERVER_NAME’] . ‘ Port ‘ . $_SERVER[‘SERVER_PORT’] : $_SERVER[‘SERVER_SIGNATURE’];
- // this should be templatized in a real-world solution
- $body = ‘<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “”>
- <html>
- <head>
- <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
- <title>’ . $status . ‘ ‘ . RestUtils::getStatusCodeMessage($status) . ‘</title>
- </head>
- <body>
- <h1>’ . RestUtils::getStatusCodeMessage($status) . ‘</h1>
- <p>’ . $message . ‘</p>
- <hr />
- <address>’ . $signature . ‘</address>
- </body>
- </html>’;
- echo $body;
- exit;
- }
- }
public static function sendResponse($status = 200, $body = '', $content_type = 'text/html') { $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status); // set the status header($status_header); // set the content type header('Content-type: ' . $content_type); // pages with body are easy if($body != '') { // send the body echo $body; exit; } //atized in a real-world solution $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <html> <head> <meta http- <title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title> </head> <body> <h1>' . RestUtils::getStatusCodeMessage($status) . '</h1> <p>' . $message . '</p> <hr /> <address>' . $signature . '</address> </body> </html>'; echo $body; exit; } }
That’s It! We technically have everything we need now to process requests and send responses. Let’s talk a bit more about why we need to have a standard body response or a custom one. For GET requests, this is pretty obvious, we need to send XML / JSON content instead of a status page (provided the request was valid). However, there’s also POSTs to deal with. Inside of your apps, when you create a new entity, you probably fetch the new entity’s ID via something like mysql_insert_id(). Well, if a user posts to your API, they’ll probably want that new ID as well. What I’ll usually do in this case is simply send the new ID as the body (with a 201 status code), but you could also wrap that in XML or JSON if you’d like.
So, let’s extend our sample implementation a bit:
- switch($data->getMethod)
- {
- // this is a request for all users, not one in particular
- case ‘get’:
- $user_list = getUserList(); // assume this returns an array
- if($data->getHttpAccept == ‘json’)
- {
- RestUtils::sendResponse(200, json_encode($user_list), ‘application/json’);
- }
- else if ($data->getHttpAccept == ‘xml’)
- {
- // using the XML_SERIALIZER Pear Package
- $options = array
- (
- ‘indent’ => ‘ ‘,
- ‘addDecl’ => false,
- ‘rootName’ => $fc->getAction(),
- XML_SERIALIZER_OPTION_RETURN_RESULT => true
- );
- $serializer = new XML_Serializer($options);
- RestUtils::sendResponse(200, $serializer->serialize($user_list), ‘application/xml’);
- }
- break;
- // new user create
- case ‘post’:
- $user = new User();
- $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
- // and so on…
- $user->save();
- // just send the new ID as the body
- RestUtils::sendResponse(201, $user->getId());
- break;
- }
switch($data->getMethod) { // this is a request for all users, not one in particular case 'get': $user_list = getUserList(); // assume this returns an array if($data->getHttpAccept == 'json') { RestUtils::sendResponse(200, json_encode($user_list), 'application/json'); } else if ($data->getHttpAccept == 'xml') { // using the XML_SERIALIZER Pear Package $options = array ( 'indent' => ' ', 'addDecl' => false, 'rootName' => $fc->getAction(), XML_SERIALIZER_OPTION_RETURN_RESULT => true ); $serializer = new XML_Serializer($options); RestUtils::sendResponse(200, $serializer->serialize($user_list), 'application/xml'); } break; // new user create case 'post': $user = new User(); $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner // and so on... $user->save(); // just send the new ID as the body RestUtils::sendResponse(201, $user->getId()); break; }
Again, this is just an example, but it does show off (I think, at least) how little effort it takes to implement RESTful stuff.
Wrapping Up
So, that’s about it. I’m pretty confident that I’ve beaten the point that this should be quite easy into the ground, so I’d like to close with how you can take this stuff further and perhaps properly implement it.
In a real-world MVC application, what you would probably want to do is set up a controller for your API that loads individual API controllers. For example, using the above stuff, we’d possibly create a UserRestController which had four methods: get(), put(), post(), and delete(). The API controller would look at the request and determine which method to invoke on that controller. That method would then use the utils to process the request, do what it needs to do data-wise, then use the utils to send a response.
You could also take it a step further than that, and abstract out your API controller and data models a bit more. Rather than explicitly creating a controller for every data model in your app, you could add some logic into your API controller to first look for an explicitly defined controller, and if none is found, try to look for an existing model. For example, the url “api/user/1″, would first trigger a lookup for a “user” rest controller. If none is found, it could then look for a model called “user” in your app. If one is found, you could write up a bit of automated voodoo to automatically process all the requests against those models.
Going even further, you could then make a generic “list-all” method that works similar to the previous paragraph’s example. Say your url was “api/users”. The API controller could first check for a “users” rest controller, and if none was found, recognize that users is pluaralized, depluralize it, and then look for a “user” model. If one’s found, load a list the list of users and send that off.
Finally, you could add digest authentication to your API quite easily as well. Say you only wanted properly authenticated users to access your API, well, you could throw some code like this into your process request functionality (borrowed from an existing app of mine, so there’s some constants and variables referenced that aren’t defined in this snippet):
- // figure out if we need to challenge the user
- if(emptyempty($_SERVER[‘PHP_AUTH_DIGEST’]))
- {
- header(‘HTTP/1.1 401 Unauthorized’);
- header(‘WWW-Authenticate: Digest realm=”‘ . AUTH_REALM . ‘”,qop=”auth”,nonce=”‘ . uniqid() . ‘”,opaque=”‘ . md5(AUTH_REALM) . ‘”‘);
- // show the error if they hit cancel
- die(RestControllerLib::error(401, true));
- }
- // now, analayze the PHP_AUTH_DIGEST var
- if(!($data = http_digest_parse($_SERVER[‘PHP_AUTH_DIGEST’])) || $auth_username != $data[‘username’])
- {
- // show the error due to bad auth
- die(RestUtils::sendResponse(401));
- }
- // so far, everything’s good, let’s now check the response a bit more…
- $A1 = md5($data[‘username’] . ‘:’ . AUTH_REALM . ‘:’ . $auth_pass);
- $A2 = md5($_SERVER[‘REQUEST_METHOD’] . ‘:’ . $data[‘uri’]);
- $valid_response = md5($A1 . ‘:’ . $data[‘nonce’] . ‘:’ . $data[‘nc’] . ‘:’ . $data[‘cnonce’] . ‘:’ . $data[‘qop’] . ‘:’ . $A2);
- // last check..
- if($data[‘response’] != $valid_response)
- {
- die(RestUtils::sendResponse(401));
- }
// figure out if we need to challenge the user if(empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="' . AUTH_REALM . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5(AUTH_REALM) . '"'); // show the error if they hit cancel die(RestControllerLib::error(401, true)); } // now, analayze the PHP_AUTH_DIGEST var if(!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || $auth_username != $data['username']) { // show the error due to bad auth die(RestUtils::sendResponse(401)); } // so far, everything's good, let's now check the response a bit more... $A1 = md5($data['username'] . ':' . AUTH_REALM . ':' . $auth_pass); $A2 = md5($_SERVER['REQUEST_METHOD'] . ':' . $data['uri']); $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2); // last check.. if($data['response'] != $valid_response) { die(RestUtils::sendResponse(401)); }
Pretty cool stuff, huh? With a little bit of code and some clever logic, you can add a fully functional REST API to your apps very quickly. I’m not just saying that to cheerlead the concept either, I implemented this stuff into one of my personal frameworks in about half a day, and then spent another half day adding all sorts of cool magic to it. If you (the reader) are interested in seeing my final implementation, drop me a note in the comments and I’d be happy to share it with you! Also, if you’ve got any cool ideas you’d like to share, be sure to drop those in the comments as well… if I like it enough, I’d even let you guest author your own article on the subject!
Until next time…
UPDATE: The much-requested follow-up to this article has been posted: Making RESTful Requests in PHP
See all REST with ASP.NET MVC :
Reference :
A strong productive technique associated with them may deliver you the greatest ranking with very fast period.
Very effectively written information. Will probably be beneficial to anybody who usess it, together with myself. Keep up the great work – for certain ill check out more posts.
Pingback: SQUARISM »until lambs become lions How to write a Ruby and Rails 3 REST API « Chandara | https://lchandara.wordpress.com/2011/08/13/create-a-rest-api-with-php/ | CC-MAIN-2017-26 | refinedweb | 4,020 | 58.72 |
I hear alot of people saying not use:
system("pause"); system("cls"); system("title");
I think you get what I mean, so I'm trying to make functions that will replace all of these, and for my first installment I'm going to show you how to replace system("pause");. Here is what I have.
#include <iostream> #include <conio.h> void PrsAnyKey2Cont (); char KeyStroke; void PrsAnyKey2Cont () { cout << "Press any key to continue . . .\n"; KeyStroke = getch (); KeyStroke = getch (); switch (KeyStroke) { default : break; } } int main () { cout << "Hello world!!" << endl; PrsAnyKey2Cont (); return 0; }
There are probably a million things wrong with this right now and I plan on making a better function that will allow you to set the time of the pause and wether or not the user even needs to input a key to continue. Thanks for any constructive critisism!! ^_^ | https://www.daniweb.com/programming/software-development/threads/104737/replacing-system-pause-with-a-function | CC-MAIN-2017-47 | refinedweb | 140 | 77.57 |
The.
Table of contents:
$> cd /folder1/folder2 /folder1/folder2 $> pwd /folder1/folder2
Building Ogre
First, create a folder where the whole Ogre3D project will live:
$> sudo mkdir -p /opt/dev:
/opt/dev/ $> mkdir dependencies
Go to the following link and download ogre3D’s dependencies:
Unzip the file you downloaded. This will contain a folder called Dependencies. Copy the content of that folder to the following location:
/opt/dev/dependencies
You should have something like this::
/opt/dev/dependencies/lib/Release $> lipo -info libOIS.a Architectures in the fat file: libOIS.a are: x86_64 i386
To download the Ogre3D's code, write in a terminal:
$> cd /opt/dev /opt/dev/ $> hg clone ogre3d-1.9.0:
opt/dev/$> du -sh /opt/dev/ogre3d-1.9.0/ 461M /opt/dev/ogre3d-1.9.0/
Now it's time to build Ogre3D statically (before running the cmake command, validate that your paths are consistent. After that, just build):
..
Here is the explanation for every parameter:
After building Ogre3D's makefiles with CMake, look for the OGRE.xcodeproj file:
:
Go to Product → Scheme → Edit Scheme.. and change the Build Configuration to Release:
Select the install scheme and change the Build Configuration to Release:
Select again the ALL_BUILD scheme:
Running the Ogre3D’s Samples
Now that the building process has finished you can run the Ogre3D’s samples. Open the following file in Finder:
/opt/dev/ogre3d-1.9.0/build/bin/Release/SampleBrowser.app
You should be able to see the sample browser application called SampleBrowser.app. Additionally, you can see the sample browser’s log file in the following path:
/Users/YOURUSERNAME/Library/Application Support/Ogre/Xalafu/ogre.log:
Select the Add button (on the upper-right side). A sub-dialog will be shown, fill the Kits name information:
Creating a Project (that will use CMake)
From the File menu select the option New File or Project…. You will see a dialog like this:
Select the option Non-Qt Project from the Projects list and subsequently select the Plain C++ Project (CMake Build) option. Afterwards click the Choose… button (located at the bottom-right side of the dialog). Afterwards set the project’s name and location:
The information used for this tutorial in the previous dialog (the folder ogreprojects was created beforehand):
Name: tutorial1 Create in: /opt/dev/ogreprojects
Then click the Continue button. In the following dialog select a version control if you are going to use one. This tutorial won't use any:
Then click the Done button. You now need to define the Build Location folder in the following dialog:
/opt/dev/ogreprojects/tutorial1/build
Click the Continue button. In the following dialog you will run the project’s cmake configuration file. Click the Run CMake button and you should see something like:
project(tutorial1) cmake_minimum_required(VERSION 2.8) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST})
main.cpp:
#include <iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; }
Before changing anything in those files, let's reorganize the project files:
/
Now, after performing some changes in the CMakeLists.txt file, this is how it looks like:".
Run the CMake command, you should see something like this:
-- /opt/dev/ogreprojects/tutorial1 -- Configuring done -- Generating done -- Build files have been written to: /opt/dev/ogreprojects/tutorial1/build
Build and run your project. You shouldn't get any errors.
Binaries and App Bundles
In the terminal
Do you see the file called tutorial1?, that is the project's executable (or binary). In order to execute it, in the terminal run:
/opt/dev/ogreprojects/tutorial1/build $> ./tutorial1 Hello World:
ADD_EXECUTABLE(${PROJECT_NAME} MACOSX_BUNDLE ${SRCS} ${HDRS})
The only difference is the addition of the MACOSX_BUNDLE flag to the ADD_EXECUTABLE command. Now run the CMake command, then Build and Run. In your build folder you should now see a new file called tutorial1.app:
If you try to run the app bundle just like we run the binary previously, you will get the following error:
/opt/dev/ogreprojects/tutorial1/build $> ./tutorial1.app -bash: ./tutorial1.app/: is a directory
If you want to run the binary from the terminal, you need to treat the app bundle as a directory (in fact it's a directory):
Including Libraries in your Project
Currently this is the status of the main.cpp file:
#include <iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; }
Let's add a Ogre::String in order to print something else:
#include <iostream> using namespace std; int main() { Ogre::String variable = "My first string using Ogre3D"; cout << "Hello World: " << variable << endl; return 0; }
If you try to build the previous code, you will get an error:
/opt/dev/ogreprojects/tutorial1/src/main.cpp:9:5: error: use of undeclared identifier 'Ogre' Ogre::String variable = "My frist string using Ogre3D"; ^ 1 error generated.
This means that the compiler is not able to find the Ogre::String declaration in your code. In order to fix that we need to add the libraries of Ogre3D into the project.
This is the new CMakeLists.txt file: )
Changes:
- The following line was deleted because is no longer necessary:
MESSAGE(STATUS ${PROJECT_SOURCE_DIR}/src)
- )
Now go the main.cpp and add this line after the inclusion of the iostream library :
#include <OgreString.h>
You should have a main.cpp file like this:
#include <iostream> #include <OgreString.h> using namespace std; bool start(); int main() { Ogre::String variable = "My first string using Ogre3D"; cout << "Hello World: " << variable << endl; return 0; }
When you included the previous line (#include ‹OgreString.h›), the QtCreator IDE should be able to find the definition of the Ogre::String. To validate if it's true, the Ogre::string type should be colored in a purple tone:
Now run the CMake command, then Build and Run. Everything should be working fine:
Ok. This first part ends here. In order to create a window and render something in it, continue to the following part: Using Ogre3D 1.9 Statically | https://wiki.ogre3d.org/tiki-index.php?page=Building%20Ogre3D%201.9%20Statically%20in%20Mac%20OS%20X%20%28Yosemite%29&structure=Sandbox%20Structure | CC-MAIN-2021-25 | refinedweb | 990 | 54.93 |
10.2. Convexity¶
Convexity plays a vital role in the design of optimization algorithms. This is largely due to the fact that it is much easier to analyze and test algorithms in this context. In other words, if the algorithm performs poorly even in the convex setting we should not hope to see great results otherwise. Furthermore, even though the optimization problems in deep learning are generally nonconvex, they often exhibit some properties of convex ones near local minima. This can lead to exciting new optimization variants such as Stochastic Weight Averaging by Izmailov et al., 2018. Let’s begin with the basics.
10.2.1. Basics¶
10.2.1.1. Sets¶
Sets are the basis of convexity. Simply put, a set \(X\) in a vector space is convex if for any \(a, b \in X\) the line segment connecting \(a\) and \(b\) is also in \(X\). In mathematical terms this means that for all \(\lambda \in [0,1]\) we have
This sounds a bit abstract. Consider the picture below. The first set isn’t convex since there are line segments that are not contained in it. The other two sets suffer no such problem.
Definitions on their own aren’t particularly useful unless you can do something with them. In this case we can look at unions and intersections. Assume that \(X\) and \(Y\) are convex sets. Then \(X \cap Y\) is also convex. To see this, consider any \(a, b \in X \cap Y\). Since \(X\) and \(Y\) are convex, the line segments connecting \(a\) and \(b\) are contained in both \(X\) and \(Y\). Given that, they also need to be contained in \(X \cap Y\), thus proving our first theorem.
We can strengthen this result with little effort: given convex sets \(X_i\), their intersection \(\cap_{i} X_i\) is convex. To see that the converse is not true, consider two disjoint sets \(X \cap Y = \emptyset\). Now pick \(a \in X\) and \(b \in Y\). The line segment connecting \(a\) and \(b\) needs to contain some part that is neither in \(X\) nor \(Y\), since we assumed that \(X \cap Y = \emptyset\). Hence the line segment isn’t in \(X \cup Y\) either, thus proving that in general unions of convex sets need not be convex.
Typically the problems in deep learning are defined on convex domains. For instance \(\mathbb{R}^d\) is a convex set (after all, the line between any two points in \(\mathbb{R}^d\) remains in \(\mathbb{R}^d\)). In some cases we work with variables of bounded length, such as balls of radius \(r\) as defined by \(\{\mathbf{x} | \mathbf{x} \in \mathbb{R}^d \text{ and } \|\mathbf{x}\|_2 \leq r\}\).
10.2.1.2. Functions¶
Now that we have convex sets we can introduce convex functions \(f\). Given a convex set \(X\) a function defined on it \(f: X \to \mathbb{R}\) is convex if for all \(x, x' \in X\) and for all \(\lambda \in [0,1]\) we have
To illustrate this let’s plot a few functions and check which ones satisfy the requirement. We need to import a few libraries.
%matplotlib inline import d2l from mpl_toolkits import mplot3d import numpy as np
Let’s define a few functions, both convex and nonconvex.
def f(x): return 0.5 * x**2 # convex def g(x): return np.cos(np.pi * x) # nonconvex def h(x): return np.exp(0.5 * x) # convex x, segment = np.arange(-2, 2, 0.01), np.array([-1.5, 1]) d2l.use_svg_display() _, axes = d2l.plt.subplots(1, 3, figsize=(9, 3)) for ax, func in zip(axes, [f, g, h]): d2l.plot([x, segment], [func(x), func(segment)], axes=ax)
As expected, the cosine function is nonconvex, whereas the parabola and the exponential function are. Note that the requirement that \(X\) is necessary for the condition to make sense. Otherwise the outcome of \(f(\lambda x + (1-\lambda) x')\) might not be well defined. Convex functions have a number of desirable properties.
10.2.1.3. Jensen’s Inequality¶
One of the most useful tools is Jensen’s inequality. It amounts to a generalization of the definition of convexity.
In other words, the expectation of a convex function is larger than the convex function of an expectation. To prove the first inequality we repeatedly apply the definition of convexity to one term in the sum at a time. The expectation can be proven by taking the limit over finite segments.
One of the common applications of Jensen’s inequality is with regard to the log-likelihood of partially observed random variables. That is, we use
This follows since \(\int p(y) p(x|y) dy = p(x)\). This is used in variational methods. Here \(y\) is typically the unobserved random variable, \(p(y)\) is the best guess of how it might be distributed and \(p(x)\) is the distribution with \(y\) integrated out. For instance, in clustering \(y\) might be the cluster labels and \(p(x|y)\) is the generative model when applying cluster labels.
10.2.2. Properties¶
10.2.2.1. No Local Minima¶
In particular, convex functions do not have local minima. Let’s assume the contrary and prove it wrong. If \(x \in X\) is a local minimum there exists some neighborhood of \(x\) for which \(f(x)\) is the smallest value. Since \(x\) is only a local minimum there has to be another \(x' \in X\) for which \(f(x') < f(x)\). However, by convexity the function values on the entire line \(\lambda x + (1-\lambda) x'\) have to be less than \(f(x')\) since for \(\lambda \in [0, 1)\)
This contradicts the assumption that \(f(x)\) is a local minimum. For instance, the function \(f(x) = (x+1) (x-1)^2\) has a local minimum for \(x=1\). However, it is not a global minimum.
def f(x): return (x-1)**2 * (x+1) d2l.set_figsize((3.5, 2.5)) d2l.plot([x, segment], [f(x), f(segment)], 'x', 'f(x)')
The fact that convex functions have no local minima is very convenient. It means that if we minimize functions we cannot ‘get stuck’. Note, though, that this doesn’t means that there cannot be more than one global minimum or that there might even exist one. For instance, the function \(f(x) = \mathrm{max}(|x|-1, 0)\) attains its minimum value over the interval \([-1, 1]\). Conversely, the function \(f(x) = \exp(x)\) does not attain a minimum value on \(\mathbb{R}\). For \(x \to -\infty\) it asymptotes to \(0\), however there is no \(x\) for which \(f(x) = 0\).
10.2.2.2. Convex Functions and Sets¶
Convex functions define convex sets as below-sets. They are defined as
Such sets are convex. Let’s prove this quickly. Remember that for any \(x, x' \in S_b\) we need to show that \(\lambda x + (1-\lambda) x' \in S_b\) as long as \(\lambda \in [0,1]\). But this follows directly from the definition of convexity since \(f(\lambda x + (1-\lambda) x') \leq \lambda f(x) + (1-\lambda) f(x') \leq b\).
Have a look at the function \(f(x,y) = 0.5 x^2 + \cos(2 \pi y)\) below. It is clearly nonconvex. The level sets are correspondingly nonconvex. In fact, they’re typically composed of disjoint sets.
x, y = np.mgrid[-1: 1: 101j, -1: 1: 101j] z = x**2 + 0.5 * np.cos(2 * np.pi * y) # Plot the 3D surface d2l.set_figsize((6,4)) ax = d2l.plt.figure().add_subplot(111, projection='3d') ax.plot_wireframe(x, y, z, **{'rstride': 10, 'cstride': 10}) ax.contour(x, y, z, offset=-1) ax.set_zlim(-1, 1.5) # Adjust labels for func in [d2l.plt.xticks, d2l.plt.yticks, ax.set_zticks]: func([-1,0,1])
10.2.2.3. Derivatives and Convexity¶
Whenever the second derivative of a function exists it is very easy to check for convexity. All we need to do is check whether \(\partial_x^2 f(x) \succeq 0\), i.e. whether all of its eigenvalues are nonnegative. For instance, the function \(f(\mathbf{x}) = \frac{1}{2} \|\mathbf{x}\|^2_2\) is convex since \(\partial_{\mathbf{x}}^2 f = \mathbf{1}\), i.e. its derivative is the identity matrix.
The first thing to realize is that we only need to prove this property for one-dimensional functions. After all, in general we can always defing some function \(g(z) = f(\mathbf{x} + z \cdot \mathbf{v})\). This function has the first and second derivatives \(g' = (\partial_{\mathbf{x}} f)^\top \mathbf{v}\) and \(g'' = \mathbf{v}^\top (\partial^2_{\mathbf{x}} f) \mathbf{v}\) respectively. In particular, \(g'' \geq 0\) for all \(\mathbf{v}\) whenever the Hessian of \(f\) is positive semidefinite, i.e. whenever all of its eigenvalues are greater equal than zero. Hence back to the scalar case.
To see that \(f''(x) \geq 0\) for convex functions we use the fact that
Since the second derivative is given by the limit over finite differences it follows that
To see that the converse is true we use the fact that \(f'' \geq 0\) implies that \(f'\) is a monotonically increasing function. Let \(a < x < b\) be three points in \(\mathbb{R}\). We use the mean value theorem to express
By monotonicity \(f'(\beta) \geq f'(\alpha)\), hence
By geometry it follows that \(f(x)\) is below the line connecting \(f(a)\) and \(f(b)\), thus proving convexity. We omit a more formal derivation in favor of a graph below.
def f(x): return 0.5 * x**2 x, axb, ab = np.arange(-2, 2, 0.01), np.array([-1.5, -0.5, 1]), np.array([-1.5, 1]) d2l.set_figsize((3.5, 2.5)) d2l.plot([x, axb, ab], [f(x) for x in [x, axb, ab]], 'x', 'f(x)') d2l.annotate('a', (-1.5, f(-1.5)), (-1.5, 1.5)) d2l.annotate('b', (1, f(1)), (1, 1.5)) d2l.annotate('x', (-0.5, f(-0.5)), (-1.5, f(-0.5)))
10.2.3. Constraints¶
One of the nice properties of convex optimization is that it allows us to handle constraints efficiently. That is, it allows us to solve problems of the form:
Here \(f\) is the objective and the functions \(c_i\) are constraint functions. To see what this does consider the case where \(c_1(\mathbf{x}) = \|\mathbf{x}\|_2 - 1\). In this case the parameters \(\mathbf{x}\) are constrained to the unit ball. If a second constraint is \(c_2(\mathbf{x}) = \mathbf{v}^\top \mathbf{x} + b\), then this corresponds to all \(\mathbf{x}\) lying on a halfspace. Satisfying both constraints simultaneously amounts to selecting a slice of a ball as the constraint set.
10.2.3.1. Lagrange Function¶
In general, solving a constrained optimization problem is difficult. One way of addressing it stems from physics with a rather simple intuition. Imagine a ball inside a box. The ball will roll to the place that is lowest and the forces of gravity will be balanced out with the forces that the sides of the box can impose on the ball. In short, the gradient of the objective function (i.e. gravity) will be offset by the gradient of the constraint function (need to remain inside the box by virtue of the walls ‘pushing back’). Note that any constraint that is not active (i.e. the ball doesn’t touch the wall) will not be able to exert any force on the ball.
Skipping over the derivation of the Lagrange function \(L\) (see e.g. the book by Boyd and Vandenberghe, 2004 for details) the above reasoning can be expressed via the following saddlepoint optimization problem:
Here the variables \(\alpha_i\) are the so-called Lagrange Multipliers that ensure that a constraint is properly enforced. They are chosen just large enough to ensure that \(c_i(\mathbf{x}) \leq 0\) for all \(i\). For instance, for any \(\mathbf{x}\) for which \(c_i(\mathbf{x}) < 0\) naturally, we’d end up picking \(\alpha_i = 0\). Moreover, this is a saddlepoint optimization problem where one wants to maximize \(L\) with respect to \(\alpha\) and simultaneously minimize it with respect to \(\mathbf{x}\). There is a rich body of literature explaining how to arrive at the function \(L(\mathbf{x}, \alpha)\). For our purposes it is sufficient to know that the saddlepoint of \(L\) is where the original constrained optimization problem is solved optimally.
10.2.3.2. Penalties¶
One way of satisfying constrained optimization problems at least approximately is to adapt the Lagrange function \(L\). Rather than satisfying \(c_i(\mathbf{x}) \leq 0\) we simply add \(\alpha_i c_i(\mathbf{x})\) to the objective function \(f(x)\). This ensures that the constraints won’t be violated too badly.
In fact, we’ve been using this trick all along. Consider weight decay in Section 4.5. In it we add \(\frac{\lambda}{2} \|\mathbf{w}\|^2\) to the objective function to ensure that \(\mathbf{w}\) doesn’t grow too large. Using the constrained optimization point of view we can see that this will ensure that \(\|\mathbf{w}\|^2 - r^2 \leq 0\) for some radius \(r\). Adjusting the value of \(\lambda\) allows us to vary the size of \(\mathbf{w}\).
In general, adding penalties is a good way of ensuring approximate constraint satisfaction. In practice this turns out to be much more robust than exact satisfaction. Furthermore, for nonconvex problems many of the properties that make the exact approach so appealing in the convex case (e.g. optimality) no longer hold.
10.2.3.3. Projections¶
An alternative strategy for satisfying constraints are projections. Again, we encountered them before, e.g. when dealing with gradient clipping in Section 8.5. There we ensured that a gradient has length bounded by \(c\) via
This turns out to be a projection of \(g\) onto the ball of radius \(c\). More generally, a projection on a (convex) set \(X\) is defined as
It is thus the closest point in \(X\) to \(\mathbf{x}\). This sounds a bit abstract. The figure below explains it somewhat more clearly. In it we have two convex sets, a circle and a diamond. Points inside the set (yellow) remain unchanged. Points outside the set (black) are mapped to the closest point inside the set (red). While for \(\ell_2\) balls this leaves the direction unchanged, this need not be the case in general, as can be seen in the case of the diamond.
One of the uses for convex projections is to compute sparse weight vectors. In this case we project \(\mathbf{w}\) onto an \(\ell_1\) ball (the latter is a generalized version of the diamond in the picture above).
10.2.4. Summary¶
In the context of deep learning the main purpose of convex functions is to motivate optimization algorithms and help us understand them in detail. In the following we will see how gradient descent and stochastic gradient descent can be derived accordingly.
Intersections of convex sets are convex. Unions are not.
The expectation of a convex function is larger than the convex function of an expectation (Jensen’s inequality).
A twice-differentiable function is convex if and only if its second derivative has only nonnegative eigenvalues throughout.
Convex constraints can be added via the Lagrange function. In practice simply add them with a penalty to the objective function.
Projections map to points in the (convex) set closest to the original point.
10.2.5. Exercises¶
Assume that we want to verify convexity of a set by drawing all lines between points within the set and checking whether the lines are contained.
Prove that it is sufficient to check only the points on the boundary.
Prove that it is sufficient to check only the vertices of the set.
Denote by \(B_p[r] := \{\mathbf{x} | \mathbf{x} \in \mathbb{R}^d \text{ and } \|\mathbf{x}\|_p \leq r\}\) the ball of radius \(r\) using the \(p\)-norm. Prove that \(B_p[r]\) is convex for all \(p \geq 1\).
Given convex functions \(f\) and \(g\) show that \(\mathrm{max}(f,g)\) is convex, too. Prove that \(\mathrm{min}(f,g)\) is not convex.
Prove that the normalization of the softmax function is convex. More specifically prove the convexity of \(f(x) = \log \sum_i \exp(x_i)\).
Prove that linear subspaces are convex sets, i.e. \(X = \{\mathbf{x} | \mathbf{W} \mathbf{x} = \mathbf{b}\}\).
Prove that in the case of linear subspaces with \(\mathbf{b} = 0\) the projection \(\mathrm{Proj}_X\) can be written as \(\mathbf{M} \mathbf{x}\) for some matrix \(\mathbf{M}\).
Show that for convex twice differentiable functions \(f\) we can write \(f(x + \epsilon) = f(x) + \epsilon f'(x) + \frac{1}{2} \epsilon^2 f''(x + \xi)\) for some \(\xi \in [0, \epsilon]\).
Given a vector \(\mathbf{w} \in \mathbb{R}^d\) with \(\|\mathbf{w}\|_1 > 1\) compute the projection on the \(\ell_1\) unit ball.
As intermediate step write out the penalized objective \(\|\mathbf{w} - \mathbf{w}'\|_2^2 + \lambda \|\mathbf{w}'\|_1\) and compute the solution for a given \(\lambda > 0\).
Can you find the ‘right’ value of \(\lambda\) without a lot of trial and error?
Given a convex set \(X\) and two vectors \(\mathbf{x}\) and \(\mathbf{y}\) prove that projections never increase distances, i.e. \(\|\mathbf{x} - \mathbf{y}\| \geq \|\mathrm{Proj}_X(\mathbf{x}) - \mathrm{Proj}_X(\mathbf{y})\|\). | http://classic.d2l.ai/chapter_optimization/convexity.html | CC-MAIN-2020-16 | refinedweb | 2,892 | 65.83 |
AzeoTech® DAQFactory® Serial / Ethernet Communications Guide DAQFactory Serial / Ethernet Communications Guide DAQFactory for Windows, Version 5.34, July 18th, 2006. Copyright © 2001-2006 AzeoTech, Inc. All rights reserved worldwide. Documentation Version 1.00. Information in this document is subject to change without notice. AzeoTech is a registered trademark of AzeoTech, Inc. DAQFactory is a registered trademark of AzeoTech, Inc. Other brand and product names are trademarks of their respective holders. Copyright © 2001-2006 AzeoTech, Inc. All rights reserved worldwide. No portion of this manual may be copied, modified, translated, or reduced into machine-readable form without the prior written consent of AzeoTech, Inc. Overview DAQFactory can communicate with a wide variety of devices with serial (RS232/422/485) and Ethernet connections. This guide explains how to start communicating with your device and how to create a protocol to interpret the language your device speaks. Since serial and Ethernet communications are done almost identically, we’ll simply refer to it as serial communications. Ethernet is actually a serial technique, meaning bits of data are sent over the wire one after another. There are additional layers with Ethernet handled by your operating system and your hardware, but as far as DAQFactory is concerned, Ethernet, RS232, RS-422 and RS-485 are pretty much identical. This allows you to apply any protocol to either serial or Ethernet ports. DAQFactory handles serial communications by splitting the transport layer: RS232, RS-422, RS-485, Ethernet, etc, from the protocol used on that layer: Modbus, DF1, NMEA. In less technical speak you can think of the transport layer as a telephone. There are many different types of telephones: ones that plug into a wall, cordless phones, cellular phones, and even VOIP. We then communicate on the phone. The protocol is the language that we speak: English, Swahili, Klingon, modem speak. By splitting the telephone from the language, we can use any language on any phone type. DAQFactory provides all the tools for communicate over the various phone types. DAQFactory provides several different languages to communicate with common devices, but also provides the tools for you to specify your own special languages. In order for you to communicate with your device, you have to select and configure the proper telephone type, and you have to speak the proper language over the phone. This guide assumes you have a basic knowledge of DAQFactory and have at least progressed through the guided tour in the user’s guide. If you are going to create your own protocol, we suggest reviewing the section on sequence scripting in the user’s guide as well. We assume a basic knowledge of DAQFactory scripting in our discussion of user protocols. This guide applies to DAQFactory 5.34 or newer. USB: It should be noted now, though, that USB devices, even though the S stands for Serial, are not handled by Windows the same way as Ethernet or normal RS232 serial communications. USB devices require very specialized software to allow for plug and play. The manufacturer of your USB device should provide you with a driver to help you communicate with the USB device. For some devices, such as mice and flash drives, this driver is included with Windows. For others, the manufacturer will provide a driver which will make your USB device appear like a Window’s resource. The most common examples of this are serial to USB converters. These devices include a driver which makes the USB device appear like a standard Windows serial RS232 comm port. Since it appears as a comm port, you should ignore the USB device and just pretend you have an extra comm port on your PC. For even more specialized devices, such as USB DAQ devices, the manufacturer should provide a DLL with functions you can call to communicate with the device. To use these devices in DAQFactory, you should use extern() function and perhaps create a user device. Bottom line: if you are trying to communicate with a USB device, and not a serial to USB converter (or device that appears as a serial port) you are reading the wrong guide. One more note about serial to USB converters. We have had several reports of problems from customers using multiple serial to USB converters on a single PC. There appears to be a backlog of some sort in the driver software that is included with these devices. Most of the cheap devices have the same chip internally and therefore use the same software driver even though they come from different manufacturers. If you are using only one converter you are probably OK, but if you are going to communicate on multiple ports, we strongly recommend purchasing a converter designed for industrial applications such as the ones from Sealevel Systems (). Getting Started Enough of the fine print on USB devices. Let’s start communicating with your device. The first step when trying to setup a new serial device in DAQFactory is to initialize and test the communications. To do this, we’ll create a new communications port and use the DAQFactory monitor window to talk to it. 1) Start DAQFactory, or go File-New if you have already started DAQFactory. 2) Select Quick – Device Configuration from the DAQFactory main menu, then select New Serial / Ethernet Device. This will open up the serial device configuration window. For now we’ll ignore most of it since we just want to talk to our device a little. 3) Click on either New Serial or New Ethernet depending on how you device connects to your PC. New Serial: 4) If you are doing a serial (RS-232, RS-422 or RS-485) connection: in the window that appears, give your comm port a name, then specify the comm port number and its parameters. This information is usually available from your device’s manual. The default timeout value of 1000 is fine. Most likely flow control will be off. New Ethernet: 5) If you are doing an Ethernet connection: in the window that appears, give your connection a name, then enter the IP address of the device. You will need to configure your device with a valid IP on your subnet. The device manual should explain how to do this. If you don’t know what a valid IP is, or for that matter what subnet means, you should ask an IT person or get help from the device manufacturer. There is also an Ethernet Primer at the end of this guide. Next, you will need to enter the IP port. Ethernet is really a big bundle of different communication lines. Each one is assigned a port number. Certain ports have standard uses. For example, port 80 is typically used by the web for HTTP requests. ModbusTCP is typically on port 502. Once again, you will need to check with your device for the proper Ethernet port. If you don’t enter the correct port, you will not be able to communicate with your device. Finally, a timeout of 1000 is more then adequate for most cases. The Monitor Window 6) Once you have created your new port, click on the port in the port list so there is a check next to it, and then click the monitor button. This will display the DAQFactory serial monitor window. This window allows you to view the data being transmitted and received on the serial line. It also allows you to manually transmit data. This window is unique in several ways. First, it is what is called a modeless window. This means you can keep the window displayed and manipulate other parts of DAQFactory. In order to do much of that, though, you will need to move the window to the side and close the serial configuration window hiding underneath. Second, the monitor window displays binary data, or data that can’t normally be seen (like carriage returns, line feeds, tabs, etc) as three digit ASCII codes preceded by a backslash. At this point we go in three directions depending on your device. Streamed data: If your device is a scale, or GPS or similar device that simply streams data out without prompting (like a politician giving their opinion), then you should see data appearing in the window immediately. If you don’t then chances are either your device is not transmitting, or you have the communications parameters incorrect and you should go back and check them. Just remember you can leave the monitor window open while you tweak the settings. Polled data with simple protocol: If your device is of the more common sort that requires a little prodding, you will need to send it a command using the manual output. Refer to your device’s documentation and find a simple command you can send it. Enter that command in the output box at the top and hit Send. If you need to enter control or binary characters, put a backslash and the three digit code. For example, if you needed to send it “Give me data” and a carriage return, you would put: Give me data\013 13 is the ASCII code for carriage return, so \013 sends a carriage return at the end. Other common codes are \010 for a line feed (LF), and \009 for tab. If you have no idea what to send, start with a carriage return: \013. No matter what you send, you should see what your output appear in the monitor error preceded by “Tx:”, and hopefully your device’s response. If you don’t see what you outputted and the Tx, then the connection failed. With serial RS232/422/485 comm ports, this usually means another piece of software is using the port or you specified a non-existant port and you probably got an alert already indicating this. With Ethernet, this means a connection could not be established, which means either the IP address was wrong, or inaccessible, or the IP port was incorrect. Or you just forgot to turn the device on. Either way, you should keep the monitor window open and tweak your settings until you get it transmitting. If you get Tx: and your output string but no response, then things are a little better off. First, check your command and make sure you have it properly formatted. Many devices don’t respond to invalid commands. Second, the communications settings could still be off. With serial, this typically occurs when you have the wrong baud or other setting. With Ethernet, it could be that you are simply communicating with the wrong device because you put the wrong IP, or your device has multiple Ethernet ports (some Ethernet encapsulation devices have this), and you connected to the wrong one. Or, perhaps while you weren’t looking your cat ate the cable. Again, leave the monitor window open, tweak your settings, check your cable, and check the device’s manual. Until you get a response, there is no point in moving forward with the rest of this guide. Polled data with a complex protocol: If your device uses a complex protocol, such as Modbus, you probably don’t know off hand what a proper message is. If you do, perhaps you’d like a job with AzeoTech? If not, fortunately we do work for AzeoTech and so here are a couple example commands that might work. You could also simply jump ahead to the section on prebuilt protocols, leaving the monitor window open. ModbusRTU: assuming your device is at Modbus ID 1, to read the first holding register do: \001\003\000\000\000\001\132\010 ModbusTCP: you can actually send 6 characters and the device will likely echo it back. But here is the same command as the above example for RTU using ModbusTCP: \000\000\000\000\000\006\001\003\000\000\000\001 Allen Bradley: assuming your device has an ID of 1 in CRC mode, to read N7:0 do: \016\002\001\000\015\000\042\000\162\002\007\137\000\000\016\003\136\065 Mitsubishi FX serial: to read T0, do: \0020080002\0035D Mitsubishi uses a combined binary ASCII protocol, thus the combination of control codes (\002 and \003) and ASCII characters. For other devices or if you’d prefer to skip entering manual commands, you should jump ahead to the section on prebuilt protocols, leaving the monitor window open so you can see when the communications starts working. If DAQFactory doesn’t have a prebuilt protocol for your device, you probably should study the device’s instructions and manually calculate out a proper string. Usually the CRC calc is the hard part, and you can always write a short sequence script to do this. At this point you should either be getting some sort of data from your device, or you have a device with a complex protocol that you don’t know off the top of your head, so you need to jump forward. If not, you really should go back to the last few steps above and get things working. Like above, there are three different courses of action next depending on your device: 1) your device uses a protocol with an existing protocol driver included with DAQFactory (for example the many flavors of Modbus) 2) your device uses a unique poll – response protocol. This means you have to send the device a command, at which point it responds with some data 3) your device streams data to you unprovoked. You only need to interpret the incoming data and probably never have to output anything. Did we say three? We meant four: you have #2 and #3 combined. Some protocols allow you to send a command that causes the device to switch to streaming data continuously. Another command typically stops the streaming. In this case, you’ll need to read twice as much as everyone else to learn to do both. Don’t worry, its not that bad. Using an existing protocol: DAQFactory comes with an ever expanding list of protocol drivers that you can use immediately. To use one of these drivers you should create a new serial / Ethernet device as described above. You can either go all the way through the procedure described above, or once you create your serial or Ethernet port, you can simply select the desired protocol from the list, give your device a name, and close the window. Once you do this, a new device will be available in the channel table that will communicate on the port you specified using the protocol you specified. In the channel table, you will see different I/O types available depending on the protocol. You will also find different device functions available depending on the protocol selected. At this point you should read the section in the help on the desired protocol as it will describe what each I/O type and function mean, as well as the proper addressing of your device. Creating a Poll / Response protocol If an existing protocol is not available, you can create your own using DAQFactory scripting. For most protocols this is a pretty simple task. To do so,. In a poll / response protocol, DAQFactory will send a command to your device (polling it) and your device will send some data or an acknowledgment back (the response). Fortunately, DAQFactory provides just the function for doing this sort of thing. When you first create your protocol, DAQFactory will automatically create several functions. Four of them are events and start with “On” and we’ll talk about them later as they are only for advanced protocols. The last is called “Poll”. Not only is the function created, but DAQFactory even writes the function for you. You can click on Poll in the function list and see the code. This was done to allow advanced users to tweak their polling, or to use this script as a template for more advanced serial protocols. For now, we’ll just use the function as is. As an example, let’s say when your device gets the letter D followed by a carriage return, it will respond with a data value and a carriage return. So, we need to send the command D + carriage return, and then listen for the response. To make the protocol easy to use, we also want this to be an I/O type so we can assign it to a channel. To create a new I/O type for this protocol, click on the Add I/O Type button. A new window will appear: Give your I/O type a name (say GetData) and leave the rest in their default settings and hit OK. This adds the new I/O type to the protocol and gives a blank box for entering code for this I/O Type. With the Poll function DAQFactory already created for you, this is really easy and requires only one line of code: return(StrToDouble(Poll("D"+chr(13),13))) Starting from the inside we have “D” + chr(13). This is simply a string containing D plus a carriage return (ASCII code 13). The chr() function simply takes an ASCII code number and creates the corresponding character. The Poll() function takes the string to output as its first parameter. The second parameter, 13, is the end of line character for the reply from your device. The Poll() function will return the entire string received up to this end of line character. So, moving out, we take this string and send it to the StrToDouble() function which converts our string into a number. So if the reply was “3248”, it would convert it to the number 3248. In almost every case you’ll need to convert the string reply from your device into a number. Finally, we return that number from our I/O type function. This will put it in the channel. To use this I/O type we have to apply the protocol GetData in the I/O type column. The D# and Channel number are not used in the code we wrote. If you select a timing of 1 and hit apply, DAQFactory will start sending out D and carriage return every second waiting for a reply. If you open the monitor on the comm port you will see this. That is the simplest of polling routines, and in many cases this is all you need. If you had different commands to get different values, you would simply create more I/O types and send a different command to the Poll function. Getting a little more advanced, we’ll assume that your device has multiple channels. Let’s say the command is still “D”, but with the channel number after. For example, D5 plus carriage return would return the data from channel 5 on your device. Ideally we want to use a single I/O type function and use the channel number specified in the channel table. Fortunately, DAQFactory passes several private variables to your I/O type function that describe the channel. This includes the device number, channel number and more. For now, we’ll just use the channel number. Fortunately, the code isn’t that much more complicated. To make it easier to read, though, we’ll split it into a couple lines: private string dataout = "D" + DoubleToStr(Channel) + Chr(13) return(StrToDouble(Poll(dataout,13))) The first line creates the output string. Its just like before, but we put the channel in the middle. The Channel variable is a number, so we need to convert it to a string too using the DoubleToStr() function. Then, we simply call the Poll() function again, and return the result converted to a number. That’s it! Now you can create multiple channels with the same I/O type and different channel numbers and different commands will be sent to your device. So far, we’ve assumed your device simply returns a number and a carriage return. Most devices return extra stuff we don’t want. Often times this is simply the command echoed back. Lets say our device returns “D” plus the value and a carriage return. In this case we can’t just convert the result of the Poll() function to a number because D doesn’t convert to any number in decimal. So we have to change the code a little. Keeping it readable by splitting it into separate lines, it would look like this: private string dataout = "D" + DoubleToStr(Channel) + Chr(13) private string datain = Poll(dataout,13) return(StrToDouble(Mid(datain,1,10))) Now lets get even more complicated and assume your device returns more than one value with a single request. In this case, we’ll use a single channel to trigger the read and then push the data into multiple channels. As an example, lets say your device is polled with our original “D” plus carriage return, and it returns a comma delimited list of 3 values followed by a carriage return. We’ll use channel # 0 of our I/O type to trigger the read, and then put the data in channels 0,1 and 2: if (Channel != 0) return(NULL) endif private string datain = Poll("D"+Chr(13),13) Channel.AddValue(strDevice,0,"GetData",1,StrToDouble(Parse(datain,1,","))) Channel.AddValue(strDevice,0,"GetData",2,StrToDouble(Parse(datain,2,","))) return(StrToDouble(Parse(datain,0,”,”))) The first three lines ensure that we trigger the read from channel 0 only. This is so we don’t have to worry about setting the Timing of channels 1 and 2 to 0. Note that by returning NULL, we keep DAQFactory from adding a value to the channel. The next line we do our standard Poll(). The following two lines stuff the second and third values into channels 1 and 2. The Channel.AddValue() function allows you to put data into a channel that you don’t know the name off. It takes 5 parameters. The first 4 describe the channel (device type, device number, I/O type, and channel number), the last contains the value to put in the channel. strDevice is a local variable that contains the name of the device the user created when using this protocol. You have to use strDevice because you don’t know what a user might name their device. We then specified a D# of 0. This means our channels will have to have a D# of 0, where previously it did not matter. Next is a string with the name of our I/O Type. Finally we have the channel number and the value to put in the channel. To retrieve the proper value, we use the Parse() function. This function takes a string, the index into the string, and the character used to delimit the string. In this case, the data is a comma delimited string, and we want the second value (index 1 since its numbered from 0) for channel 1, and the third value for channel 2. Finally we return the first value in the list to put it in channel 0. That covers the primary types of poll / response protocols. Adapting to your device is simply a matter of creating the correct output string and parsing the input. Some protocols require more advanced functionality and that, along with the details of how the Poll() function works is described at the end of this guide. Binary and fixed field protocols: But first, we should talk a little more about binary protocols. The protocols so far have been primarily ASCII protocols. The only binary information is the carriage return that marks the end of the line of data. What if, instead of “D3” + chr(13) to read the 3rd channel with an ASCII string response, we had to send the binary value 15 to trigger a read, and a word representation of the channel, for a total of 3 bytes, and then read a 5 byte response, the command byte (15) plus a 4 digit double word representation of the number? Well, we’d have to do a few things differently. We’d still construct our query as a string, but we’d use some different functions: private string dataout = chr(15) + chra(From.Word(Channel)) This looks similar to our previous example when we did “D” plus the channel number in ASCII string form, except this time we use the From.Word() function. The From. functions are a series of functions that convert numbers into their byte representation. There are 16 different functions for the various ways a number can be represented. In this case, we want the word with default LSB first representation. The From functions return an array of numbers, so to convert it into a string, we use the chra() function. This is just like the chr() function, except it takes an array of values and returns a single string made up of the characters in the array. If you did just chr() with an array of values, it would return an array of strings. It is important to understand that just because dataout is a string, it doesn't mean it can't be a bunch of unreadable binary codes. The string simply provides a simple way to manipulate these codes. We could do the same thing by creating an array of all our values, but would have to convert the array to a string to call any of the communication functions. As it happens, it is sometimes more useful to do this. It is entirely up to you. Moving on, the protocol in our example is different from the previous examples not only because it is entirely binary, but because it is has a fixed length response and doesn't have an end of line character. The Poll function is written to read to an end of line character. So, to read a fixed number of characters, we'll need to modify the Poll function slightly. Fortunately, all we need to do is change one line. If you click on the Poll function in the protocol editor you will see all the code for the Poll function. Skipping the details of the code, which is discussed later, change the one line that says: in = ReadUntil(until) to in = Read(until) The Read() function takes a single parameter which is the number of characters to read, so now our Poll() function's second parameter is the number of characters to read instead of the end of line character. So, the next line of our I/O type would be: private string datain = Poll(dataout,5) The 5 is the number of characters to read. Now all we need to do is parse the data: return(To.Long(AscA(Mid(datain,1,4))) There are a bunch of functions here, so starting from the inside: Mid(datain,1,4) returns the 2nd through 5th characters, thus skipping the first code which should be 15, our command code echoed back to us. AscA(...) converts those 4 characters into an array of 4 numbers. This is the exact opposite of ChrA(). Actually, if you did ChrA(AscA("abc")) you'd get the string "abc". To.Long(...) converts an array of bytes to a single long value, which we then return. The To. functions are the opposite of the From. functions. From. functions convert a from a number to bytes, while the To. functions convert to a number from bytes. Binary protocols aren't much more complicated than ASCII protocols as long as you remember that a string is just a series of numbers, each between 0 and 255. Fixed field length protocols are equally easy, though you need to make a small modification to the Poll function, but that's why we coded it in DAQFactory script. Creating a Protocol to Accept non-polled Data While the majority of devices use the poll / response method, there are still a fair number of common devices that simply stream their data without prompting. Some common examples of this are GPS devices (and most anything that uses the NMEA protocol), and scales. For these types of devices we use the OnReceive event of an user protocol to capture and parse data as it comes in. To create an user protocol,. Let’s jump right in with an example. Let’s say you have a scale that simply outputs the weight every second as a number followed by a carriage return. To parse this data and put it in a channel we would add the following code to the OnReceive event of your protocol: if (strIn == Chr(13)) private string datain = ReadUntil(13) Channel.AddValue(strDevice, 0, "Input", 0, StrToDouble(DataIn)) Endif The OnReceive event is called every time a character is received on the port. The character received is passed to the event in the strIn variable. In the first line above, we look to see if the last character received is a carriage return. The chr() function simply creates a string with the given ASCII character, in this case ASCII code 13 which is carriage return. If the character received is not a carriage return, we don’t do anything. If it is, we use the ReadUntil() function to read all the characters accumulated so far up until the carriage return. Then we parse the data and put it into a channel using the Channel.AddValue() function. We parse the data with the StrToDouble() function. This function simply takes the string response and converts it to a number. The AddValue() function takes 4 parameters that describe the channel to put the data into (the device type, device number, I/O type, and channel number), and the data point. The strDevice variable contains the name of the device the user created using your protocol. This is not known ahead of time, so you have to use this variable. A device and channel number of 0 was chosen arbitrarily. The I/O type of Input was also chosen arbitrarily. In order for the user to be able to create a channel with this I/O type though, we need to add this I/O type to our protocol. To do this, we simply click the Add I/O type button and enter Input for the name. The rest can be left in its defaults. We don’t have to put any code in this I/O type. We just need it to exist so the user can create a channel. To use this protocol we have to apply the it Input in the I/O type column. The D# and Channel number have to be 0 because of how we coded the AddValue() function above. You should select a timing of 0 since there is no polling in this protocol. If data were received in the proper format, data would automatically appear in your channel when you hit Apply. Multiple points on a single line: Often the device streams multiple data points in a single line. For example, your device might output two values separated by a comma and followed by a carriage return. The code is almost the same: if (strIn == Chr(13)) private string datain = ReadUntil(13) Channel.AddValue(strDevice, 0,"Input",0, StrToDouble(Parse(DataIn,0,","))) Channel.AddValue(strDevice, 0,"Input",1, StrToDouble(Parse(DataIn,1,","))) Endif All we added was the Parse() function to split the data apart and then two calls to AddValue to put the data into channels 0 and 1. The Parse command takes 3 parameters, the string to parse, the index you want to retrieve and the delimiter. Varying data types: A slightly more advanced streaming protocol is the NMEA standard often used in devices like GPS. In this case different lines of data are received with different meanings. The meaning of a particular line is determined by the first 6 characters. To parse this, we simply look at these first six characters and put the data in different places depending on this header’s value. You can delineate different places using either different I/O types or different device numbers. For example: if (strIn == chr(10)) // now read until the LF private string datain = ReadUntil(10) // split out header private string head = Left(datain,6) // now examine each line type differently. switch case (head == "$GPRMC") Channel.AddValue(strDevice, 0, "RMC", Channel.AddValue(strDevice, 0, "RMC", case (head == "$GPGSA") Channel.AddValue(strDevice, 0, "GSA", Channel.AddValue(strDevice, 0, "GSA", endswitch endif 0, Parse(datain,1, ",") 1, Parse(datain,2, ",") 0, Parse(datain,1, ",") 1, Parse(datain,2, ",") If your data is binary, you may want to review the section on Binary Protocols at the end of the section on Poll / Response protocols to learn about the To and From series of functions. Poll / Response and streaming data: Some devices perform both poll / response type commands and streaming data. Typically they start in poll / response mode and a particular command will start it streaming. The streaming continues until another command is sent to the device. Handling these types of devices is almost entirely a matter of combining the concepts described above. The exception is that you have to use a flag to keep the OnReceive event from parsing data when the device isn’t streaming. To do this you will first need to create the variable for the flag. For this you can use a local variable. A local variable is similar to a private variable, but it is viewable by any code in the protocol. It is not viewable outside the protocol. Typically you will want to declare your local variables in the OnLoad event. Something like this: local streamflag = 0 Then, in the OnReceive event, you would enclose your stream parsing code with a simple if: if (streamflag) … parse data, we’re streaming endif Of course you’ll need to set and clear the streamflag from somewhere. This can be done in the code that sends the stream start and stop commands to the device. Advanced Communications The Poll() function in detail: Here is the script for the poll function with line numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 function Poll(string out, until) // this function will poll the port with given string and read // the response until the given character. Returns NULL (empty) // if there is an error if (argc < 2) throw("Invalid number of parameters") endif private string in try // lock the port if (!LockPort()) throw("Unable to lock port") endif // clear anything pending Purge() // output our string Write(out) // and read until the eol: in = ReadUntil(until) // release the port UnlockPort() // and return the response return(in) catch() // error occured UnlockPort() throw() endcatch // return NULL to indicate error. This should never happen // because of the throw() statement above return(NULL) The first line is a standard function declaration. Its not required, but it allows us to quickly name the two parameters of this function, out and until. Lines 5 through 7 ensure that there were actually two parameters passed in. Argc is a private variable set in all functions that contains the number of parameters passed. If there are less then two passed in, we throw an error. Next we have to lock the port in line 11. Locking the port prevents another sequence or thread from trying to communicate over the port while we are in the middle of a poll / response cycle. If we didn’t lock the port, we could have a case where we send the device a command, and another thread sends another command before we get a response. If this happened the response may not match our request. The LockPort() function doesn’t always succeed. If the port is being over used, the port may not come available within the timeout specified in the port. In this case, LockPort() returns 0 and we throw an error. We can’t do anything else, otherwise we’d defeat the purpose of locking the port in the first place. In line 15 we purge the port. This clears out any extraneous data on the port and is usually a good idea just to be sure nothing is left over from a previous request. Once purged, we can write the string out in line 17. We can then immediately read the data back in line 19. The readuntil() function reads from the port until the given character is received or the timeout occurs. If the timeout does occur, an error is thrown. Otherwise, the characters are returned and placed in the variable. Once we have a response, we can unlock the port in line 21 and return the string received in line 23. If we don’t unlock the port after locking it, no other sequences or threads will be able to communicate on the port. For this reason, immediately after locking the port, we enclose all the code up to the UnlockPort() in a try/catch block (lines 9 to 24). If an error is thrown inside this block, DAQFactory will skip to line 26 where it unlocks the port. We then rethrow the error in line 27 so the user knows something happened. This format ensures that the port is properly unlocked. As stated in the comments in the code, line 31 is not really necessary as it is impossible to reach, but we placed it there anyway just in case the logic changed in the rest of the script. This ensures that something is actually returned from the function, even if its nothing. Ethernet Primer Since an IT person may not be available, here is a quick explanation of Ethernet communications and IP addressing and a few pointers at the end. Ethernet communications can be complicated, especially in large corporations. If you do not feel comfortable with this, you should contact an IT person. Assigning an incorrect IP address may bump another individual off the network and is not a good way to make friends. Ethernet communications, as explained previously, is a serial communications method, meaning bits of data are sent one after another and assembled to create bytes of data. A bit is simply a one or a zero. A byte is a collection of 8 bits that describe a number between 0 and 255. Often, a byte is used to describe a character, a letter, number, symbol or code. So, for example, a capital A is typically coded as 65. This code is called the ASCII code and you can see the standard characters by searching for ASCII on the internet. Note that only the numbers from 0 to 127 have standard meanings. The numbers above 127 are used for a wide variety of things, often to generate non-english characters. But we deviate from Ethernet… Ethernet is actually made of multiple layers. The details of what these layers are is not so important. The important ones are the hardware layer, the IP layer, and the TCP/UDP layer. The hardware layer is the what it seems. Typically this is Ethernet cabling, switches and routers, but could also be fiber optic cable, DSL lines, GPRS, etc. In general, you do not need to worry about the hardware layer, except for proper cabling. Fortunately, there is usually only two different types of cabling: direct and crossover. In most LAN’s you will use exclusively direct cabling. This means that each pin on one side of the cable corresponds to the same pin on the other side of the cable. In a crossover cable, several pairs of pins are swapped. You would use a crossover cable if you wanted to connect your PC directly to your Ethernet device (PLC, DAQ device) without going through a switch, hub, or router. A switch or hub is simply a traffic cop who allows Ethernet traffic to pass through to the appropriate spots. Often switches/hubs are combined with your cable or DSL modem to allow multiple computers to connect to the same internet connection. On top of the hardware layer runs the IP layer. The IP layer handles the addressing, thus the “IP Address”. The IP address is a collection of 4 numbers, each between 0 and 255, separated by periods. These 4 numbers actually define a single big number internally that ranges from 0 to a little over 4 billion, but splitting that number into 4 sections makes it easier for us to read. A URL, such as, is not an IP address. In fact, before your computer can find azeotech.com it has to go to what is called a domain name server (DNS) to find the IP address that corresponds to azeotech.com. Domain name servers are typically provided by your ISP and their sole job is to take a URL and translate it into the IP address. Ethernet cannot use URLs directly. IP addresses are addresses and therefore every computer on the Internet has a unique IP address. On the Internet, these addresses are distributed by a global governing body, and typically provided to you by your ISP. Since IP addresses basically define a number between 0 and about 4 billion, there can only be about 4 billion computers directly connected to the Internet. Fortunately there are things called routers which allow you to connect multiple computers on a LAN (local area network) to a single IP address on the internet. Each computer on the LAN has its own IP address, but in order to communicate with computers on the internet the computer has to connect to the LAN’s router, called a gateway first. In addition to allowing multiple computers to connect to the internet using one global Internet IP address, routers also provide a level of security. Each computer in the LAN has a private IP address. This address typically starts with 10. or 192.168. IP addresses that start with these numbers are called non-routable IP addresses and used exclusively in LAN’s. If your computer has an address starting with one of these numbers then it cannot be accessed from the Internet without using special tools like VPN (virtual private networking) or a virus. Since your computer isn’t visible from the outside, it is somewhat protected by the router. The most common security problem occurs when you get a virus. This virus runs on your computer and announces to the world (or at least the virus author) “Here I am!” and creates a link from the inside, much as you would when you access a web site. Now, how does your computer know when to look for an IP address that is on the LAN, for example, a printer, or local file server, and when to go to the gateway router to access an external computer? This is where the subnet comes in. The subnet tells your computer which computers are directly accessible and which computers are only accessible through the gateway. In general, subnets are specified as 255.255.255.0 or 255.255.0.0 or 255.0.0.0. In the first case, the subnet includes all addresses with the same first three numbers. So, 192.168.1.1 and 192.168.1.2 would be on the same subnet, but 192.168.2.1 would not and in order to access that address, your computer would have to ask the gateway, which would have to somehow have access to that subnet as well, presumably by having a subnet of 255.255.0.0, which includes all addresses with the same first two numbers. There are other combinations that don’t include 255, but this gets much more complicated to figure out and are pretty rare. Typically, in small LAN’s you will have a single subnet, but if you are in a large corporation, you may have multiple subnets for different parts of your company. This allows each part to secure their own network and control their resources. If you are in this situation, you almost certainly have IT people and should talk to them before putting anything on the LAN. Finally, on top of the IP layer there is the TCP/UDP layer. TCP and UDP are two different methods for data transmission. TCP is what is called a guaranteed delivery protocol. This means that if you send a packet over TCP to a device, the Ethernet layers below will keep trying to deliver that packet until it is delivered or a timeout period occurs. If it is not delivered, then the sending computer is notified and can take appropriate action. This is the most common method. UDP is a broadcast protocol. With UDP, the packet is sent without regard to whether it is received or not. UDP is often used to find out what devices are connected to a subnet. So, for example, a piece of software could send a UDP command to every IP address on the local subnet that tells the device to send a response. Then, it can simply wait for responses and find out who is actually connected. As mentioned before, just to complicate things, in addition to the IP address, there are ports on each address. The port is like a communications channel. Each IP address has 65535 ports available. Some of these ports are used for common things. For example, HTTP, the protocol used to get web pages, uses port 80. Most ports are picked arbitrarily by various software packages or hardware devices. You have to have both the correct IP address and port to communicate with a device over Ethernet. One final discussion: static versus dynamic IP addressing. To make the installation of new PC’s easier on the IT people, something called DHCP was invented. DHCP is a protocol used to automatically provide IP addresses to devices. The DHCP retains a list of IP addresses that can be used and when a new computer connects to the LAN, it finds the DHCP server and requests an IP address to use. This address is called a dynamic IP address. It is dynamic because the next time the PC or device is powered up and requests an address from the DHCP server, it may be a different address. A static IP address is specified directly on the PC or device and is fixed. Dynamic IP addresses work because most of the stuff people do on PC’s are client based, meaning they start the communications and connect to a server or other device with a known fixed IP address. If your PC or device has a dynamic IP address, you cannot access it externally because you don’t know its address. It would be like trying to telephone somebody whose telephone number changed every day. Dynamic IPs are also used by ISP’s to stretch the number of users they can have on a group of static IPs. The ISP might own 100 IP addresses and have 200 subscribers. But not all 200 subscribers are on the Internet at the same time, so they rotate IPs among those that are connected. Since much web browsing is a connect, download, and release mechanism, it is pretty easy to rotate IPs even if 200 people are browsing the web at the same time. Now the important points: 1) To connect to an Ethernet device using DAQFactory and TCP, you must know the IP address of the remote device. The IP address also must be accessible from your subnet. So if your device has an IP of 192.168.1.2 and you have an IP of 10.0.0.3 and your subnet is 255.0.0.0, you probably won’t be able to connect to your device. When you first start, you should always try and put your device on the same subnet so you don’t have to worry about routing. 2) You also must know the port number of the TCP/IP connection that your device is listening on. Many devices listen to multiple ports using different protocols, so make sure you get the right port. 3) In order to put a device on the Internet in a way that allows access to that device, the device must have a static, Internet capable, address. This means the address can’t start with 192.168 or 10. You will have to contact your ISP or IT people for a static IP address, and it may cost extra. This is a very insecure method. Alternatively, you can use a technology like VPN to access your LAN and then get access to the local addresses. In this case, your device will still have to have a static IP, but it can be a local address, i.e. one that starts with 192.168 or 10. VPN typically requires a special type of hardware firewall. VPN is much more secure then simply giving your device a static IP on the internet. 4) The only way to connect a PC directly to a device without using a switch, hub or router is to use a crossover cable. In this case, you will need both the device and the PC to have IP addresses on the same subnet. Your best bet is to simply use 192.168.1.2 and 192.168.1.3, but it doesn’t really matter because there are no other computers or devices to interfere with. 5) Some devices require a crossover cable to initially set the IP address. The device may come from the factory with an IP of 192.168.1.1 or similar. You will probably not want to simply plug this device into your LAN. Instead, you should connect directly to the device with a crossover cable and assign your PC an IP address on the same subnet, 192.168.1.2 for example. 6) Be careful when you have multiple Ethernet connections. This is especially common on laptops that have both a wireless and wired connection. Depending on your settings, the two connections may be on completely different subnets which may prevent a connection. 7) An easy way to tell if you have access to a device is to ping it. Not all devices support ping, but most do. To perform a ping, open a command line prompt, which is typically under Start – Programs –Accessories – Command Prompt. Type in something like: ping 192.168.1.1 to ping a particular address. You will probably get one of three responses: A) It will pause and say “Request timed out.”. This means either the IP can’t be found or can’t be accessed, or the device does not support the ping function. B) It will display something like: “address is unaccessible”. This means you are not on the same subnet as the IP specified and either your gateway doesn’t exist, or it doesn’t know how to get to that address either. This can also occur if you are using DHCP on your PC and your PC hasn’t gotten its IP address yet. C) It will display something like: “Reply from 192.168.1.1: bytes=32 time=1ms TTL=63”. This means you can successfully reach the device. Whether or not it is actually the device you want is another question, but chances are, you are successful. Now the trick is determining which port to connect to, and for that you’ll have to review your devices manual. | https://manualzz.com/doc/1278402/mitsubishi-rs232-485-lan-serial-communication-control-use. | CC-MAIN-2018-34 | refinedweb | 8,594 | 62.78 |
Type: Posts; User: JustSomeGuy
I have a hash table that is patient id, patients names
In my data sometimes the patients names are entered in differently but they are the same patient.
A patient might be listed as
or
I have two classes.
1) class dbgBuf : public std::streambuf
2) class dbgFile : public std:: ostream
I first got dbgBuf class working
dbgBuff ob;
This is a simple example of a log file class I'm trying to develop.
Debug.h
#ifndef DEBUG_H
#define DEBUG_H
#include <iostream>
#include <fstream>
The bit bucket.
I just don't get it... This code works in some environments but not in others...
I've attached the source... If anyone has time to look, that would be great.
I'm on MAC OS X, 10.5.7 using XCode...
Could you elaborate please? What is composition?
do you mean:
class dbgFile : public std::ostream {
private:
std::filebuf output_buffer;
needs to change to:
class dbgFile {
dbg is an instance of dbgFile
however the first call to
dbg << "A Message" << std::endl;
causes a segmentation fault.
The debugger shows:
0 std::ostring::_M_write
This constructor is causing the application to crash on Mac OS X, in
xcode...
dbgFile::dbgFile(void) : std::ostream(0), output_buffer(),indent_buffer(&output_buffer), isopen(false) {}
here is...
I want to create a collection of names.
co.add "foo", "Brian"
co.add "bar", "Bob"
However i need to make sure that the same key is not used twice.
I don't know how to catch the error if...
Is sftp the same as ftp over a ssl?
Did I mis-read it... I that that it was only an example of ftp not sftp.
I need to be able to upload a file to a site by sftp.
I found this great example on how to upload via ftp......
I'm trying to traverse a directory and all its sub-directories searching for files like "*.jpg"
In C / C++ I used functions called FindFirst & FindNext.
Can you point me to the C# (Microsoft Visual...
I don't know it looks recursive to me...
I mean findnext does call findfirst doesn't it?
myButton.doModal
Thanks that's a great idea!
De looping that loop was driving me loop de loop.
I have a loop that searches a directory and its sub directories for files.
When if finds a file it goes off and processes it. On top of that it's recursive.
I need to break this loop into to...
I have a project that has a module. There is a public function in that module.
However when I compile the application I get the error message
Sub or function not defined.
Why? It's in the module...
I don't think my form knows about these methods...
I'm looking for a simple example of how to enable drag and drop on my application so that I can drag a folder or some selected files onto my application for processing.
(Right now I select from a...
No.. its just an application without any database..
or system files are out of date.. I don't have the exact error in front of me....
I tried to install and application that was written in VB6.0 on a new XP system.
The setup was created using the...
but... but.. but... Its an 8bit data type.. endianism is irrelevant.
This code is for data communications between systems...
I cannot assume that it will be my code on both ends.
But I just noticed this bug where the low bit has now become the high bit.
Now I'm...
I have a structure...
typedef struct
{
unsigned int item_len;
unsigned char PresentationContextID;
unsigned char unused : 6;
unsigned char last : 1;
unsigned char...
Yes I guess your right..
As none of the properties are pointers to data....
Right? | http://forums.codeguru.com/search.php?s=041c03700bc90331a88a97c765ad8ed3&searchid=6123459 | CC-MAIN-2015-06 | refinedweb | 637 | 77.74 |
C ++ vtables. Part 1 (basics + multiple Inheritance)
Hello! The translation of the article was prepared specifically for students of the course "C ++ Developer". Is it interesting to develop in this direction? Come online December 13 at 20:00 Moscow time. to the master class "Practice using the Google Test Framework"!
In this article, we will look at how clang implements vtables (virtual method tables) and RTTI (runtime type identification). In the first part, we start with the base classes, and then look at multiple and virtual inheritance.
Please note that in this article we have to dig into the binary representation generated for various parts of our code using gdb. This is a pretty low level, but I will do all the hard work for you. I do not think that most of the future posts will describe the details of such a low level.
Disclaimer: everything written here depends on the implementation, may change in any future version, so you should not rely on it. We consider this for educational purposes only.
excellent, then let's get started.
Part 1 – vtables – Basics
Let's look at the following code:
#include using namespace std; class NonVirtualClass { public: void foo () {} }; class VirtualClass { public: virtual void foo () {} }; int main () { cout << "Size of NonVirtualClass:" << sizeof (NonVirtualClass) << endl; cout << "Size of VirtualClass:" << sizeof (VirtualClass) << endl; }
$ # compile and run main.cpp $ clang ++ main.cpp && ./a.out Size of NonVirtualClass: 1 Size of VirtualClass: 8
NonVirtualClass has a size of 1 byte, because in C ++ classes cannot have zero size. However, this is not important now.
The size
Virtualclass is 8 bytes on a 64-bit machine. Why? Because inside there is a hidden pointer pointing to a vtable. vtables are static translation tables created for each virtual class. This article talks about their content and how they are used.
To get a deeper understanding of what vtables look like, let's look at the following code with gdb to find out how memory is allocated:
#include class Parent { public: virtual void Foo () {} virtual void FooNotOverridden () {} }; class Derived: public Parent { public: void Foo () override {} }; int main () { Parent p1, p2; Derived d1, d2; std :: cout << "done" << std :: endl; }
$ # compile our code with debugging symbols and start debugging using gdb $ clang ++ -std = c ++ 14 -stdlib = libc ++ -g main.cpp && gdb ./a.out ... (gdb) # set gdb to automatically de-decorate C ++ characters (gdb) set print asm-demangle on (gdb) set print demangle on (gdb) # set a breakpoint on main (gdb) b main Breakpoint 1 at 0x4009ac: file main.cpp, line 15. (gdb) run Starting program: /home/shmike/cpp/a.out Breakpoint 1, main () at main.cpp: 15 15 Parent p1, p2; (gdb) # go to the next line (gdb) n 16 Derived d1, d2; (gdb) # go to the next line (gdb) n 18 std :: cout << "done" << std :: endl; (gdb) # print p1, p2, d1, d2 - we will talk about what output means soon (gdb) p p1 $ 1 = {_vptr $ Parent = 0x400bb8 } (gdb) p p2 $ 2 = {_vptr $ Parent = 0x400bb8 } (gdb) p d1 $ 3 = { = {_vptr $ Parent = 0x400b50 }, } (gdb) p d2 $ 4 = { = {_vptr $ Parent = 0x400b50 }, }
Here is what we learned from the above:
– Despite the fact that classes do not have data members, there is a hidden pointer to vtable;
– vtable for p1 and p2 is the same. vtables are static data for each type;
– d1 and d2 inherit the vtable-pointer from Parent, which points to vtable Derived;
– All vtables indicate an offset of 16 (0x10) bytes in the vtable. We will also discuss this later.
Let's continue our gdb session to see the contents of vtables. I will use the x command, which displays the memory on the screen. We are going to output 300 bytes in hexadecimal format, starting with 0x400b40. Why exactly this address? Because we saw above that the vtable pointer points to 0x400b50, and the symbol for this address
vtable for Derived + 16 (16 == 0x10).
(gdb) x / 300xb 0x400b40 0x400b40 : 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x400b48 : 0x90 0x0b 0x40 0x00 0x00 0x00 0x00 0x00 0x400b50 : 0x80 0x0a 0x40 0x00 0x00 0x00 0x00 0x00 0x400b58 : 0x90 0x0a 0x40 0x00 0x00 0x00 0x00 0x00 0x400b60 : 0x37 0x44 0x65 0x72 0x69 0x76 0x65 0x64 0x400b68 : 0x00 0x36 0x50 0x61 0x72 0x65 0x6e 0x74 0x400b70 : 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x400b78 : 0x90 0x20 0x60 0x00 0x00 0x00 0x00 0x00 0x400b80 : 0x69 0x0b 0x40 0x00 0x00 0x00 0x00 0x00 0x400b88: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x400b90 : 0x10 0x22 0x60 0x00 0x00 0x00 0x00 0x00 0x400b98 : 0x60 0x0b 0x40 0x00 0x00 0x00 0x00 0x00 0x400ba0 : 0x78 0x0b 0x40 0x00 0x00 0x00 0x00 0x00 0x400ba8 : 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x400bb0 : 0x78 0x0b 0x40 0x00 0x00 0x00 0x00 0x00 0x400bb8 : 0xa0 0x0a 0x40 0x00 0x00 0x00 0x00 0x00 0x400bc0 : 0x90 0x0a 0x40 0x00 0x00 0x00 0x00 0x00 ...
Note: we look at de-decorated (demangled) characters. If you're really interested, _ZTV is the prefix for vtable, _ZTS is the prefix for the type string (name), and _ZTI for typeinfo.
Here is the structure
vtable parent:
Here is the structure
vtable derived:
one:
(gdb) # find out what debugging symbol we have for the address 0x400aa0 (gdb) info symbol 0x400aa0 Parent :: Foo () in section .text of a.out
2:
(gdb) info symbol 0x400a90 Parent :: FooNotOverridden () in section .text of a.out
3:
(gdb) info symbol 0x400a80 Derived :: Foo () in section .text of a.out
Remember that the vtable pointer in Derived pointed to a +16 byte offset in the vtable? The third pointer is the address of the pointer of the first method. Want a third method? No problem – add 2 sizeof (void) to the vtable pointer. Want a typeinfo record? go to the pointer in front of it.
Moving on – what about the typeinfo record structure?
Parent:
And here is the record
typeinfo derived:
one:
(gdb) info symbol 0x602090 vtable for __cxxabiv1 :: __ class_type_info @@ CXXABI_1.3 + 16 in section .bss of a.out
2:
(gdb) x / s 0x400b69 0x400b69 : "6Parent"
3:
(gdb) info symbol 0x602210 vtable for __cxxabiv1 :: __ si_class_type_info @@ CXXABI_1.3 + 16 in section .bss of a.out
4:
(gdb) x / s 0x400b60 0x400b60 : "7Derived"
If you want to know more about __si_class_type_info, you can find some information here as well as here.
This exhausts my skills with gdb and also completes this part. I suggest that some people find this too low, or perhaps simply not of practical value. If so, I would recommend skipping parts 2 and 3, going straight to part 4.
Part 2 – Multiple Inheritance
The world of single inheritance hierarchies is easier for the compiler. As we saw in the first part, each child class extends the parent vtable by adding entries for each new virtual method.
Let's look at multiple inheritance, which complicates the situation, even when inheritance is implemented only purely from interfaces.
Let's look at the following code snippet:
class Mother { public: virtual void MotherMethod () {} int mother_data; }; class Father { public: virtual void FatherMethod () {} int father_data; }; class Child: public Mother, public Father { public: virtual void ChildMethod () {} int child_data; };
Note that there are 2 vtable pointers. Intuitively, I would expect 1 or 3 pointers (Mother, Father and Child). In fact, it is impossible to have one pointer (more on this later), and the compiler is smart enough to combine the entries of the child vtable Child as a continuation of vtable Mother, thus saving 1 pointer.
Why can't a child have one vtable pointer for all three types? Remember that a Child pointer can be passed to a function that accepts a Mother or Father pointer, and both will expect the this pointer to contain the correct data at the correct offsets. These functions do not need to know about Child, and you should definitely not assume that Child is really what is under the Mother / Father pointer with which they operate.
(1) It is not relevant to this topic, but, nevertheless, it is interesting that child_data is actually placed in the filling of Father. This is called tail padding and may be the subject of a future post.
Here is the structure
vtable:
In this example, the Child instance will have the same pointer when casting to the Mother pointer. But when casting to the Father pointer, the compiler calculates the offset of the this pointer to point to the _vptr $ Father part of the Child (3rd field in the Child structure, see the table above).
In other words, for a given Child c ;: (void) & c! = (void) static_cast(& c). Some people do not expect this, and perhaps one day this information will save you some time debugging.
I have found this useful more than once. But wait, that’s not all.
What if Child decided to override one of the Father methods? Consider this code:
class Mother { public: virtual void MotherFoo () {} }; class Father { public: virtual void FatherFoo () {} }; class Child: public Mother, public Father { public: void FatherFoo () override {} };
The situation is getting harder. The function can take the argument Father * and call FatherFoo () for it. But if you pass the Child instance, it is expected to call the overridden Child method with the correct this pointer. However, the caller does not know that he really contains Child. It has a pointer to the Child offset, where the location of the Father is. Someone has to offset the this pointer, but how to do it? What kind of magic does the compiler do to make this work?
Before we answer this, note that overriding one of the Mother methods is not very tricky, since the this pointer is the same. Child knows what to read after vtable Mother, and expects Child methods to be right after it.
Here is the solution: the compiler creates a thunk method that corrects the this pointer and then calls the “real” method. The address of the adapter method will be under the vtable Father, while the “real” method will be under the vtable Child.
Here
vtable Child:
0x4008e8 : 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x4008f0 : 0x60 0x09 0x40 0x00 0x00 0x00 0x00 0x00 0x4008f8 : 0x00 0x08 0x40 0x00 0x00 0x00 0x00 0x00 0x400900 : 0x10 0x08 0x40 0x00 0x00 0x00 0x00 0x00 0x400908 : 0xf8 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0x400910 : 0x60 0x09 0x40 0x00 0x00 0x00 0x00 0x00 0x400918 : 0x20 0x08 0x40 0x00 0x00 0x00 0x00 0x00
Which means:
Explanation: as we saw earlier, Child has 2 vtables – one is used for Mother and Child, and the other for Father. In vtable Father, FatherFoo () points to an “adapter”, and in vtable Child points directly to Child :: FatherFoo ().
And what is in this “adapter”, you ask?
(gdb) disas / m 0x400820, 0x400850 Dump of assembler code from 0x400820 to 0x400850: 15 void FatherFoo () override {} 0x0000000000400820 : push% rbp 0x0000000000400821 : mov% rsp,% rbp 0x0000000000400824 : sub $ 0x10,% rsp 0x0000000000400828 : mov% rdi, -0x8 (% rbp) 0x000000000040082c : mov -0x8 (% rbp),% rdi 0x0000000000400830 : add $ 0xfffffffffffffff8,% rdi 0x0000000000400837 : callq 0x400810 0x000000000040083c : add $ 0x10,% rsp 0x0000000000400840 : pop% rbp 0x0000000000400841 : retq 0x0000000000400842: nopw% cs: 0x0 (% rax,% rax, 1) 0x000000000040084c: nopl 0x0 (% rax)
As we have already discussed, this is offsets and FatherFoo () is called. And how much should we shift this to get Child? top_offset!
Please note that I personally find the non-virtual thunk name to be extremely confusing as it is a virtual table entry for a virtual function. I’m not sure that it’s not virtual, but this is only my opinion.
That's all for now, in the near future we will translate 3 and 4 parts. Follow the news! | https://prog.world/c-vtables-part-1-basics-multiple-inheritance/?amp | CC-MAIN-2022-21 | refinedweb | 1,917 | 69.11 |
subclass a class in the namespace of the that subclass
Discussion in 'Ruby' started by Trans, Oct 22, 2008.
Can define a class for namespace A in some other namespace B?Peng Yu, Sep 14, 2008, in forum: C++
- Replies:
- 0
- Views:
- 661
- Peng Yu
- Sep 14, 2008
String subclass method returns subclass - bug or feature?S.Volkov, Mar 11, 2006, in forum: Ruby
- Replies:
- 2
- Views:
- 242
- S.Volkov
- Mar 12, 2006
Initialize a subclass inside a namespaceJ2M, Oct 15, 2006, in forum: Ruby
- Replies:
- 3
- Views:
- 110
- J2M
- Oct 15, 2006
Subclass of subclassFab, Aug 9, 2012, in forum: C++
- Replies:
- 0
- Views:
- 415
- Fab
- Aug 9, 2012 | http://www.thecodingforums.com/threads/subclass-a-class-in-the-namespace-of-the-that-subclass.853788/ | CC-MAIN-2014-52 | refinedweb | 110 | 75.34 |
This preview shows
pages
1–3. Sign up
to
view the full content.
COP 3503 – Computer Science II – CLASS NOTES - DAY #23 Huffman Coding Tree public class HuffNode { protected boolean children; protected char root; protected HuffNode left; protected HuffNode right; public HuffNode ( ) { children = false; root = null; left = null; right = null; } // end constructor public HuffNode (char in, HuffNode lef, HuffNode rig) { children = true; root = in; left = lef; right = rig; } // end constructor } // end HuffNode public class Hufflist { protected HuffNode head; protected HuffNode current; protected String answer; public HuffList ( ) { head = new HuffNode ( ); current = head; answer = new String ( ); } // end constructor Day 23 - 1
View Full
Document
This
preview
has intentionally blurred sections.
public void insertAll (char[ ] alpha) { for (int i = 0; i < 26; i++) { HuffNode temp = new HuffNode (alpha[i], null, null) if ((i % 2) == 0) { current.left = temp; } else{ current.right= temp; current = getNextParent ( ); } //end else } //end for current = head; } // end insertAll public boolean find (HuffNode h, char c) { if (h.root == c) return true;
This note was uploaded on 02/22/2009 for the course COP 3503c taught by Professor Staff during the Spring '08 term at University of Central Florida.
- Spring '08
- Staff
- Computer Science
Click to edit the document details | https://www.coursehero.com/file/1648987/day23/ | CC-MAIN-2017-17 | refinedweb | 200 | 55.47 |
I am trying to do some Ribbon customizations and was running into an issue as to where my dgnlib file was located. I thought I was in the proper directory, but apparently I was not, so changes were happening to the "personal.dgnlib" file instead. When I was trying the same process on my laptop, it was actually working properly. Looking at the MS_GUIDGNLIBLIST variable, I see what is happening, but I am unsure as to how to fix it since it seems to be broken at the 'System' level and I've just gone though what I thought were the system .cfg files to no avail...
On the laptop (where everything works fine), this is what I have for the variable:
On my work pc (after commenting many cfg files):
By the looks of it, MicroStation Connect is somehow trying to get my default Documents directory. My laptop is not managed by my IT department, but the pc is on the Domain and I know they manage the Home folder with AD.
The question is: How is MicroStation finding this directory? Is this setting modifiable from a MicroStation config or is it programmatically done?
Yes, I know I can reset the variable using '=', but I normally do not do this in my configurations due to version changes/enhancements.
Hi Sean,
in my opininon the best first step is to produce msdebug.txt file (start MicroStation with -debug=5 argument, see e.g. this article for more information) both for you work and personal computers. Comparing these two files it will be more clear how the variables are creates and how your home and work configurations differ.
Personally I am not sure if it's correct to try to define customization on system level, MicroStation CONNECT Edition provides new variables, so the configuration is more flexible (in my opinion ;-) and personal.dgnlib defined using MS_PERSONALDGNLIB looks like better approach.
I have two note to the captures you provided (thanks for them, they are helpful):
Final question is: What do you want to achieve? Do you want to have one dgnlib file with your personal customization, so you will be able to share it easily between work and home computer? Or your aim is something different?
With regards,
Jan
Labyrinth Technology | dev.notes() | cad.point
Hi Jan,
Thanks for reminding me about the debug argument...major brain fart on my end.
The debug confirmed that the variables were still being set by backup files I had in the folder that the system files reside. Had to rename the files to a .bak to prevent them from applying. This allowed me to finally track down what is really going on here.
By looking at the debug file with further testing, the path was set by _USTN_WORKSETROOT which is set inside of ...Configuration\WorkSpaces\NoWorkSpace\NoWorkSet.cfg which set that variable from the Windows variables HOMEDRIVE and HOMEPATH.
_USTN_WORKSETROOT=$(HOMEDRIVE)$(HOMEPATH)\
Given our setup here in our Domain, HOMEDRIVE = U: and HOMEPATH = \
This essentially should set the variable to U:\\ instead of the U:// that MicroStation is setting it to. Further testing came to the following conclusion that only a developer would be able to confirm - the real problem looks like a auto-format/parser that they have inside of MicroStation Connect.
\
Given the above examples, the following things happen:
In my opinion, if multiple backslashes are encountered after a colon, then they should be trimmed down to one instance:
U:\\\ to this-> U:\ not this -> U:///
As to your questions: I was just trying to figure out what was causing the U:// that you noticed wasn't correct either. At this point, the configuration setting is not only affecting this setting, but anything else using _USTN_WORKSETROOT in this instance. I am currently developing a new DGNLIB for our organization's menu system and found it odd that it wasn't modifying the file I was inside of even though it should've been modifiable.
Thanks again for your help with that debug option...
To add a few notes Chuck's summary:
The best practices / recommendations for MicroStation configuration files are:
Of course these rules are not strict, so they can be broken, but there should be a serious reason to do it.
Well, there isn't a chance in the world that I'm going to be able (or anyone else for that matter) to convince an IT person that they will need to change a backslash within a standard Windows variable for a Windows directory to a forward slash since this type of symbology is not really valid for a directory path. Even so, changing this variable to a forward slash would still resolve _USTN_WORKSETROOT to U:// which is not a valid path.
Essentially the delivered MicroStation configuration file NoWorkSet.cfg potentially does not work with standard Windows variables that are in proper Windows directory syntax dependent on the IT section's setup of Home Folder within Active Directory/Group Policy.
This is just going to force me to use WorkSets now where I may not have had to use them since I mainly setup our Department at a Site level.
Thanks for everyone's thoughts on this matter.
Sean Duphily said:There isn't a chance in the world that I'm going to be able to convince an IT person that they will need to change a backslash within a standard Windows variable for a Windows directory to a forward slash
You don't need to. Operating system environment variables should be defined in whatever way is suitable for the operating system. MicroStation configuration variables are not operating system environment variables.
MicroStation configuration files are designed to be operating-system agnostic. Years ago, the same configuration file worked with, say, UNIX, MS-DOS and Windows NT. Times have changed, and the only operating system of interest is Windows 7 etc. Or is that the only game in town? We are seeing Bentley Systems products on Android and other operating systems, so it may be that agnosticism will be required once more.
When MicroStation processes its configuration files, operating system environment variables are evaluated as required. If one of your configuration files finds a Windows environment variable MY_WINDOWS_FOLDER it evaluates it for subsequent use as it processes other configuration variables. The appropriate directory separator characters are used or substituted as required.
Define operating system environment variables as required by your operating system. Define MicroStation configuration variables following the rules for those variables documented in MicroStation help and repeated by Bill Robinson and Jan Slegr above.
Regards, Jon Summers LA Solutions
Jon Summers said:
Define operating system environment variables as required by your operating system. Define MicroStation configuration variables following the rules for those variables documented in MicroStation help and repeated by Bill Robinson and Jan Slegr above.
I totally agree with this. The issue is that a delivered configuration file tries to utilize two Windows variables...HOMEDRIVE and HOMEPATH. By default with a Windows 7+ (maybe Vista also, but I never really used it) machine not connected to a Domain, these variables default to:
HOMEDRIVE - C: HOMEPATH - \users\<username>
In a Domain situation where the IT department utilizes the Home Path option in Active Directory, the HOMEDRIVE variable is set to a drive letter associated to a UNC path and the HOMEPATH will be set to "\". There really isn't an easy way to change this behavior if my memory serves me right...
I initially opened this thread just to find out what was causing the weird result that was happening (U:// instead of U:\) since I've never come across it before. Instead, all I received were comments on how I should be setting up my configuration files and proper syntax. My issue with this is that I never set this file up to begin with and it has all the proper syntax...yet the directory doesn't resolve correctly. I've setup config files and scripting for the past 25 years now (yes, back in the UNIX days as well), so I'm pretty well versed in the proper syntax and understand why the slash is used instead of backslash. On my call into Bentley today, I did mention that maybe they should've finally ditched the Unix syntax since it's been at least 15+ years since I know when we last used one of those machines, but your explanation with potential hurdles with other OS's in the future seems like a valid reason not to change the current system.
After looking into this a bit more tonight, I want to reach out to Bentley development to attempt to fix this issue. If I remember correctly, if a user's Home Path is set from Active Directory, then the HOMESHARE variable should also be set. This variable does not exist (please correct me if I'm wrong here) if the Home Path is not set from Active Directory. I have tested the following code in the configuration file in question and it seems to work fine for me on both my laptop (not part of a Domain) and my pc:
Exist Code:
%if exists ($(HOMEDRIVE)$(HOMEPATH)/Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/Documents/%else _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/%endif
Proposed Code:
%if exists ($(HOMESHARE)) %if exists ($(HOMEDRIVE)$(HOMEPATH)Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)Documents/ %else _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH) %endif%else %if exists ($(HOMEDRIVE)$(HOMEPATH)/Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/Documents/ %else _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/ %endif%endif
If anyone else would like to confirm whether this code does/doesn't or should/shouldn't work, please do so. If there seems to be a consensus that this should work, I'd like the files delivered by Bentley to be changed.
Thanks again,
Sean
Sean Duphily said:In a Domain situation where the IT department utilizes the Home Path option in Active Directory, the HOMEDRIVE variable is set to a drive letter associated to a UNC path
MicroStation configuration file processing comprehends UNC path names. You can use a UNC path in a MicroStation configuration variable...
MY_SERVER = //ServerName/
MY_FOLDER = $(MY_SERVER)cad/dgn/
Sean Duphily said:Proposed Code
Your proposed code convinces me. You've avoided completely any double-slash or double-backslash issues by using only configuration variables and environment variables.
However, the test for $(HOMESHARE) results in the same definition for _USTN_WORKSETROOT whether or not $(HOMESHARE) is defined. Of course, you may have reduced the content for illustration, and you may want to add more statements depending on whether that test succeeds or fails.
Jon Summers said:
MicroStation configuration file processing comprehends UNC path names. You can use a UNC path in a MicroStation configuration variable...
MY_SERVER = //ServerName/
MY_FOLDER = $(MY_SERVER)cad/dgn/
Yes, I already do utilize MicroStation configuration variables in our Site file (for example):
DELDOT_RESOURCES = //dotfs08/cadd/Active_Designs/msv8/DELDOT_MDL = $(DELDOT_RESOURCES)mdlapps/MS_DGNLIBLIST > $(DELDOT_RESOURCES)dgnlib/deldot_levels.dgnlibMS_DGNLIBLIST > $(DELDOT_RESOURCES)dgnlib/deldot_textstyles.dgnlib
Jon Summers said:However, the test for $(HOMESHARE) results in the same definition for _USTN_WORKSETROOT whether or not $(HOMESHARE) is defined.
I'm not quite sure I follow this...the test for %ifexist $(HOMESHARE) should fail on a machine that doesn't have its Home Folder managed by Active Directory:
If this is the case, it will not result in the same definition for _USTN_WORKSETROOT.
However, on a machine that does have the Home Folder managed by Active Directory:
$(HOMESHARE) would resolve to the same location as $(HOMEDRIVE)...only with a UNC path vs. a drive letter. With this, the proposed code could also be written:
%if exists ($(HOMESHARE)) %if exists ($(HOMEDRIVE)/Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)/Documents/ %else _USTN_WORKSETROOT = $(HOMEDRIVE)/ %endif %else %if exists ($(HOMEDRIVE)$(HOMEPATH)/Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/Documents/ %else _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/ %endif %endif
or even as such if UNC paths are desired:
%if exists ($(HOMESHARE)) %if exists ($(HOMESHARE)/Documents) _USTN_WORKSETROOT = $(HOMESHARE)/Documents/ %else _USTN_WORKSETROOT = $(HOMESHARE)/ %endif %else %if exists ($(HOMEDRIVE)$(HOMEPATH)/Documents) _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/Documents/ %else _USTN_WORKSETROOT = $(HOMEDRIVE)$(HOMEPATH)/ %endif %endif | https://communities.bentley.com/products/microstation/f/microstation-forum/114665/connect---ms_guidgnliblist-at-system-level/351489 | CC-MAIN-2020-29 | refinedweb | 1,986 | 50.16 |
Monads, part 2: impure computations
July 9, 2012
Refresher
In the last post, we learned about monads and how to use them to implement exception handling, vector operations, and debug output. To refresh your memory, a monad is defined by:
- A type constructor that defines a monadic type (usually parameterized by some other type).
- A
unitfunction that takes a value and returns a value in the corresponding monadic type.
- A
bindoperation that takes a monadic value and a function from the non-monadic type to the monadic type. It returns a value in the monadic type.
The
IO monad
Today we’ll talk about how one can use monads to describe impure computations in a pure language. Let’s define a monad which represents an impure computation:
class Computation: UNIT = 0 BIND = 1 INPUT = 2 OUTPUT = 3 def __init__(self, type, data): self.type = type self.data = data def __repr__(self): if self.type == Computation.UNIT: type_str = 'Computation.UNIT' elif self.type == Computation.BIND: type_str = 'Computation.BIND' elif self.type == Computation.INPUT: type_str = 'Computation.INPUT' elif self.type == Computation.OUTPUT: type_str = 'Computation.OUTPUT' return 'Computation(' + type_str + ', ' + self.data.__repr__() + ')'
Note that we’ve defined
__repr__so that we can print a computation and examine its structure. Now, let’s define
unitand
bindfor this monad:
def unit(x): return Computation(Computation.UNIT, [x]) def bind(x, f): return Computation(Computation.BIND, [x, f])
Okay, that’s the whole monad! Let’s rewrite some helpers:
input = Computation(Computation.INPUT, []) def output(text): return Computation(Computation.OUTPUT, [text])
We now have a way of describing computations! It’s almost like we have a programming language within a programming language. In order for this monad to be useful, though, we need a way of executing a computation. As you know by now, this is not possible in our functional subset of Python. Let’s break the rules and write just one function in imperative Python, and we’ll consider this to be part of the runtime:
def execute(computation): if computation.type == Computation.UNIT: return computation.data[0] elif computation.type == Computation.BIND: return execute(computation.data[1](execute(computation.data[0]))) elif computation.type == Computation.INPUT: return raw_input() elif computation.type == Computation.OUTPUT: print computation.data[0] return None
Sweet, let’s try it out! We’ll start with Hello, World:
main = output('Hello, World!')
What is
main? Let’s find out:
>>> main Computation(Computation.OUTPUT, ['Hello, World!'])
It’s a computation of type
Computation.OUTPUT, just as we would expect. Now let’s run this computation:
>>> execute(main) Hello, World!
Sweet victory! You can now see how monads can be used to do I/O in a pure functional language. Let me emphasize that the
executeprocedure isn’t written in our pure language, and it’s not referentially transparent. Rather, it is implemented as part of the runtime. The interpreter uses it to execute our program (when we call
execute(main), we are basically playing the role of the runtime).
More advanced examples
Now that we understand the idea, let’s try to write some more useful programs than Hello, World. First, we can try out the program from the previous example which reads a line of text and prints it back:
main = bind(input, output)
This time, we get:
>>> main Computation(Computation.BIND, [Computation(Computation.INPUT, []), <function output at 0x00000000027E1198>])
And running the program:
>>> execute(main) This will get printed back! This will get printed back!
Note that I entered the first
This will get printed back!, and the second one was printed by the program as we would expect.
Now let’s write a program that responds to user input:
def respond(input): if input == 'yes': return output('You said YES!') else: return output('You said NO!') main = bind(input, respond)
Let’s test it out:
>>> execute(main) yes You said YES! >>> execute(main) no You said NO!
It works! Let’s modify the example so that it keeps asking the user for input until he/she says
yes:
def main_wrapper(dummy): return main def respond(input): if input == 'yes': return output('You said YES!') else: return bind(output('Try saying \'yes\' once in a while.'), main_wrapper) main = bind(input, respond)
Does it work?
>>> execute(main) no Try saying 'yes' once in a while. no Try saying 'yes' once in a while. no Try saying 'yes' once in a while. yes You said YES!
Sweet—recursion doesn’t seem to be a problem either. Notice how we defined
main_wrappersimply because
bindexpects a function of one argument. It turns out that this is a common monadic pattern, so let’s abstract it:
def sequence(u, v): return bind(u, lambda x: v)
sequenceperforms the computation
u, ignores its return value, and then performs
vand returns the result. Note that
executemust be eager when evaluating its argument. If it was lazy, the first computation (
u) might never get executed because the lambda expression doesn’t use it. Let’s rewrite our example using
sequence:
def respond(input): if input == 'yes': return output('You said YES!') else: return sequence(output('Try saying \'yes\' once in a while.'), main) main = bind(input, respond)
Does it still work?
>>> execute(main) no Try saying 'yes' once in a while. no Try saying 'yes' once in a while. no Try saying 'yes' once in a while. yes You said YES!
Excellent. To conclude, let’s write a program that asks the user for two lines of input, concatenates them, and prints the result:
def respond2(input1): return lambda input2: output('You said "' + input1 + '" and "' + input2 + '".') def respond1(input1): return bind(input, respond2(input1)) main = bind(input, respond1)
And finally:
>>> execute(main) hello world You said "hello" and "world".
It works! Hopefully by now you have an idea of how to compose impure computations with monads. Let me know in the comments if anything wasn’t clear!
Monads, part 1: a design pattern
July 9, 2012
Monad is a design pattern that allows us to redefine how function composition works. Before I define what a monad is, let’s develop some intuition with motivational examples.
Example 1: exception handling (a.k.a. “Maybe”)
Let’s use Python to describe a function which computes the quotient of
100and some divisor. In the special case where the divisor is zero, we’ll return
None:
def divide100(divisor): if divisor == 0: return None else: return 100 / divisor
Let’s also write a function to compute the square root of a number. If the input is negative, we’ll return
None:
def sqrt(x): if x < 0: return None else: return x ** 0.5
Can we compose these functions? What if we wanted to compute something like
sqrt(divide100(sqrt(x)))? That would work as long as
xis positive. If we explicitly handle the case when any of those functions returns
None, the code becomes much longer:
a = sqrt(x) if a is not None: b = divide100(a) if b is not None: c = sqrt(b)
You can imagine how tedious it would be if we had to do manual error checking like this for all of our function calls. Perhaps a better solution is to rewrite
divide100and
sqrtsuch that they each do the error handling themselves. For example, we might modify them as follows:
def composable_divide100(divisor): if divisor is None or divisor == 0: return None else: return 100 / divisor def composable_sqrt(x): if x is None or x < 0: return None else: return x**0.5
Now we can evaluate expressions like
composable_sqrt(composable_divide100(composable_sqrt(x))). When
x <= 0, the entire expression evaluates to
Nonejust as we would expect.
Rather than modifying all of our functions to check for
None, let’s write a wrapper function (let’s call it
bind) to do the error handling for us. It takes a value (either a number or
None) and a function (such as
divide100or
sqrt) and applies the function to that value. If the input is
None, we skip the function application and just return
None:
def bind(x, f): if x is None: return None else: return f(x)
Now we can compose these functions like:
bind(bind(bind(x, sqrt), divide100), sqrt). Sweet! We have a way to compose numerical functions that might fail. You’ve essentially just implemented Haskell’s
Maybemonad, which is a simple form of exception handling. Let’s try some more complex examples.
Example 2: vector operations (a.k.a. “List”)
We know that, mathematically, positive numbers have two square roots. Let’s modify
sqrtto return a list of values:
def sqrt(x): if x < 0: return [] elif x == 0: return [0] else: return [x**0.5, -x**0.5]
So there are three cases we have to consider. If
xis positive, we return its two square roots. If
xis
0, we return
[0]. If
xis negative, we return the empty list.
Great! Our sqrt function now makes more mathematical sense, at least for real numbers. But we have the same problem as in Example 1—it is no longer composable with itself. We can’t just compute
sqrt(sqrt(x)), because the inner call to
sqrtreturns a list, and the outer call expects a number. As before, we need to define a
bindfunction to help us with composition:
def bind(x, f): return [j for i in x for j in f(i)]
Here,
bindtakes a list of numbers
xand a function
f. The doubly-iterated list comprehension might look cryptic—you can think of it like this: We apply
fto each value in
x, which gives us a list of lists. Then we flatten the result into one list and return it. Now we can compute the square roots of a list of numbers, and then compute all the square roots of the results:
>>> bind(bind([5, 0, 3], sqrt), sqrt) [1.4953487812212205, -1.4953487812212205, 0, 1.3160740129524924, -1.3160740129524924]
It works! But our original goal was to find the square roots of one number. We could always write
bind([x], sqrt)where
xis a number, maybe it would be better to use a function to abstract the representation of our input. Let’s call this function
unit:
def unit(x): return [x]
Yep, it just puts a value into a list. It may seem unmotivated now, but we’ll write a more helpful
unitfunction in the next example. Now we don’t have to put our input into a list—instead, we run it through
unit, which puts it in the necessary representation:
>>> bind(bind(unit(4), sqrt), sqrt) [1.4142135623730951, -1.4142135623730951]
Cool, we can now intelligently compose functions that might return several values! That’s basically Haskell’s
Listmonad.
Example 3: debug output (a.k.a. “Writer”)
Suppose we have some functions
uand
v, and each function takes a number and returns a number. It doesn’t really matter what these functions are, so let’s define them as follows:
def u(x): return x + 4 def v(x): return x * 2
No problem there. We can even compose them, as in
u(v(x)). What if we wanted these functions to output some extra information along with their normal return value? For example, suppose we want each function to also return a string indicating that the function had been called. We might modify
uand
vlike this:
def verbose_u(x): return (x + 4, '[verbose_u was called on ' + str(x) + ']') def verbose_v(x): return (x * 2, '[verbose_v was called on ' + str(x) + ']')
Now we have the same problem as before, we broke composability:
verbose_u(verbose_v(x))doesn’t work. By now, we know the solution to this problem is
bind:
def bind(x, f): result, output = f(x[0]) return (result, x[1] + output)
Here,
xis a tuple containing the result from another operation (such as
verbose_uor
verbose_v) and the output from that operation. We apply
fto
xto produce a new result-output tuple. The final result is the result from applying
fand the concatenation of the previous output and the output from
f. This means we can once again compose
verbose_uand
verbose_v, using
bind:
>>> bind(bind((4, ''), verbose_v), verbose_u) (12, '[verbose_v was called on 4][verbose_u was called on 8]')
Awesome! Not only do we get a numerical result, but we also get a complete execution trace. Notice how we passed
(4, ''), when all we cared about was the
4. The empty string means that no functions had been called at that point, but that’s an implementation detail. It would be better to write a unit function to construct this tuple for us, so we don’t have to worry about what goes in the string, the ordering of the elements of the tuple, etc.
def unit(x): return (x, '')
Our example becomes:
>>> bind(bind(unit(4), verbose_v), verbose_u) (12, '[verbose_v was called on 4][verbose_u was called on 8]')
Still works! We’ve just implemented Haskell’s
Writermonad!
The pattern
In each example, we had some functions which we wanted to compose, but their type signatures were incompatible. Our functions took a value of some type and returned a value in the corresponding monadic type. All we did was write a wrapper function
bind(x, f), which defines the logic for how such functions can be chained together. We also defined
unit(x)(which is often called
returnbecause of the way it is used) to convert a value into a monadic type, so it can be used with our bound functions.
A monad is a type constructor, a
bindoperation, and a
unitfunction. In Example 1, the monadic type was the union of
floatand
NoneType(we didn’t need a
unitfunction because the monadic type was a superset of the input type). In Example 2, the monadic type was
list(of
floats), and
unitsimply put values into a
list. Finally, the monadic type for Example 3 was the product (i.e., tuple) of
intand
str, so unit constructed that tuple from a value and the empty string.
So the use of monads is basically a design pattern, and it’s been used to implement several concepts that are normally associated with imperative programming, such as exception handling (much like in Example 2), parsers, state, collections, and I/O (as we will see shortly).
Monad axioms
Proper monads must obey three axioms so they behave the way we expect.
- Left Identity:
bind(unit(x), f) == f(x)
- Right Identity:
bind(x, unit) == x
- Associativity:
bind(bind(x, f), g) == bind(x, lambda a: bind(f(a), g))
(Here, equality should be taken to mean the two expressions represent the same computation.)
The first two axioms mean that
unitand
bindroughly do inverse things: unit puts a value into a monadic container for binding and bind takes it out to apply a function. The last axiom means we can compose functions together without worrying about how composition precedence works. I’ll leave it as an exercise for the reader to prove that the versions of
unitand
bindthat we wrote obey the three monad laws.
But what about side effects?
It’s probably not obvious how we can use monads to do side effects in a pure way. But by now you understand what a monad is and how to use it to do some useful things, like exception handling, error propagation, and stack traces. We’ll talk about I/O in the next post, but keep in mind that I/O is just one of many uses of monads.
Appendix: do notation
When using monads, expressions like these can become tedious to write:
bind(bind(unit(4), verbose_v), verbose_u)
Haskell uses the infix operator
x >>= fto mean
bind(x, f)(also,
unitis called
returnin Haskell). So in Haskell, it might look more like this:
return 4 >>= verbose_v >>= verbose_u
Not bad. But even with this convenient syntax, it can get a little ugly (example taken from Learn You a Haskell):
Just "Hello, " >>= (\x -> Just "World!" >>= (\y -> Just (x ++ y)))
A special syntax for monads was invented for Haskell called do-notation. It makes common monadic operations easier on the eyes. For example, the above expression could be written in do-notation like this:
do x <- Just "Hello, " y <- Just "World!" Just (x ++ y)
It’s a clever syntax that makes function composition look more like an imperative program. Because it is Haskell-specific, I won’t go into details, but more information can be found here. | https://www.stephanboyer.com/articles/4 | CC-MAIN-2018-39 | refinedweb | 2,732 | 64.81 |
Hide Forgot
Description of problem:
In tetex there is /usr/bin/texdoctk. That is nice with this catch that
it starts with:
use strict;
use Tk;
....
which is an obvious problem as there is no 'perl-Tk' in a base.
For FC4 at least currently 'perl-Tk' package is available in extras.
This is actually a useful program and I would rather not to loose it.
One possible way out could be to replace 'use Tk;' by an equivalent,
if there is no error, construct in a style
BEGIN {
eval {require Tk;};
die "This program requires perl-Tk. Try to look in fedora-extras.\n" if $@;
import Tk;
}
This at least gives a useful information what to do.
Version-Release number of selected component (if applicable):
tetex-3.0-4
Applied, thanks.
From User-Agent: XML-RPC
tetex-3.0-6.FC4 has been pushed for FC4, which should resolve this issue. If these problems are still present in this version, then please make note of it in this bug report. | https://partner-bugzilla.redhat.com/show_bug.cgi?id=162441 | CC-MAIN-2020-05 | refinedweb | 171 | 76.42 |
*
Thread question
Andy Ceponis
Ranch Hand
Joined: Dec 20, 2000
Posts: 782
posted
Feb 21, 2001 10:13:00
0
Hi,
Im wrote a small program where i had a group of threads that i placed into an array. They all had to do basically the same thing, as each thread represented a person doing an action. Now i want to expand on that program. I would like to write another class that takes another thread and has that thread interact with one of the threads that is in the array. Now my question is this. For one program, can i have more than one run() method? If not then how would get my new thread to do what i want it to do if it has to run in the same run() method? Im probably overlooking something here, so i apologize for seeming slow.
Frank Carver
Sheriff
Joined: Jan 07, 1999
Posts: 6920
posted
Feb 21, 2001 10:18:00
0
I'm a little puzzled that you say you want the Threads to interact with each other. Do you actually mean call methods on other Thread objects? This is a somewhat strange thing to want to do. It's far more common (and probably more useful) to have all the threads interacting with some shared data items.
Can you clarify a little on what you want to do with these threads?
Read about me at frankcarver.me
~
Raspberry Alpha Omega
~
Frank's Punchbarrel Blog
Andy Ceponis
Ranch Hand
Joined: Dec 20, 2000
Posts: 782
posted
Feb 21, 2001 11:24:00
0
LOL, i just re-read my post and even i have no clue what thats supposed to mean.
Sorry. I know what i want to ask, but when i type it out it gets all garbled, hehe.
ok, here is some code from a sample i was given to use as an example.
class Diner0 extends Thread { public char state = 't'; public Fork L, R; public Diner0(Fork left, Fork right) { super(); L = left; R = right; } protected void think() throws InterruptedException { sleep((long) (Math.random() * 7.0)); } protected void eat() throws InterruptedException { sleep((long) (Math.random() * 7.0)); } public void run() { int i; try { for (i = 0; i < 1000; i++) { state = 't'; think(); state = L.id; sleep(1); L.pickup(); state = R.id; sleep(1); R.pickup(); state = 'e'; eat(); L.putdown(); R.putdown(); } state = 'd'; } catch (InterruptedException e) { } } } public class Diners0 { static Fork[] fork = new Fork[5]; static Diner0[] diner = new Diner0[5]; public static void main(String[] args) { int i; int j = 0; boolean goOn; for (i = 0; i < 5; i++) { fork[i] = new Fork(i); } for (i = 0; i < 5; i++) { diner[i] = new Diner0(fork[i] , fork[(i + 1) % 5]); } for (i = 0; i < 5; i++) { diner[i].start(); } int newPrio = Thread.currentThread().getPriority() + 1; Thread.currentThread().setPriority(newPrio); goOn = true; while (goOn) { for (i = 0; i < 5; i++) { System.out.print(diner[i].state); } if (++j % 5 == 0) System.out.println(); else System.out.print(' '); goOn = false; for (i = 0; i < 5; i++) { goOn |= diner[i].state != 'd'; } try { Thread.sleep(51); } catch (InterruptedException e) { return; } } } }
now the run() method there is where the created array of threads execute. But the new thread i want to have wont be in the array. Instead what it should do is pick one of the threads in the array and get information from it. For example when thread 2 is in the 'eat' state, my new thread would want to print that out. Is that more clear?
I agree. Here's the link:
subject: Thread question
Similar Threads
Threads Using Static Method
Playing 1 sound after another
[NX]STuPiD questions HELP !!!!
join() method
Servlets, Sessions & Thread Safety??
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/388076/java/java/Thread | CC-MAIN-2014-15 | refinedweb | 640 | 73.68 |
Difficulty Level:
Hard.
Problem Statement :
Sachin is teaching a group of N students. Now every student has an arrogance level. He make all the N students lined up in a row. Now what he saw was a student was forcefully handing over his assignments to the person closest and in front of him with a lower arrogance level. So if the ith students hands over his assignments to the jth student then Sachin reducts j−i+1 marks from the class discipline.
Find the number of marks deducted after some students hand over their assignments to others.
See original problem statement here
Test Case:
Input: 1 5 1 2 3 2 1 Output: 7 Explanation: Student standing at index 0 is the smallest and hence does not have any other student with less arrogance number than him. So, he cannot give his assignment to anybody; Student at index 1 gives his assignment to the student at index 4 as its arrogance number is less than his. So,his contibution in deducted marks is (4-1+1)=4; Student at index 2 gives his assignment to the one at index 3,hence his contribution becomes (3-2+1)=2; Similarly,student at index 3 contributs (4-3+1)=2.
Solving Approach :
According to data structures and algorithms, Starting from the last index we pop elements from stack until we encounter an element lesser than it. In the process, if stack becomes empty that means the student at that particular index does not give his assignment to any other student.We keep pushing elements to the stack.
Solutions:
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 void solve() { long long n, i, j, ans, t; cin >> n ; vector<long long> a(n); for (i = 0; i < n; i++) cin >> a[i]; stack<pair<long long, long long> > st; ans = 0; for (i = n - 1; i >= 0; i--) { while (!st.empty() && st.top().first >= a[i]) st.pop(); if (!st.empty()) { ans = (ans + (st.top().second - i + 1)) % MOD; } st.push(make_pair(a[i], i )); } cout << ans << "\n"; } int main() { int t; cin>>t; while(t--) { solve(); } return 0; }
import java.util.*; public class Solution { final static int M=1000000007; public static void solve(){ Scanner sc=new Scanner(System.in); int n, i,j; long ans, t; n=sc.nextInt(); ArrayList<Long> a=new ArrayList<Long>(); for (i = 0; i < n; i++) a.add(sc.nextLong()); Stack<Pair> st = new Stack<Pair>(); ans = 0; for (i = n - 1; i >= 0; i--) { while (!st.isEmpty() && st.peek().first>= a.get(i)) st.pop(); if (!st.isEmpty()) { ans = (ans + (st.peek().second - i + 1)) % M; } st.push(new Pair(a.get(i), i )); } System.out.println(ans); } public static class Pair { long first; long second; public Pair(long first, long second) { this.first = first; this.second = second; } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { solve(); } } } | https://www.prepbytes.com/blog/stacks/arrogant-students/ | CC-MAIN-2021-39 | refinedweb | 494 | 66.33 |
Elegant astronomy for Python
Skyfield is a pure-Python astronomy package that is compatible with both Python 2 and 3 and makes it easy to generate high precision research-grade positions for planets and Earth satellites.
from skyfield.api import load planets = load('de421.bsp') earth, mars = planets['earth'], planets['mars'] ts = load.timescale() t = ts.now() position = earth.at(t).observe(mars) ra, dec, distance = position.radec() print(ra) print(dec) print(distance)
The result:
10h 47m 56.24s +09deg 03' 23.1" 2.33251 au
Skyfield’s only binary dependency is NumPy. Once that is available, Skyfield can usually be installed with:
pip install skyfield
Here are the essential project links:
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/skyfield/ | CC-MAIN-2017-26 | refinedweb | 132 | 61.33 |
From: Bjørn Roald (bjorn_at_[hidden])
Date: 2007-05-16 22:09:26
Piyo wrote:
> I am open to any form of solution whether it be macro-based or bcp
code is as far as I remember not complete, so the best start would be
the earlier version based on boost::regexp only. If this is what you
want to try, I will send you the code..
To reduce overhead introduced by this build-time, I added an option to
my bcp version which in case the target file exist only will overwrite
if file content changes. This reduces build time dramatically for
changes after initial build.
> or
> Xerces style. I just find it sad that I am stopping 1.34 from entering
> our company on purpose because I do not think that adding to our
> existing 1.32 and 1.33.1 installations will help. Is there anyway we can
> get the core boost developers to look into this? Since I am the only
> boost-evangelist here, I can't imagine me stopping progress over
> something like this.
>
>
Help is offered ;-) Anyone ready to try this can mail me off the list
if you prefer.
-- Bjørn
This file contains notes regarding enhansements to BOOST_ROOT/tools/bcp
to support replacement of the boost namespace in sourcecode copied
from the boost distrubution.
==================== HOWTO ======================
A new option:
--namespace=ns set a namespace that will replace 'boost'
is added to the bcp tool. This allow the user to specify a namespace
to use as replacement for boost in exported source code.
example use:
> cd ~/src/boost
> mkdir -p /tmp/testbcp/mylib
> tools/bcp/run/bcp -cvs -namespace=mylib filesystem /tmp/testbcp/mylib
later you can use
> tools/bcp/run/bcp -cvs --namespace=spoost --diff-only filesystem /tmp/testbcp/mylib
to only do the changes
You can add boost-build.jam Jamfile Jamrules to the module-list on the
bcp command line to get the top level build files needed to build
the exported code. If you change the following 2 lines in the exported Jamfile
[ glob-tree $(BOOST_ROOT)/boost/compatibility/cpp_c_headers : c* ]
[ glob-tree $(BOOST_ROOT)/boost : *.hpp *.ipp *.h *.inc ]
to
[ glob-tree $(BOOST_ROOT)/mylib/compatibility/cpp_c_headers : c* ]
[ glob-tree $(BOOST_ROOT)/mylib : *.hpp *.ipp *.h *.inc ]
you can actually build the exported libraries with bjam. NOTE: see limitation
regarding Boost.Build
================== TODO =========================
1.
Support replacing namespace boost with nested namespace, e.g.
namespace boost ====> namespace mylib::boost
or
namespace boost ====> namespace mylib::stuff::platform
2.
Better Boost.Build and Jamfile support in export
=============== LIMITATIONS ======================
1.
Only replacement of boost namespace with single level namespace
is suported. No replacement with nested namespace supported jet.
2.
Boost.Build export not suported properly. Buildfiles are still configured for
the "boost" name after export. E.g. libriaries built contain the string
"boost" in their filenames.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2007/05/121769.php | CC-MAIN-2021-10 | refinedweb | 489 | 58.69 |
Post your Comment
adding two numbers with out using any operator
adding two numbers with out using any operator how to add two numbers with out using any operator
import java.math.*;
class AddNumbers
{
public static void main(String[] args)
{
BigInteger num1=new
Swap two any numbers
Swap Any Two Numbers
... to swap or exchange the number to each other. First of all we have to create.... Use a
temporary variable z of type integer that will help us to swap
Comparing Two Numbers
Comparing Two Numbers
... of
comparing two numbers and finding out the greater one. First of all, name a
class "Comparing" and take two numbers in this class. Here we have
taken a=24
Addition of two numbers
Addition of two numbers addition of two numbers
Write a program to list all even numbers between two numbers
Write a program to list all even numbers between two numbers
Java Even Numbers - Even...
all the even numbers between two numbers. For this first create a class named
Rational Numbers
rational numbers. A rational number can be represented as the ratio of two integer... form. That is, any common factor of a and b should be removed. For example... static method that returns the largest common factor of the two positive
Adding two numbers
Adding two numbers Accepting value ffrom the keyboard and adding two numbers
Listing all even numbers between two numbers
Listing all even numbers between two numbers Hi,
How to write code to list all the even numbers between two given numbers?
Thanks
Hi... the numbers.
Check the tutorial Write a program to list all even numbers between two
Applet for add two numbers
);
add(text2);
label3 = new Label("Sum of Two Numbers...Applet for add two numbers what is the java applet code for add two numbers?
import java.awt.Graphics;
import javax.swing.*;
public
Swap two any numbers (from Keyboard)
Swap two any numbers (from Keyboard)
... will
learn how to swap or exchange the number to each other. First of all we have... in command line. Use a
temporary variable z of type integer that will help us to swap
Midpoint of two number
important to find the number that is exactly between two numbers.
In this example we are finding a midpoint of two
numbers by using the while loop.
...Midpoint of two number
program to calculate swap of two numbers. Swapping
is used where you want... ability.
In this program we will see how we can swap two
numbers. We can do... swap the numbers. To swap two numbers first we have to
declare a class Swapping
Swapping of two numbers in java
Swapping of two numbers in java
In this example we are going to describe swapping of two numbers in java without using the third number in
java. We... values from the command prompt. The swapping of two
numbers is based on simple
Add Complex Numbers Java
aware of Complex numbers. It is composed of two part - a real part and an imaginary... format of complex numbers is "a + bi". We have taken two variables a and b.The... of two complex numbers.
Here is the code:
public class ComplexNumber
Mysql Multiply
;
Mysql Multiply is used to define the product of any two or more numbers... two or more numbers
in a specified table.
select(a*b) : The Query return you the product of two numbers a and
b.
Query:
The given below query is used
Mysql Multiply
the product of any two or more numbers
in a specified table.
select(a*b) : The Query return you the product of two numbers a and
b.
Query:
...;
Mysql Multiply is used to define the product of any two or more
Add Two Numbers in Java
Add Two Numbers in Java
... of two numbers!
Sum: 32... these
arguments and print the addition of those numbers. In this example, args
Two Element Dividing Number
Dividing Two Numbers in Java
...
will learn how to divide any two number. In java program use the class package... are going to use how to divide two
number. First all of, we have to define class named
PHP Numbers Variables
PHP Variables Numbers
We already define that variables are used to store the values or information in the form text strings, numbers or array. A variable... you can used again and again.
You can also assign numbers in PHP variable
Hexadecimal numbers multiplication
Hexadecimal numbers multiplication Sir,
I have to multiply 128 bit hexadecimal numbers. Do u have any logic for this??
The numbers are like
ab7564fa342b5412c34d9e67ab341b58
Swapping of two numbers without using third variable
Swapping of two numbers without using third variable
In this tutorial we.... This is simple program to swap two value using
arithmetic operation Swapping of two... to swap two variables without using the third variables. First
we declare one
JavaScript determine add, product of two numbers
JavaScript determine add, product of two numbers
In this section, you... numbers. To find this, we have created two textboxes
and four button...("Sum of two numbers is: "+sum);
}
function divide
Post your Comment | http://www.roseindia.net/discussion/21586-Swap-two-any-numbers.html | CC-MAIN-2014-52 | refinedweb | 847 | 64.91 |
Download presentation
Presentation is loading. Please wait.
Published byEmory Ford Modified about 1 year ago
1
DECISIONS Chapter 5
2
The if Statement Action based on a conditions If the condition is true, the body of the statement is executed if (amount <= balance) balance = balance – amount;
3
Flow Chart for If Statement Amount <= Balance? balance= balance - amount Look familiar?
4
The if Statement (Java Form) If (amount < = balance) balance = balance – amount; else balance = balance – OVERDRAFT_PENALTY; Amount <= Balance? balance= balance – OVERDRAFT_PENALTY Java Statements.Visual Logic.
5
If Else Flowchart
6
Java Code for If Else If (amount < = balance) balance = balance – amount; else balance = balance – OVERDRAFT_PENALTY;
7
The if Statement What if you need to execute multiple statements based on decision? if (amount <= balance) { double balance = balance – amount; }
8
What Is Wrong if (amount <= balance) newBalance = balance – amount; balance = newBalance; if (amount <= balance) { newBalance = balance – amount; balance = newBalance; }
9
Relational Operators Test the relationship between two values. Most of the operators are similar to Visual Logic There are some differences. A big one is equals. In Visual Logic equals is =. In Java ==. Not equal in Java is !=.
10
Relational Operators JavaDescription >Greater than >=Greater than or equal
11
Comparing Floating-Point Numbers Must be careful in comparing Rounding problems
12
Java Example of Floating Point Comparison
13
Comparing floating – Point Numbers Need to test for close enough final double EPSILON = 1E-14; if (Math.abs(x-y) <= EPSILON) // x is approximately equal to y
14
Comparing Strings Can’t use mathematical operators Special methods have been developed if (string1.equals(string2))…. Remember case matters Special method if (string1.equalsIgnoreCase(string2))…. This is very different from Visual Logic
15
Comparing Strings May want to compare other than equal string1.compareTo(string2) < 0; Compares based on dictionary What happen if we use == We are testing the string on left with constant If (nickname == “Rob”) Testing to see if the variable nickname value is Rob. Will be true only if it points to the string object Remember that a string is and object and what is stored is the address. That is the problem
16
Comparing Strings String nickname = “Rob”; If(nickname == “Rob”); //Test is true String name=“Robert”; String nickname = name.substring(0,3); If(nickname == “Rob”); //Test is false
17
Comparing Objects Use == you are testing to determine if the reference of the two objects are the same. In other words, do they point to the same address Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); box1 == box2; // true or false box1 == box 3; //true or false
18
Testing for Null Null is a special object reference It says no value has been set. The memory has been set aside or instantiated Null is not the same as the empty string “” “” assigns a blank Null means no assignment has been made if (x = null)………
19
Multiple Alternatives Require more than 1 if/else decisions Need to make series of related comparisons Use if …. else if ……
20
Example public String getDescription() { if (richter >=8.0) r = “Most structures fall”; else if (richter >= 7.0) r = “Many buildings destroyed”; ………. else r= “Negative numbers are not valid”; return r; }
21
Switch Statement Use instead of a sequence of if/else/else statements. int digit; ….. Switch (digit) { case 1: System.out.print(“one”); case 2: System.out.print(“two”); default: System.out.print(“error”); }
22
Nested Branches Based on the decision of one statement make another decision.
23
Nested Branch in Visual Logic
24
Nested Branches - Java If (status == SINGLE) { if (income <= SINGLE_BRACKET1) tax = Rate1 * income; else if (income <= SINGLE_BRACKET2) tax = Rate2 * income.
25
Enumeration Types Think of it as a switch statement for strings. You assure that they are categorized correctly public enum FilingStatus {SINGLE, MARRIED} FilingStatus status = FilingStatus.SINGLE; Use the == to compare enumerated values if (status==FilingStatus.SINGLE)…
26
Using Boolean Expressions True/False Assigned to an expression such as <1000 double amount = 0; System.out.println(<1000); Output: true
27
Predicate Methods Method that returns a boolean value public class BankAccount { public boolean isOverdrawn() { return balance < 0; }
28
Character Class Predicate Methods isDigit isLetter isUpperCase isLowerCase Scanner class hasNext() nextInt
29
Boolean Operators Test two conditions and && or || if (input.equals(“S”) || input.equals(“M”))….. If(input.equals(“S”) && input.equals(“M”)) …. Can use ! – means not Negates the answer Same as Visual Logic Note repeat
30
Boolean Variables Primitive type Must declare as boolean private boolean married; if (married) ….. Don’t use if (married == true)…
Similar presentations
© 2016 SlidePlayer.com Inc. | http://slideplayer.com/slide/4273766/ | CC-MAIN-2016-50 | refinedweb | 759 | 52.09 |
Archived:How to access Symbian resources in WRT or Flash Lite, using PySymbian
Introduction
New programming languages for mobile application development, such Flash Lite and WRT, can't access device native resources such as GPS, Accelerometer, etc. This problem happens because they usually run in a sandbox. An approach that fixes this problem is the development of an access layer which must be between device and mobile application (Flash Lite or WRT). This access layer can be developed in any programming language that has native access to the device.
The figure below shows how this layer works.
Solution
We propose the development of a mobile web server written in Python language which the main goal is to allow the retrieval of available native services in a Web Service REST-based approach. The web server was developed in an extensible manner that allows an easy addition of new services, decoupling the parameters handling of the service implementation. Due to that, it's possible to write a service with just the business logic itself.
Figure 2 depicts our architecture solution. There are three main entities associated with the architecture: client, HTTP server and the services.
- Client: the application written in whatever technology, such as WRT or FlashLite, which requires internal resources. This application is completely independent from ServerPython, because this use only HTTP request to communicate with it.
- HTTP Server: Manages all requests from Clients and invokes the right service.
- Services: A set of services implemented by the developer. This is the hotspot of the ServerPython framework.
Figure 2. Architecture of the Mobile Web Server
Figure 3 shows the class diagram of the ServerPython. The Services class is the hotspot of the framework. The developer has to create methods and call the addCallBack method of the MyServer class added in the instance of Services.
Figure 3. Class diagram
The Source-Code
In this section, we present some of the main features of our solution.
The code below presents the HTTPServer class which handles the HTTP requests.
class HTTPServer:
def __init__(self, host, port):
"""This class is responsible for parsing the HTTP request and calling the correct method"""
self.host = host;
self.port = port;
self.callbacks={}
def doGet(self, request, response):
"""This method is called when a GET request is sent to the web server. It MUST be overwritten in subclasses and it's called through template method design pattern"""
pass
def doPost(self, request, response):
"""This method is called when a POST request is sent to the web server. It MUST be overwritten in subclasses and it's called through the template method design pattern"""
pass
def __handlerAttributes(self, rawAttributes):
"""This method is called to handler the attributes of the HTTP request"""
rawAttributes=rawAttributes[:-2]
map={}
for i in rawAttributes:
map[i[:i.find(':')]]=i[i.find(':')+2:-1]
return map
def __handlerRequest(self, connection, rawRequest):
"""This method is called to handler the request. It splits the tokens, call the '__handlerAttributes' method and finaly call the correct request, i.e. GET or POST method"""
self._rawRequest = rawRequest
tokenizedLine=self._rawRequest.split('\n')
requestLine=tokenizedLine[0]
attributes = self.__handlerAttributes(tokenizedLine[1:])
tokenizedLine = requestLine.split()
attributes["request-method"]=tokenizedLine[0]
attributes["requisition"]=tokenizedLine[1]
attributes["http-version"]=tokenizedLine[2]
request_object = attributes["requisition"]
if request_object.startswith('/'):
request_object=request_object[1:]
objects=request_object.split('?')
attributes["object-requested"]=objects[0]
map={}
if len(objects)>1:
objects=objects[1].split('&')
for i in objects:
iObject = i.split('=')
map[iObject[0]]=iObject[1]
attributes["parameters"]=map
request = Request(self._rawRequest, attributes)
response = Response()
if attributes["request-method"]=='GET':
self.doGet(request, response)
elif attributes["request-method"]=='POST':
self.doPost(request, response)
rsp = response.getResponse()
connection.send(rsp)
class MyServer(HTTPServer):
"""This is a subclass of HTTPServer. The implementation of the GET HTTP method is provided. In our case, we call the correct service"""
def __init__(self,host, port):
HTTPServer.__init__(self, host, port)
def doGet(self, request, response):
"""Implementation of the GET method"""
functionName=request.getProperty("object-requested")
attributes=request.getProperty("parameters")
response.println(str(self.callbacks[functionName](attributes))) # Call the service requested and return the result as a string
This is a service example. In this function we retrieve the position of device through GPS
def get_position(attributes):
positioning.select_module(positioning.default_module())
pos=positioning.position()['position']
ret='latitude=' + str(pos['latitude']) + '&longitude=' + str(pos['longitude'])
return ret
This is a piece of code that shows how to start the server and to add a service.
server = MyServer('127.0.0.1',5004)
server.addCallBack("get_position", get_position)
server.startServer()
Step-by-step guide to install and use the ServerPython
- Download and install spython.sis into your device.
- Start the spython application.
- Start the application which uses the intended resource (Flash Lite or WRT)
The developer can easily include new methods into the S60ServerPython, which requires minor knowledges about Python language. Below is described the required steps to make this task.
Implement a method 'method_x' in the Services class. It imposed just one restriction to the new method structure. The method MUST receive a map representing the passed parameters of the URL.
Execute the method 'server.addCallBack('url_to_x', method_x)', where server is an attribute of the type MyServer inside the Services class.
Download
Here you can download the source code and the SIS file of the ServerPython. Note that if you want to use GPS, you have to install the SIS file. Click here to get the zip file with the source and SIS.
An example application in Flash Lite
As discussed previously, a client (Flash Lite) application has access to S60 internal resources through HTTP requests. In ActionScript 2.0 (which is used in Flash Lite 2.x and 3.x) a HTTP request can be executed using the LoadVars class. The basic use of this class is shown below:
var lv:LoadVars = new LoadVars();
lv.onLoad = function(success:Boolean){
//Actions when data is loaded.
}
lv.sendAndLoad("",lv,"GET");
The URL has to be changed to
if you want to get the GPS position from the device using the ServerPython.
A complete example on getting GPS position and showing a Google static map can be found here: File:Gps-serverpython.zip example project. More details about this example code are available here: Accessing system resources with PySymbian on S60 3rd Edition devices.
Created by
- Ivo Calado (ivocalado [at] embedded [dot] ufcg [dot] edu [dot] br)
- Marcos Fábio Pereira (marcos [at] embedded [dot] ufcg [dot] edu [dot] br) | http://developer.nokia.com/community/wiki/index.php?title=How_to_access_Symbian_resources_in_WRT_or_Flash_Lite,_using_PySymbian&oldid=173289 | CC-MAIN-2014-35 | refinedweb | 1,067 | 50.12 |
#include <vmi.h>
List of all members.
Example usage:
Return the JNI JavaVM associated with the VM interface.
JavaVM* JNICALL GetJavaVM(VMInterface* vmi);
Return a pointer to an initialized HyPortLibrary structure.
HyPortLibrary* JNICALL GetPortLibrary(VMInterface* vmi);
The port library is a table of functions that implement useful platform specific capability. For example, file and socket manipulation, memory management, etc. It is the responsibility of the VM to create the port library.
Return a pointer to a HyVMLSFunctionTable.
This is a table of functions for allocating, freeing, getting, and setting thread local storage.
ifndef HY_ZIP_API
Return a pointer to the HyZipCachePool structure used by the VM. It is the responsibility of the vm to allocate the pool using zipCachePool_new(). else
Return a pointer to a JavaVMInitArgs structure as defined by the 1.2 JNI specification.
This structure contains the arguments used to invoke the vm.
JavaVMInitArgs* JNICALL GetInitArgs(VMInterface* vmi);
Genereated on Tue Mar 11 19:25:27 2008 by Doxygen.
(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable. | http://harmony.apache.org/subcomponents/drlvm/doxygen/intf/html/struct_v_m_interface_functions__.html | CC-MAIN-2015-35 | refinedweb | 173 | 51.75 |
Since its release, the Eclipse Rich Client Platform (RCP) has suffered from a lack of support for automated builds with tests. The IDE provides tools for building and packaging RCP applications, but they are very different from the PDE/Build tools that perform these tasks in an automated fashion. Also, until recently, testing support for JUnit 4 was not present in the Eclipse TestFramework. While the situation has markedly improved in Eclipse 3.6, setting up an automated build with tests remains a time-consuming and difficult task.
To make the job easier, I've created a minimal project called "Lightning," which demonstrates how to combine the new automated build tool Buckminster, the Eclipse Test Framework, and the integration testing tool SWTBot. Lightning has been tested on Linux and Windows. (Buckminster on the Mac platform has a few kinks to work out.)
Buckminster is a build system for Eclipse products and plug-ins. It can be run from within the IDE (with the proper tooling installed) or from the command line. I use the command-line version in Lightning, so no additional IDE tooling is required. Buckminster can inspect artifacts such as plug-ins and features in order to determine their dependencies.
I launch Buckminster with Apache Ant, which manages all the other tools required by Lightning. Ant provides the top-level targets and everything you need to run the build from Eclipse, the command line, or a continuous-integration server like Jenkins.
Since the command-line distribution of Buckminster is hard to install manually, the Lightning build process installs it automatically using the P2 director application from the Buckminster download site. P2 is the provisioning system in Eclipse, replacing the old update manager.
The first step in building the Lightning project is to download it from github and unzip it, or just clone the project using git.
Because this build uses Buckminster, you can actually download and assemble the target platform for the project from the Helios P2 repository automatically which is called "materializing" in Buckminster parlance. To do so, simply navigate to the "Buckminster.build.feature" directory and run the command
ant materialize.target.platform, which will materialize the target platform to "<unzip location>/workspace-target-platform." This directory will serve as the target platform for the IDE workspace. Next, import the Lightning plug-ins into a new Eclipse 3.6 workspace and instruct it to use the target platform you just materialized.
Building the Application
You can kick off the full build process by running the command
ant from the "buckminster.build.feature" directory.
The build process starts by installing P2. This, in turn, installs the command-line version of Buckminster. The next step uses Buckminster to build the Eclipse RCP products. Two products are created during the build process. The first is the test product, which includes Lightning along with all tests and test dependencies. The second is the production product, which includes only the Lightning application. This is the version that will be shipped to customers when the time comes. If it seems a little strange that two products are needed, just remember that the tests must be run inside an OSGi environment, and this means that they need to be packaged into a fully functional Eclipse RCP application.
When Buckminster is used to build the Lightning products it runs in an Eclipse workspace, just as it would if it were being run from within the IDE. The first step in building the product, therefore, is to set up the workspace and associated target platform. This gives Buckminster a sandbox in which to play. The target platform is imported using a target definition file, which tells Buckminster where to place any plug-ins it later downloads for the target platform. Next, the
import command executes an import of those plug-ins as defined in a .cquery file (Listing One).
Listing One: The structure of the .cquery file.
<cq:componentQuery xmlns: <cq:rootRequest ... </cq:componentQuery>
The .cquery file points to an Eclipse feature that I have created especially for Buckminster, and also includes a list of places to find the plug-ins included in that feature. This list is stored in an .rmap file, part of which I include in Listing Two.
Listing Two: The .rmap file.
<rm:rmap xmlns: <rm:searchPath <rm:provider <rm:uri </rm:provider> </rm:searchPath> <rm:searchPath <rm:provider <rm:uri <bc:propertyRef </rm:uri> </rm:provider> </rm:searchPath> <rm:searchPath <rm:provider <rm:uri <bc:propertyRef <bc:propertyRef </rm:uri> </rm:provider> </rm:searchPath> <rm:locator <rm:locator <rm:locator </rm:rmap>
The .rmap file lists the locations of the plug-ins that ultimately make up the application. These include public P2 repositories from the Internet, local P2 repositories, and local source folders. The local P2 repositories were created earlier in the build process using the P2 director application and a list of previously built plug-ins. To reduce traffic to the remote P2 repositories, it is a good idea to create mirrors of the P2 repositories on the local network (though this is not required).
Once the .cquery is imported, Buckminster has a fully materialized target platform, a workspace, and the required projects for Lightning. It is now ready to build the projects. Note that you could set up the build to use the workspace-target-platform created earlier, and the process would probably be a bit faster. But I wanted to demonstrate how Buckminster can assemble a target platform on the fly. | http://www.drdobbs.com/tools/automating-an-eclipse-rcp-build/231500378 | CC-MAIN-2017-47 | refinedweb | 914 | 55.34 |
2011-08-19 Dev status update
The first weekly status update about the development of ZF2.
Community Initiatives
Obviously, community interaction has exploded. Since last week, we've had almost 400 messages in the zf-contributors mailing list, an IRC meeting, and the start of a dedicated "ZF2" area of the main website (if you're reading this, you're in it).
Topics that have been under heavy discussion include:
- What will modules look like, and how will they be installed (and potentially distributed).
- Process: how should the proposal process work moving forward, and what ideas fit for it. One item we've agreed upon is that for architectural issues, posting to the mailing list, discussing in IRC, and creating RFC-style pages in the wiki is probably better.
- Visualizing development status: a page has been built, based on the work of Evan Coury in his zf-status project. This should help folks identify what new changes and features exist that they may want to review.
If you missed the IRC meeting, we have a summary posted.
Development status
The Zend Framework core team has decided to write, every week, a post on this blog to inform about the development status of ZF2.
The aim of this update is to have a new channel where the developers that are working on the ZF2 can share ideas with the community and inform people about the working progress of the project. Of course, we have the ZF wiki, the mailing lists and the IRC channels (#zftalk.dev, #zf2-meeting) but we think that this blog can be helpful as well.
This is the first post of the new ZF2 blog about the dev status update of ZF2. We hope you will find it useful.
In the last week the Zend Framework Core Team has been involved in the development of the new Zend\Http components.
In particular we have redesigned the following classes:
- Zend\Http\Request
- Zend\Http\Response
- Zend\Http\Headers
- Zend\Http\Client
We implemented these components following the RFC specifications:
- RFC2616, for the HTTP 1.1
- RFC3986, for the Uniform Resource Identifier (URI)
- RFC2069, RFC2617, for the HTTP Authentication: Basic and Digest Access Authentication
The new API provided is more convenient compared with the ZF1. We provided a full OO implementation of the Headers with specific features for each type (for instance we have Zend\Http\Header\Accept that implements the Accept header type).
These classes are implemented in the namespace Zend\Http\Header. In order to support not standard headers we built a generic header class, Zend\Http\Header\GenericHeader.
The new Zend\Http\Client is basically a class that uses the Request, Response, Headers components to send request to a specific HTTP adapter.
Just to give you an idea of these new architecture, we reported an example of two different uses for the same use case:
First example
Second exampleSecond example
<?php
$client= new Zend\Http\Client('');
$client->setMethod('POST');
$client->setParameterPost(array('foo' => 'bar));
$response= $client->send();
if ($response->isSuccess()) {
// the POST was successfull
}
<?php
$request= new Zend\Http\Request();
$request->setUri('');
$request->setMethod('POST');
$request->setParameterPost(array('foo' => 'bar));
$client= new Zend\Http\Client();
$response= $client->send($request);
if ($response->isSuccess()) {
// the POST was successfull
}
Moreover, we implemented a static version of the Zend\Http\Client to be able to write something simple code like that:
<?php
$response= Zend\Http\ClientStatic::post('',array('foo'=>'bar'));
if ($response->isSuccess()) {
// the POST was successfull
} | http://framework.zend.com/blog/2011-08-19-dev-status-update.html | CC-MAIN-2014-52 | refinedweb | 577 | 51.38 |
This.
Note by jdike - The main benefit to this is that it brings an
arbitrary thread back into context, where it can be examined by
gdb. The fact that it dumps it stack is secondary. This provides
the capability to examine a sleeping thread, which has existed in tt
mode, but not in skas mode until now.
Also, the other threads, that sysrq doesn't cover, can be gdb-ed
directly anyway.
Signed-off-by: Allan Graves<allan.graves@...>
Signed-off-by: Jeff Dike <jdike@...>
Index: test/arch/um/drivers/mconsole_kern.c
===================================================================
--- test.orig/arch/um/drivers/mconsole_kern.c 2005-09-02 12:50:26.000000000 -0400
+++ test/arch/um/drivers/mconsole_kern.c 2005-09-02 13:03:31.000000000 -0400
@@ -32,6 +32,7 @@
#include "os.h"
#include "umid.h"
#include "irq_kern.h"
+#include "choose-mode.h"
static int do_unlink_socket(struct notifier_block *notifier,
unsigned long what, void *data)
@@ -276,6 +277,7 @@
go - continue the UML after a 'stop' \n\
log <string> - make UML enter <string> into the kernel log\n\
proc <file> - returns the contents of the UML's /proc/<file>\n\
+ stack <pid> - returns the stack of the specified pid\n\
"
void mconsole_help(struct mc_request *req)
@@ -479,6 +481,56 @@
}
#endif
+/* Mconsole stack trace
+ * Added by Allan Graves, Jeff Dike
+ * Dumps a stacks registers to the linux console.
+ * Usage stack <pid>.
+ */
+void do_stack(struct mc_request *req)
+{
+ char *ptr = req->request.data;
+ int pid_requested= -1;
+ struct task_struct *from = NULL;
+ struct task_struct *to = NULL;
+
+ /* Would be nice:
+ * 1) Send showregs output to mconsole.
+ * 2) Add a way to stack dump all pids.
+ */
+
+ ptr += strlen("stack");
+ while(isspace(*ptr)) ptr++;
+
+ /* Should really check for multiple pids or reject bad args here */
+ /* What do the arguments in mconsole_reply mean? */
+ if(sscanf(ptr, "%d", &pid_requested) == 0){
+ mconsole_reply(req, "Please specify a pid", 1, 0);
+ return;
+ }
+
+ from = current;
+ to = find_task_by_pid(pid_requested);
+
+ if((to == NULL) || (pid_requested == 0)) {
+ mconsole_reply(req, "Couldn't find that pid", 1, 0);
+ return;
+ }
+ to->thread.saved_task = current;
+
+ switch_to(from, to, from);
+ mconsole_reply(req, "Stack Dumped to console and message log", 0, 0);
+}
+
+void mconsole_stack(struct mc_request *req)
+{
+ /* This command doesn't work in TT mode, so let's check and then
+ * get out of here
+ */
+ CHOOSE_MODE(mconsole_reply(req, "Sorry, this doesn't work in TT mode",
+ 1, 0),
+ do_stack(req));
+}
+
/* Changed by mconsole_setup, which is __setup, and called before SMP is
* active.
*/
Index: test/arch/um/drivers/mconsole_user.c
===================================================================
--- test.orig/arch/um/drivers/mconsole_user.c 2005-09-02 12:50:26.000000000 -0400
+++ test/arch/um/drivers/mconsole_user.c 2005-09-02 12:56:59.000000000 -0400
@@ -30,6 +30,7 @@
{ "go", mconsole_go, MCONSOLE_INTR },
{ "log", mconsole_log, MCONSOLE_INTR },
{ "proc", mconsole_proc, MCONSOLE_PROC },
+ { "stack", mconsole_stack, MCONSOLE_INTR },
};
/* Initialized in mconsole_init, which is an initcall */
Index: test/arch/um/include/mconsole.h
===================================================================
--- test.orig/arch/um/include/mconsole.h 2005-09-02 12:50:26.000000000 -0400
+++ test/arch/um/include/mconsole.h 2005-09-02 12:56:59.000000000 -0400
@@ -81,6 +81,7 @@
extern void mconsole_go(struct mc_request *req);
extern void mconsole_log(struct mc_request *req);
extern void mconsole_proc(struct mc_request *req);
+extern void mconsole_stack(struct mc_request *req);
extern int mconsole_get_request(int fd, struct mc_request *req);
extern int mconsole_notify(char *sock_name, int type, const void *data,
Index: test/arch/um/kernel/process_kern.c
===================================================================
--- test.orig/arch/um/kernel/process_kern.c 2005-09-02 12:53:20.000000000 -0400
+++ test/arch/um/kernel/process_kern.c 2005-09-02 13:04:47.000000000 -0400
@@ -119,7 +119,14 @@
to->thread.prev_sched = from;
set_current(to);
- CHOOSE_MODE_PROC(switch_to_tt, switch_to_skas, prev, next);
+ do {
+ current->thread.saved_task = NULL ;
+ CHOOSE_MODE_PROC(switch_to_tt, switch_to_skas, prev, next);
+ if(current->thread.saved_task)
+ show_regs(&(current->thread.regs));
+ next= current->thread.saved_task;
+ prev= current;
+ } while(current->thread.saved_task);
return(current->thread.prev_sched);
Index: test/include/asm-um/processor-generic.h
===================================================================
--- test.orig/include/asm-um/processor-generic.h 2005-09-02 12:50:26.000000000 -0400
+++ test/include/asm-um/processor-generic.h 2005-09-02 12:56:59.000000000 -0400
@@ -21,6 +21,7 @@
* copy_thread) to mark that we are begin called from userspace (fork /
* vfork / clone), and reset to 0 after. It is left to 0 when called
* from kernelspace (i.e. kernel_thread() or fork_idle(), as of 2.6.11). */
+ struct task_struct *saved_task;
int forking;
int nsyscalls;
struct pt_regs regs; | http://sourceforge.net/p/user-mode-linux/mailman/user-mode-linux-devel/thread/200509142155.j8ELtsQG012132@ccure.user-mode-linux.org/ | CC-MAIN-2014-49 | refinedweb | 706 | 52.05 |
TL;DR – Python
range() is used for generating a sequence of numbers. It takes a starting point and ending point, and generates all the integers in between them.
Contents
Basic syntax for Python range()
The
range() function follows this syntax:
range([start,] stop [, step])
The
start,
stop, and
step parameters are all integers.
start and
stop tell Python the numbers to start and stop generating integers at. The
step parameter indicates whether numbers should be generated in sequence, or whether some specific integers should be skipped.
Note: only the stop parameter is required for the range() function to work. If you don’t provide a start value, Python will simply use zero.
To add one more number to the sequence, you need to raise the
stop value by the amount of the
step parameter. In the example below, the
step value is not defined explicitly, so it's
1 by default. The current output is
0, 1, 2, 3.
Note: the stop value is not included in the generated range.
If you want the function to generate a
4 as well, increase the
stop value from
4 to
5:
for i in range(4): print(i, end=', ')
0, 1, 2, 3,
Python
range() only supports integers by default. If you want to create a sequence of float values, you’ll need to create a new version of the
range()function:
def frange(start, stop, step): i = start while i < stop: yield i i += step for i in frange(0.5, 1.0, 0.1): print(i)
0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999
With this new function, you can create ranges of floating values.
Note: you can use other functions, such as len(), to specify the start, stop, or step parameters based on the length or other characteristics of another Python object.
Understanding the step parameter
The
step parameter is used to specify the numeric distance between each integer generated in the range sequence. By default,
range in Python uses a
step value of
1.
If you want to generate a range that increases in increments greater than
1, you’ll need to specify the
step parameter. For example, to generate a range from
0 to
10 by increments of
2, you would use:
range(0, 10, 2)
The
step parameter can also be used to generate a sequence that counts down rather than up. In that case, you need to reverse the
start and
stop values as well as specify a negative number for the
step parameter:
range(10, 0, -2)
Depending on your
start,
stop, and
step values, it is also possible to generate a sequence that goes from negative to positive integers or from positive to negative integers:
range(-5, 5, 1)
range(4, -2, -2)
Theory is great, but we recommend digging deeper!
Making a list of integers
Lists are extremely useful containers for data of different types in Python. How do you make a list of integers using
range() in Python 3? Simply combine the
list() command with the
range() command:
print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Using Python range() in a for loop
One of the most common uses of the
range() function is for iterating over a series of values in a
for loop. This is particularly useful if you want to access each of the values in a list or array, or, for example, only every other value.
To give an example of how
range() works with
for loops, let’s make a list of integers and then double every value in the list:
samples = [1, 3, 5, 7, 9] for i in range(len(samples)): print("Element index[", i, "]", "Previous value ", samples[i], "Now ", samples[i] * 2)
Element index[ 0 ] Previous value 1 Now 2 Element index[ 1 ] Previous value 3 Now 6 Element index[ 2 ] Previous value 5 Now 10 Element index[ 3 ] Previous value 7 Now 14 Element index[ 4 ] Previous value 9 Now 18
In this example, the
range() function is generating a sequence from
0 to
4. The
for loop is then using each value generated by
range(), one at a time, to access a value from the
sampleList.
This brings up an important point about the way
range() differs in Python 2 and Python 3. In Python 3, the
range() function generates each number in the sequence one at a time. That means it iterates through the sequence it is generating, rather than generating a list of integers at once. In Python 2, the
range() function generated a list of integers automatically. | https://www.bitdegree.org/learn/python-range | CC-MAIN-2020-16 | refinedweb | 769 | 55.88 |
I'm a beginner in using game engines in general. Do I need to use directx or any 3d graphics API in general, with Unity to develop a game? or just use unity and don't need anything else?
Answer by Berenger
·
Jan 28, 2012 at 12:20 AM
Just Unity. All the rendering part is handled inside Unity itself, using OpenGL (not quite sure about that one !) without you seeing it. If you can use OpenGL functions in scripts when need, it's quite rare. But you don't "juste need Unity", unless you want a game made of boxes, spheres and capsule :p
So it's at least Unity + 3D modeler + 2D.
import directX material??!!
1
Answer
Shader not working in OpenGL (Working in DirectX)
0
Answers
how do i port my unity project to directx 12 in windows 10
2
Answers
Standalone player crashes randomly on startup
0
Answers
Constructing a Cube Primitive using Shader
2
Answers | http://answers.unity3d.com/questions/210934/do-i-need-directx.html | CC-MAIN-2017-13 | refinedweb | 160 | 72.76 |
Hi everyone. Little new here but hope for everyone's help =). I am doing a maze for my Computer Science class. My program needs to read the maze from a .txt file and print the solution after. Im only in beginning stages but that's alright. The problem I'm having is reading the maze into a 2 dim array. I put cout statements to show the result I'm getting....crazy. What is working is the passing of reference variables between functions as requested in the HW I believe once we get this fixed the rest should flow. I've tried everything....from getline to get char. Not sure what I'm missing. Please let me know.
// Maze program ver 1.0 // #include <iostream> #include <fstream> #include <string> #include <cassert> using namespace std; //Read Maze function void readMaze(string maze1[][100],int &rows, int &cols) { // Reads in the maze file. ifstream maze_in("maze1.txt"); int i, j; char ch, test; string line; if(!maze_in.is_open()) { cout << "Can not open file..." << endl; } maze_in >> rows; maze_in >> cols; //for (i=0; i<=rows; i++) { // Added to test first 2 rows for (i=0; i<=2; i++) { for (j=0; j<=cols; j++) { maze_in.get(ch) >> maze1[i][j]; // Why does get(ch) produce stupid results // Used to debug where maze chars are in the 2 dim array cout << "r=" << i << " c=" << j << " value=" << maze1[i][j] << endl; } // Used to debug as well cout << endl; } cout << "rows = " << rows << endl; cout << "cols = " << cols << endl; } int main() { // Original Maze string mazeIn[100][100]; // Solved Maze string mazeOut[100][100]; //Maze size int rows, cols; //Loop variables int i, j; //other // Call Read Maze function readMaze(mazeIn,rows, cols); return 0; } | https://www.daniweb.com/programming/software-development/threads/153073/maze-homeword-question | CC-MAIN-2018-43 | refinedweb | 285 | 82.75 |
Brian Beckman: Don't fear the Monad
- Posted: Nov 22, 2007 at 10:28 AM
- 101,157.
Hat = Awesome^2
Brian Beckman * Hat = Awesome^3
Thus this video = Awesome^3
Cheers Charles. This looks REALLY good.
So let me try to comply, and just to be really clear I'll do an example in C#, even though it will look ugly. I'll add the equivalent Haskell at the end and show you the cool Haskell syntactic sugar which is where, IMO, monads really start getting useful.
Okay, so one of the easiest Monads it called the "Maybe monad" in Haskell. In C# the Maybe type is called Nullable<T>. It's basically a tiny class that just encapsulates the concept of a value that is either valid and has a value, or is "null" and has no value.
A useful thing to stick inside a monad for combining values of this type is the notion of failure. I.e. we want to be able to look at multiple nullable values and return "null" as soon as any one of them is null. This could be useful if you, for example, look up lots of keys in a dictionary or something, and at the end you want to process all of the results and combine them somehow, but if any of the keys are not in the dictionary, you want to return "null" for the whole thing. It would be tedious to manually have to check each lookup for "null" and return, so we can hide this checking inside the bind operator (which is sort of the point of monads, we hide book-keeping in the bind operator which makes the code easier to use since we can forget about the details).
Here's the program that motivates the whole thing (I'll define the Bind later, this just to show you why it's nice).
class Program
{
static Nullable<int> f(){ return 4; }
static Nullable<int> g(){ return 7; }
static Nullable<int> h(){ return 9; }
static void Main(string[] args)
{
Nullable<int> z =
f().Bind( fval =>
g().Bind( gval =>
h().Bind( hval =>
new Nullable<int>( fval + gval + hval ))));
Console.WriteLine(
"z = {0}", z.HasValue ? z.Value.ToString() : "null" );
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
Now, ignore for a moment that there already is support for doing this for Nullable in C# (you can add nullable ints together and you get null if either is null). Let's pretend that there is no such feature, and it's just a user-defined class with no special magic. The point is that we can use the Bind function to bind a variable to the contents of our Nullable value and then pretend that there's nothing strange going on, and use them like normal ints and just add them together. We wrap the result in a nullable at the end, and that nullable will either be null (if any of f, g or h returns null) or it will be the result of summing f, g, and h together. (this is analogous of how we can bind a row in a database to a variable in LINQ, and do stuff with it, safe in the knowledge that the Bind operator will make sure that the variable will only ever be passed valid row values).
You can play with this and change any of f, g, and h to return null and you will see that the whole thing will return null.
So clearly the bind operator has to do this checking for us, and bail out returning null if it encounters a null value, and otherwise pass along the value inside the Nullable structure into the lambda.
Here's the Bind operator:
public static Nullable<B> Bind<A,B>( this Nullable<A> a, Func<A,Nullable<B>> f )
where B : struct
where A : struct
{
return a.HasValue ? f(a.Value) : null;
}
The types here are just like in the video. It takes an "M a" (Nullable<A> in C# syntax for this case), and a function from "a" to "M b" (Func<A, Nullable<B>> in C# syntax), and it returns an "M b" (Nullable<B>).
The code simply checks if the nullable contains a value and if so extracts it and passes it onto the function, else it just returns null. This means that the Bind operator will handle all the null-checking logic for us. If and only if the value that we call Bind on is non-null then that value will be "passed along" to the lambda function, else we bail out early and the whole expression is null.
This allows the code that we write using the monad to be entirely free of this null-checking behaviour, we just use Bind and get a variable bound to the value inside the monadic value (fval, gval and hval in the example code) and we can use them safe in the knowledge that Bind will take care of checking them for null before passing them along.
There are other examples of things you can do with a monad. For example you can make the Bind operator take care of an input stream of characters, and use it to write parser combinators. Each parser combinator can then be completely oblivious to things like back-tracking, parser failures etc., and just combine smaller parsers together as if things would never go wrong, safe in the knowledge that a clever implmenetation of Bind sorts out all the logic behind the difficult bits. Then later on maybe someone adds logging to the monad, but the code using the monad doesn't change, because all the magic happens in the definition of the Bind operator, the rest of the code is unchanged.
Finally, here's the implemenation of the same code in Haskell (-- begins a comment line).
-- Here's the data type, it's either nothing, or "Just" a value
-- this is in the standard library
data Maybe a = Nothing | Just a
-- The bind operator for Nothing
Nothing >>= f = Nothing
-- The bind operator for Just x
Just x >>= f = f x
-- the "unit", called "return"
return = Just
-- The sample code using the lambda syntax
-- that Brian showed
z = f >>= ( \fval ->
g >>= ( \gval ->
h >>= ( \hval -> return (fval+gval+hval ) ) ) )
-- The following is exactly the same as the three lines above
z2 = do
fval <- f
gval <- g
hval <- h
return (fval+gval+hval)
As you can see the nice "do" notation at the end makes it look like straight imperative code. And indeed this is by design. Monads can be used to encapsulate all the useful stuff in imperative programming (mutable state, IO etc.) and used using this nice imperative-like syntax, but behind the curtains, it's all just monads and a clever implementation of the bind operator!
The cool thing is that you can implement your own monads by implemnting >>= and return. And if you do so those monads will also be able to use the do notation, which means you can basically write your own little languages by just defining two functions!
but i must say this.. saying something is easy and simple and not scary does not make it so
also i still have a problem seeing this as generaly useful.. i do see it useful, and very much so, for stuff like linq and math and the like, but for general programing? im a grassroot programmer (sorta, i do design too, its a small company) and i just have a hard time seeing how one whould write a whole program in something like f#.. how do you do ui(say a textbox) without mutable state? or something like an iterator? i just dont get that.. now i know that you can declare stuff as muteable in f#, but that makes it "less pure" right? but how whould you do that in a pure functional language? ofcourse that does not mean there is no way to do it
then again perhaps that is not the point at all, but it seems from the jaoo vids that everyone "in the know" thinks that imperative is crap and everything should be written in functional languages.. i just dont.. agree
because as anders said in another video: imperative languages are a superset of functional
also on a final note(my post is starting to get long) for me, its kind of ofputting when someone says that it impossible to make mistakes.. if there is but one universal truth it must be "there are no silver bullets", so if a claim is made that no mistakes can be made, one of two things must be true:
1. the statement is false, errors can be made
2. the language/technique does not allow anything to be created, as all created thing can potentially contain errors.
now i realize that brian does not mean all errors but still, more clarity as to what errors he does mean is needed for me
in all the interviews where functional programming is mentioned the same thing keeps popping up: "there can be no errors as long as you follow such and such rules" but.. how can you be sure that the rules have been followed? is that trivial? is it even possible? is it also trivial to express your problem in such a way that they adhere to these rules? i somehow doubt that..
the kinds or errors that can be avoided and the ones that cant, thats is something that for me atleats need to be elaborated alot more..
none the less, its a great and interestign video
i found this blog post
that really tries to explain functional programing in terms of c#3, something that for me at least is much easier to understand
i havent read all the parts yet but everyone who has trouble understadning this functional stuff should check out that post
You use a monad to model the mutable state!
Btw, F# isn't purely functional, so you would just use standard .Net functions, but if you do want to understand how the purely functional langauges do it, read on!
Basically, how would you do IO in a purely functional language? Well it's tricky isn't it? You need to ensure that functions only depend on their inputs, so how would you go about reading a line of text from the terminal, say? You could do something like this:
getLine :: World -> (String,World)
Basically a function that takes in the "World", and returns a string and a new World (one in which the input buffer of your computer contains a couple of characters fewer). This is just a semantic model, obviously the compiler doesn't actually pass around the whole world! So it's just a trick that makes "getLine" behave like a real function, even though it reads from the terminal.
Then you would just pass this new World into the next IO function which returns the next World and so on. Of course, there's an obvious problem here. What happens if you accidentally pass in an old World into a function? Oops! We blow up! There's no way of actually storing the whole world, so this only works if the "World" is just some abstract "token" that we pass around to make our semantics hold. If we use an "old" world then we need to retrieve a state of the world that no longe exists!. The bind operator (>>=) would be in charge of passing the World value from action to action. So as we compose actions together using >>=, we ensure that we always pass along the "new" World to the next monadic value down the line, and thereby guarantee that there is no way to use an old "World" value. Note that "getLine" is a value which represents the action of reading from the terminal, it doesn't actually do anything (it just models it, sort of like a shell script - they're just completely inert sequences of characters, you need to actually run them before they do anything. In Haskell, only the compiler knows how to run IO actions, so to the programmer everything is perfectly pure).
Here's how a simple hello world program looks in Haskell without syntactic sugar:
main = getLine >>= ( \ name ->
putStr ("Hello, " ++ name ) )
So first we grab the monadic value "getLine" and compose it with the lambda on the right (see the video). The >>= is implemented so that the "putStr" function gets passed the World that is returned by the getLine behind the scenes, but the user never has to see the World being passed around. All that is hidden by the bind operator!
Here's the version with syntactic sugar:
main = do
name <- getLine
putStr ( "Hello, " ++ name )
This looks very similar to any imperative language right? So voila! We have successfully embedded IO in our purely functional language, by hiding the "World passing" inside a monad! This is pretty much the main reason why monads are such a big deal in purely functional lanuages, but as we have seen there are many other monads as well. One of the more interesting ones is the ST monad. This monad just models mutable references. The difference between this one and the IO monad is that a value in the ST monad can actually be run by the programmer, which means that you can write functions that use mutable state, but as long as that mutable state doesn't leak out (the compiler checks this) you can wrap them up behind a pure function interface (using a function called "runST")..
Yes, I think you're correct (if I understand what you mean). But I think it's worth pointing out that monads are not just for encapsulating things which don't look functional. LINQ is eminently functional, for example.
Monads is like a design pattern that can be used to model certain libraries. Some of these libraries may model imperative features (IO, state, etc.), but some of them do perfectly ordinary things that just happen to fit monads very well (Parsers, queries, etc.).).
So we know that F# isn't purely functional because it's not lazy. That's ok, the monad style in F# / C# / VB is still very useful for compositional designs, even if the languages are not "pure." Some people call F# and ML and OCaml and Scheme, etc., "almost functional." 80% of the time, there won't be any difference between pure-functional and almost-functional. But you have to be careful at the fringes.
You can build lazy libraries and such and get all the way to pure functional if you need it. Heck, you can implement Haskell in F#, so there
There's lots more to say about this, so stay tuned.
Keep them coming as it is great to see how functional programming techniques are being adopted and explained in the wider scope
but does that not mean that "IO a"/"M a" have state?
ok but lets say you wanted to get the current time of brians clock for example.. that isnt something the compiler can know about (right?) how can that be done in a pure functional language? (im not saying its impossible, i just dont get how thats done)
or is it conciderd pure if the state is just completely encapsulated? in that case an can an object that has some private variables and public methods be considerd "pure" from a functional standpoint?
ok, im not sure what you mean by referential transparency but im goning to have to take your word for it
it should atleast be easier to dicepline your self to follow rules that the compiler doesnt care about, than breaking rules in the language. that is, decide to not use mutable state in a language that allows it (imperative) than try to use mutable state in a language that does not allow it (functional) right? (again i dont know, but it seems that way to me
More carefully, it means that if you define a variable or a function with an equation, then you can always substitute the right-hand-side of the definition any time the variable or function appears anywhere in an expression. If you define
fact(n) = (n <= 0) ? 1 : n * fact(n - 1)
then ANY place you see fact(x) you can just subtitute (x <= 0) ? 1 : x * fact(x - 1). Notice how I slyly slipped in the change of formal variable? The names of lambda variables don't matter so long as they don't collide with free variables.
Also notice how this would get messed up if there were side effects going on against internal mutables, like the stateful machinery inside "random:"
nonreftran(x) = (x <= 0) ? 1 : random() * x * nonreftran(x - 1)
You can't replace every reference to "nonreftran" with its definition and be sure to get the same answer ever time. Even evaluation isn't referentially transparent always:
runaway(x) = concatenate(x, runaway (x + 1))
The side-effect on the last one would be "eager evaluation" of runaway(x + 1). If that's evaluated lazily, then
takefirst(10, runaway(0))
is safe. If eagerly, then it runs on. That explains why you really can only do "almost functional" programming unless you have lazy evaluation. Under eager evaluation, most of the time you're functional <-> referentially transparent. But sometimes you're not and you "fall off the boat.". So as long as youre just building values that represent impure actions your safe. So >>=.
By modeling an IO action which represents the action of reading the value of the clock from the operating system. Again, think of it as a shell script. You can write a text string which represents the bash script that reads from the clock, right? Same thing here. The IO actions are just abstract values that represent the impure things, they don't actually do impure things (they need to be run in order to do something, and as I've said, the programmer has no way of doing this, only the compiler does).
So in order to actually do anything with the value of the clock you would build a value of type IO a that represents the action of reading the time from the OS, and passing it to a pure function to do some calculations with it. That pure function is just regular functional programming, but at "the bottom" there's a layer of IO values which represent the impure bits.
And again, refer back to the original example. This looks just like writing imperative code in any language, so it's not like it makes it any more difficult to use (you can pretend that the IO monad is just "the impure parts of Haskell" and be perfectly fine with that, but once you realise that it's actually just a way of building up values which represent impure computations, you can do much more cool stuff because now you can pass these values around in data structures, pass them around to general functions that work over any monad etc.).
It's just that you're guaranteed that a function only depends on its input. C# doesn't guarantee that, which means you can never strictly speaking call, for example, a virtual function (since that's unknown code) while within a context that requires purity (like a LINQ expression, or a transaction). In practice you just ignore it and hope nothing goes wrong, but it's much nicer if you can actually be sure that nothing will go wrong by having a language where side effects would be visible in the types.
Again, you can model imperative programing within a pure context. There are cases when mutable state is necessary for various algorithms, so in Haskell you would do this by building up a value in the ST monad, and while you're doing this you can use mutable variables, mutable arrays etc. Then at the end when you've composed all of these smaller ST actions ("readSTRef", "writeSTRef", etc.) into a large ST action, you pass it to a function called "runST" which returns a pure function. The compiler checks that the action you pass into runST doesn't "leak" any mutable state, so it's perfectly legal to have local mutable state, as long as it doesn't leak out.
EDIT:
I should clarify all of this by saing that in my opinion, the practical everyday-programmer-Joe implications of using a pure language these days are fairly non-controversial.
also, couldnt you have a random function and include it some other function in say, haskell? then that whould not be referentially transparent right?
i dont see how this is bound to the language or language paradigm in question
ok.. i understand i think
I think it was a good explaining of Monads and remembered me a little bit of the Math1 course that I did in my first year at uni.
Well, it's a bit like saying that a language is strongly typed. You can adhere to types in C and never do any casts, but as there is nothing stopping you from interpreting a float as a pointer, say, it can not be said to be strongly typed.
Math.Sin could, for all you know, on the ten thousandth invocation decide to format your hard drive!
So if a language has referential transparency that means that functions always return the same value for the same input. Now clearly this isn't true in C#, say, as a function can contain reads and writes to global memory right? So you lose the property that functions are referentially transparent. Right? It is not true that a function in C# always returns the same result for the same inputs. It may be true in certain cases here and there, but it doesn't mean it holds true for the language in general..
Nope, you can't. Random numbers have to be dealt with differently in Haskell (precisely because the language guarantees that every function must be referentially transparent). One way is to generate an infinite lazy stream of random numbers up front in the IO monad, and then pass that list of random numbers into whatever function needs them.
Remember that random numbers typically aren't random at all. They're a sequence of pseudo-random numbers where the next one can be computed from the previous one (plus, possibly, some extra values). So you can have a function like:
random :: RandomGenerator -> ( Double, RandomGenerator )
And as you can see this looks very much like my IO example above (in fact, all so called "state monads" look like this), so you can wrap this "random number supplier" behaviour in a monad too!!
ok.. but arent all code just a model of actions? the code it self desnt do anything, it just pastes together peices of assembly code that does the actuall stuff right?
it appears to be a question of where one draws the line of abstraction.. lets say i write a program in c# that contains two asseblies.? (hope that made sense)
insted of a shell script, can you think of these things we glue together as calls to some external thing that is not functionally pure and can contain mutable state?
so functional programming is dependent on these other non functional things or shell scripts as you call them, to do stuff?
and these impure actions are not part of the language?
its a bit confusing because it seems that monads represent these impure actions and monads are a part of the language but the actual impure stuff is not.. im not sure i understand how that works, but is that a correct assesment?
what if you want to add something new that is mutable in nature? like the position of a guy in a game for example, whould you write the mutable part of the game(that is the state of the game world) in something inpure (or in an impure way) and then "model" various things in the world using pure functions? (like a gravity function or something)
ok but at some point i actually do need to describe the thing that i want done right? in other words, i need to write that shell script that reads the current time from the os. and that cant be done in a pure functional way as i understand it.. am i correct?
lets say i want to keep track of how many time some arbitrary thing has happend.. the os has no idea about that. whould one write a "shell script" (or impure c# method) to track that then?
ah.. so functional programming is dependant on this lower level that does all the dirty work of mutable state so to speak?
ok.. when you say "visible in the types" do you mean that some other type is returned if the function has a side effect?
so there is mutable state in functional programming but its very tightly encapsulated?
i must say that the most confusing thing about functional programming and functional languages is this notion that there is no mutable state.. this more and more seems to be a truth with modification to me.. there is mutable state, but its just encapsulated, right?
one last thing (again sorry for the loooong posts)
i just want to say that i have no religious affinity to imperative languages
yeah i can buy into that
ok.. im goning to go out on a limb here.. so then random numbers have a diffrent type than say a regular int?
yeah.. since mutable state is forbidden in functional languages i see why monads that apparently can create mutable state are useful, because its hard to do stuff entierly without mutable state (you gotta agree on this one right?
i still have a problem understanding how monads can have their cake and eat it to.. how they can have (or appear to have) mutable state and still not violate any rules of purity..
btw i found another blogpost trying to explain functional programming in terms of c#3:
Well yes, but I'm talking about actual values, not source code. E.g. in C you might have something like:
char* readTheClockAction = "time /t"; // use DOS command
readTheClock is now an abstract representation of the action that reads time. So you can undsrtand how we can use various string processing functions to splice together lots of these and get all sorts of "impure" behaviour into a little "script" right?
Where this shell script analogy falls apart is when you actually want to interact with the results of these impure values, but monads can deal with this just fine.
As you know the >>= operator takes a function on the right hand side. The parameter of this function would be a variable that gets bound to the result of the action on the left hand side. For example:
getClockTime >>= \ t -> putStr ( "The time is " ++ show t)
So, "getClockTime" is one of these little "scripts" (or "actions" as they are most often called), and so is "putStr". The >>= is just a really intelligent operator for pasting scripts together, in that it can bind a variable name to the output of the first action. This means that the perfectly pure operation of prepending "The time is ", and converting the time to a string ("show t") can be embedded within the script. So "show" and "++" are both completely pure functions.
And again, just for clarity, here's the "nice" syntax for the above (this time without the layout dependent syntax, just to make it look even more familiar, with curly braces and all!)
do {
t <- getClockTime;
putStr ( "The time is " ++ show t );
}).
No, because the second assembly calls impure functions (in the first assembly) so it too would also need to be impure. At least for the IO monad.
Calling an IO function is impossible from a pure function. The only thing you can do with IO actions is to combine them into larger IO actions. Which means that the only place you can use an IO action like getClockTime, is from within another IO action.
For the ST monad (which only give you access to mutable variables, no other IO) you can wrap it up into a pure function (the type system guarantees that this is safe - so it's still referentially transparent), and in that case yes, you can write little snippets of "impure code" (again, it's really just monadic data that looks like impure code, and models it) here and there, and then wrap it behind a pure interface. The following nonsensical example illustrates
-- increment the contents of a reference
inc ref = do {
val <- readSTRef ref;
writeSTRef ref (val+1);
}
plusOne :: Int -> Int
plusOne x = runST ( do{
ref <- newSTRef x;
inc ref;
result <- readSTRef ref;
return result;
} )
plusOne is completely pure, even though internally it uses mutable variables (though there is no good reason for it in this case!). runST has a really clever type based on something called "rank 2 polymorphism" (ignore it for now) which ensures that it's impossible for any of the "mutable stuff" to "leak out" and result in referential transparency being violated. plusOne is thus a completly legal pure function.
A bit handwavy:
It's a bit like XML in C#. The language itself has no way of actually dealing with XML natively, but that doesn't mean you cant do XML stuff, right? So you can use various XML libraries to produce XML documents, even though the language has no notion of XML. As far as the language is concerned, all it's doing is dealing with data (strings in this case).).
So it is a bit of a trick, but an extremely useful one, since it lets us have our cake and eat it to. We can remain pure as the code we write to do IO is actually just composing data values together (without actually doing anything) that the runtime system (written in C, say) can then "interpret". But at the same time we get a very convenient syntax that looks like imperative code for doing the typically imperative tasks. And again, lots of Haskell programmers just think of IO as "impure Haskell" and don't even care that it's in fact completely pure through a clever semantic trick.
I should point out that the runtime doesn't actually do any runtime interpreting. The compiler spits out optimized native code just like in any other native language, but it's a useful semantic).
However, if you really do want to have mutable things (and sometimes you do), then both the IO and ST monad contains the concept of mutable references that you can use. And as you say, you would update this reference cell using pure functions
Yes exactly. At some point the program actually needs to do something to be useful. This is why I said that purely function doesn't really mean "no mutable state ever" anymore, it just means "principled use of mutable state, that is visible in the types" (see below).
The key issue, though, is that there is some way of distinguishing between the "actions" that can model impure concepts (like mutable state) and functions that are guaranteed to be referentially transparent.
Exactly. Take the following:
getLine :: IO String
aLine :: String
getLine has the "IO" type constructor, so we know for a fact that getLine may do IO, and furthermore there is no way of extracting the value of getLine from within a pure function (you can only do it from within another IO action). aLine is just a string however, and you can be sure that aLine will never ever change, it will always refer to the same string.
So the types make it absolutely clear where side effects are.
Precisely. You can use mutable state where you need it, but you can never use it by accident. The languages keep pure things and impure things entirely separate, and the type system tells you exactly what kind of effects various things have.
This means, for example, that the compiler can be certain that a given function can be executed safely on a different thread (because it is referentially transparent, so it can not possibly interfer with anything else). In C# the compiler can make no such assumptions. Take the TPL for example (see channel 9 videos), it absolutely relies on the fact that tasks that you pass it won't interfere with each other, but it has no way of letting you know if this is not the case! So there's ample opportunity to make devastating concurrency errors there (and we all know how fun those are!), and the compiler can't help you, because the language has no way of recognizing which functions have side effects, and which don't.
Another place where this is crucial is for STM (see channel 9 vids on that). Basically it has to do with transactions for communicating between threads with mutable state (yes, mutable state in Haskell!), if a transaction fails it may have to be retried later, but if the transaction contains a call to "launch_missiles", then running that transaction again could have catastrophic international consequences! In Haskell there is thus a restriction that only functions can be called within a transactions, no IO actions, which completely avoids such problems (with static guarantees).
Other benefits include things like the nested data parallelism, where many of the crucial steps for getting this extremeley promising way to write parallel applications fast relies entirely on purity. It can not work in an impure setting (see Simon Peyton Jones et al. on NDP in Haskell for that; there's a google video talk about it too).
ok so its these "actions" (that seem an awful lot like functions with the exception that they can be impure) that in a sense "drives" the program? can one se the program as one big action that combines a bunch of actions and sometimes call pure functions?
in a way it seems as this bottom layer is actually at the top:P). :O
is it this "rank 2 polymorphism" that prevents that from happening?
ok, i think i get the concept.. but i still dont really understand how these actions can be "executed" by a pure function without the execution function becoming inpure
how you actually do this in practice is also still a bit of a mystery but im going to research that? but i do understand what you mean when you say that he has a new position, he is no longer at his old position but his old position has not changed, he now has a new position so the position it self is not mutable.. but his, and the worlds, reference to what position the player is located must have changed right? you would have to assign his new position to something in order to keep track of it right? and that something surely must be mutable?
<rant>then why cant everyone just stop saying that there is no mutable state in haskell or functional programming in general? its so very confusing
</rant>
sorry just had to let of a little steam at the functional programming community in general?
That's correct.
Some impurity can be encapsulated. It's true that if you call an IO action you too must be an IO action. It's "contagious", you could say. That's why you should be careful to structure your program so you have a thin "layer" of IO at the bottom, and then this IO layer calls into your pure "core" of the program.
No well designed program mix IO and algorithm anyway, so it's not really a big problem, in my opinion, but the system will force you to keep this separate.
Mutable references (the ST monad) can be encapsulated, in that you can "run" the action and turn it into a normal function. But IO has no "run function".
Well variables never change their meaning within the currrent scope. If you call a function that does something depending on the player's position, than this position can be different every time you call the function. Basically imagine something like this.
movePlayer :: GameState -> Input -> Gamestate
I.e. the function takes the "state" of the game, and the input (which is passed in by the IO layer) and computes a new game state. The old game state still exists if you want to use it, this function just computes a new game state from the old one. Then next frame you do this again, and again and again, and each frame you compute an entirely new game state from the previous one. You never need to mutate anything. Now under the covers the compiler will probably reuse most of the gamestate and not actually make a full copy each frame (as that would be slow), but semantically there is no reason to start thinking in terms of mutation. (you'd also have a function like "renderGame :: GameState -> IO ()" that you have to call each frame)
Probably because this actually used to be true before some smart people figured out that monads could be used to do all sorts of "impure" things in a pure setting. Also because it's a nice short description of something that's bound to be incomplete when you look at the details.
Well the whole purpose of the STM monad is to write to mutable variables with a transactional semantaics for concurrency, so you can do those things becayse the STM monad guarantees that those things can be rolled back without causing problems. But aside from the specific things that the STM monad gives you (reading and writing to transactional variables) you're not allowed to mix in anything impure (like IO). I think there are plans to add hooks for transactional IO though, so you could write DB access etc. too. Not sure about that, but right now it's primarily about avoiding locks for concurrency.
Will we ever see a Microsoft backed version of Haskell for .NET?
Nope. As witnessed by LINQ in C# for example. This happens to be even more useful in pureley functional languages at it solves the "problem" of impure things like IO and side effects too, but there's nothing stopping you from using it for some of its other benefits in an imperative language.
Bind is special because it can compose a monadic value M a, with a function a -> M b, and produce an M b. We can thus have a totally opaque monadic value M, (i.e. we may not necessarily have a way of actually *directly* accessing its internal structure outside of the bind function -- sometimes we don't want a function of type M a -> a, for the same reason classes have private members), yet we can still use it in a controlled way by binding the value that is "wrapped" by the monad on the left hand side, to the parameter of the lambda on the right hand side in >>=. So the user of our monad can still directly access the content of the monad by binding a lambda to it, and doing whatever they want to do in the body of the lambda, but the author of the bind function has lots of power to determine precisely when and how this lambda gets called.
Note that this does not need to be a trivial operation. In the list monad, for example, the bind operator will not just pass along a single value to the lambda on the right, but every single element of the list (it then concatenates the result to end up with a list, rather than list of lists).
For example, the following Haskell code demonstrates a simple use of the list monad:
[1,2] >>= (\ x -> [3,4] >>= (\y -> return (x,y)))
Will give
[ (1,3), (1,4), (2,3), (2,4) ]
x is bound to every element of the first list, and then for each of those elements y is bound to every element in the second list, then in the innermost lambda a pair between these two elements is returned.
So it's not just a matter of simply unwrapping a value trivially, there can be much more logic behind it. (btw, the list monad starts to sniff around in the area of why LINQ is monadic).
Another example is a logging monad, where the >>= operator is responsible for passing along a logging output, so that the code you write doesn't need to worry about threading along some logging data through all its functions, that can be hidden by the bind operator.).
Consider, for example, how you would write a logic truth table of arbitrary size. Well with the list monad we just want to "shove"/"bind" each element of the list [True,False], N times in sequence, which will give us every combination of True and False for N variables. As it happens, there's a standard function called replicateM that will help here (it just replicates a monadic action N times, and returns a list of the results of "shoving"/"binding" the monadic values in sequence). So if you understand the list monad, then constructing a truth table is trivial:
truthTable n = replicateM n [True,False]
This produces a list of rows, where each row is a list of Bools of length N.
So, one of the benefits of bothering with monads, is that we can write all sorts of cool functions that work over any monad, which helps us avoid boilerplate code. Needless to say, replicateM will do something entirely different for IO monads, parser monads, etc. etc. The reason it can be used for vastly different problems is because it operates over a common structure (with the overloaded methods >>= and return), monads!
Once you strip off the "M," you've lost the data (or side effects or whatever) you're trying to track. That's why "return" and "bind" get you into the Monad, but there's no way to get out of the Monad. Once you're doing clock-arithmetic (mod by 12), you can't get back out (was that "5" originally a "17?")
In fact, you can create your own LINQ bindings -over-whatever by simply implementing the Standard Query Operators (see, for example, . These are just static "extension" methods -- methods whose first argument is an instance of a certain type. Then the C# / VB / F# syntax will "just work" over your new types because the languages recognize these kinds of methods.
You will have implemented your own monad, plus lots and lots of higher-order convenience operators, with LINQ! I would recommend starting with the trivial monad -- the monad that does nothing but adhere to the type discipline. But Sylvan has given you enough meat on the bones that you should be able to implement your own list monad and see the result of your equivalent to
[1,2] >>= (\x -> [3,4] >>= (\y -> return (x,y)) )
In practice though I am confused.
(the previous video with Monads that BB did on channel 9 was really interesting. I remember that he had told in that video about the clock analogy and I remember trying to figure out what he was talking about. I now do understand the concept but to be 100% honest I simply don't get the code stuff.)
I just admire the concept of treating functions the same way as variables/data.
I guess that there is a trilogy there that needs to be closed. One more video about Monads, Plz. That's an order
is it possible to mix c# and f#? (I'm new to this, obviously)
Yes, since both C# and F# are full "citizens" of .NET, you can call methods in one from the other and back very easily.
I would say that "composability" or "compositionality" is THE way to structure libraries. Monads aren't the ONLY way to build-in compositionality from the outset in a design, but they're a very common pattern, broadly applicable, fully understood.
"Why Functional Programming Matters,"
"Why Haskell Matters,"
I still don't think I understand monads and functional programming, my lack of math background is complicating things. But I totally get the complexity built on simplicity to ensure composability part, that is kind of my whole bid.
simplicity meaning: "easy to decide" as opposed to "easy, because I don't have to decide". so I guess functional programming will still require a very particular mindset to be successfully employed.
I am really looking forward to seeing more great interviews like this one.
You can bet on it. Next up will be a deep dive into pure functional programming (and why, at least from the interviewee's point of view, it's the only way to go) with another expert in the domain and great personality.
Stay tuned.
C
The n-Category Café
featuring YouTube videos.
"All nouny, no verby"
Cool!
Superb!!!
To get into full, pure functional programming: the only game in town is Haskell (
C# 3.0, VB 9, and F# all three now have first-class functions (lambda expressions), so you can experience many of the benefits of functional programming in any of those three, and F# has a syntax and a "look and feel" closer to Haskell, especially for purely sequential programs. If you've done any Scheme programming, then you will breathe a sigh of happiness with any of these three languages, now with LINQ and lambda. I don't have any experience with Erlang, so I can't chime in there..
You have to have some Haskell knowledge though..
These are great questions. The identity is in there so we can "lift" values into the computation (that is, the monad) without changing them. No return, no general way to get into the monad in the first place.
Associativity makes monads good for modeling ordered collections like lists. It would be terrible if [a] ++ ([z] ++ [c]) weren't guaranteed to be the same as ([a] ++ [z]) ++ [c]. Imagining a ++ operator that eats its left-hand side if it's out of lexicographic order, then
[a] ++ ([z] ++ [c]) = [a] ++ [c] = [a, c]
([a] ++ [z]) ++ [c] = [a, z] ++ [c] = [a, z, c]
This bogus ++ is not monadic because it's not associative, and it's a good thing to exclude it from our general (but not too general) discipline.
There is probably a deeper reason (hello, categorists
Since you mentioned Google, map-reduce, which is the backbone of their massively distributed, parallel infrastructure, is a composition of "reduce", which applies some given aggregate, associative calculation like sum or average or standard-deviation to a recursive data structure; with "map", which applies arbitrary transformations to a recursive data structure. It's about as functional and real-world as it gets.
There are tons of other examples. Some in the financial quants industry are using Haskell programs to model derivatives yields. I know the crypto community is going whole-hog for Haskell. Don's blog ( ) will be a great place to look at real-world applications of F#. Erlang is all over the communications industry. It's endless
EDIT: I wanted to add a side comment: one reason some mission-critical applications are going with Haskell is that if you go "all the way" to pure functional programming, where all side-effects are accounted for in type signatures, then more proofs of correctness become available. In certain cases, this is required.
But, on the downside, you can't just plunk down a "print" statement any-old-where to help you debug a Haskell program. Any computation that might EVER print MUST be in the IO monad. So if you're ever going to plunk down a print, you must plan ahead for it or rewrite for it. In the "impure" world of .NET, with C#3.0, VB9, and F#, you have many of the benefits of functional style, but you can "cheat" where necessary or useful and do side effects from anywhere.
publicclass
}
public static IMonad<B> Bind<A, B> (IMonad<A> a,
Func<A, IMonad<B>> fun)
{
if (fun.IsNull ()) throw new ArgumentNullException ("fun", "'fun' can not be null.");
return Unit; }
}
Now back to work. First I push a string into my Monad and I want, at the end to have byte collection in my Monad that represents the charachters of my string. How about this:
var var1 = "ABCD...MONAD!"
.Unit ()
.Bind ((string s) => s.ToCharArray ().Unit ())
.Bind (ca => (from c in ca select Convert.ToByte (c)).Unit ());
What is the type of var1? It is IMonad<IEnumerable<byte>>. And you see another interesting aspects of Monad here: Composability! Here we have 3 type for the type variable of our Monad. But as long as we are IN the Monad we can compose any kind of computations.
Now assume we have two Monads and we want to apply a function to the inner value of both monads. How can I pull out the values from these Monads to perform my function application? I can not pull out the inner part of monads. But i can still use their values in my computation by using closures! For example I have to Monads that contains numbers and I want to have the multipluy value of them:
var ma = 10.Unit ();
var mb = 20.Unit ();
var mr = mb
.Bind (x => ma.Bind (y => (x * y).ToString ().Unit ()));
As you can see (actually as I can see! Because writing this code make me feel a lot better about Monads - as an Imperative programmer - yet there are a lot of improvements possible to my Monad set of utilities) anything that we do in normal imperative code is possible by using this Monad. What is the good part? You can not change the Monad anywhere out of the Monad. So actually the state of you whole program that is out of the Monad is untouched. Another thing is that the Monad is immutable. Every action on a Monad produce a new Monad of that kind.
Consider a data structure that has Monads as members. You can not modify these members! Even if the data structure itself is not a Monad! See this little bit of it:
var nv = new { a = 10.Unit (), b = 20.Unit () };
var mnv = nv.Unit ();
mnv = mnv
.Bind (j => new {
a = j.a.Bind (k => (k * 2).Unit ()),
b = j.b.Bind (k => (k * 2).Unit ()) }.Unit ());
It was very interesting to me that by putting a Monad of this type as a member of the root class of a hierarchy; that hierarchi of classes became immutable! (At least for changing that member!)
I very much agree with your observation that bind is not a very good choice when you want to explain the nature of the monad laws (i.e., the monoidal structure). Instead (as you show), it's the Kleisli composition that makes it obvious.
I wish more people would use your line of explanation since it makes the monad laws look very natural.
BTW, I think strings are a good example of a monoid than everyone has encountered.
-- Lennart
Thankyou! I have been more than happy by your comment!
Just I'v discovered a bad thing in my code: using Closures! I discovered this when using a LINQ query against a set of objects (a library for handling directory tree of my html templates for some work and extracting their content and publishing via a HttpHandler). I have changed one of objects that was placed inside the where clause somewhere (in another business class - ofcourse that was a bug; but what if it wasn't?), and the resault was not what expected!
So I write another method for combining two monads and getting a third one; named Transform (I do not know this name is proper. I am a "thin client" of Haskell and Monads!).
It seems now a better solution for composing two (or more monads). It seems to me closures are a bad thing in this context, because they pass the boundries whitout any footprints.
(Code is here.)
Cheers!.
Yup, I was wrong about this. When I tried to prove it, I just ended up with the State Monad. I WAS WRONG !!!!.
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads | CC-MAIN-2014-52 | refinedweb | 8,745 | 67.89 |
GraphQL: Understanding Spring Data JPA/Spring Boot
GraphQL: Understanding Spring Data JPA/Spring Boot
Let's understand Spring Data JPA and Spring Boot with a practical example.
Join the DZone community and get the full member experience.Join For Free
GraphQL is a query language for APIs. Generally, while making REST endpoints in our APIs, the normal trend is to make an endpoint for a requirement. Let's say your endpoint is returning a list of employees, and each employee has general properties, such as name, age, and address (suppose address is another model mapped to the employee in such a way that each employee has an address). Now, at one point in time, you require data only for their address i.e. a list of all addresses in the database (only country, city, and street). For this, you will require an all-new endpoint in your service.
Here comes the power of GraphQL, which lets you deal with only a single endpoint and that changes its output based on the body of the request. Each request will call the same endpoint but with a different RequestBody. It will receive only the result that it requires.
Refer to the code on GitHub for complete code files. It's a maven project with an H2 database that has data.sql at classpath for database queries. This code rotates around getting a list of all employees from the database.
Now, let's begin with a practical implementation with Spring Boot.
We have two model classes: employee and address with respective getters and setters.
@Entity @Table public class Employee { String name; @Id String id; int age; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "addid") Address address; //......getters and setters....// } @Entity @Table public class Address { @Id @GeneratedValue String addid; String country; String city; String flat; //......getters and setters....// }
To implement the repository, we have the EmployeeRepo as:
@Repository public interface EmployeeRepo extends CrudRepository<Employee, String> { public List<Employee> findAll(); }
Now, GraphQL requires a .graphqls file at the classpath, which it parses and understands the type of request it needs to handle. You will find employee.graphqls in the code. Let me explain that.
It contains:
type Employee{ .......Employee details } and type Address{ ........Address Details }
Here, we are defining the schema of our classes, which will, in one way or another, be returned as a response to the endpoint i.e either it will return all employees, the addresses of all employees, only the names of all employees, etc.
We also defined:
type Query{ allEmployee: [Employee] }
Type of query (a query that will be sent by the client or that will be present in RequestBody) here is returning list of employees.
So, RequestBody to our endpoint will contain a root query as allEmployee.
Let's discuss requests here:
1. Requests that require all employees without their addresses:
{ allEmployee{ name age id } }
2. Requests that require only employee names and the country that they belong to:
{ allEmployee{ name address { country } } }
3. Requests that require only the address of all employees will be:
{ allEmployee{ address { country city flat addid } } }
For an explanation of the service layer of the code, read part 2.
Meanwhile, you can access the full code on GitHub.
If you enjoyed this article and want to learn more about GraphQL, check out this collection of tutorials and articles on all things GraphQL.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/graphql-understanding-with-springdatajpaspringboot | CC-MAIN-2020-16 | refinedweb | 577 | 65.93 |
CodePlexProject Hosting for Open Source Software
I'm looking at how access to the request context is provided in WebApi and I do have an issue with it; I wondered what others thought.
Background:
It's possible to provide a parameter of type HttpRequestMessage OR to "wrap" a parameter in HttpRequestMessage<T> to get access to the request context in the body of your service implemenation. Similarly, for responses, you can either return a void
or object which is turned into an HttpResponseMessage or HttpResponseMessage<T> respectively.
The features blurb highlights the provision this feature over something like WebOperationContext.Current for reasons of testability, and to extent I support this. I certainly agree that static functions are horrible for testability.
BUT.... :)
It does pollute your API. In our case this is particularly problematic because our current system generates documentation for its API by parsing the signatures. Now, it's not a great leap to modify the parsing to understand how to deal with HttpRequestMessage/<T>
and HttpRequestResponse/<T> when it sees them, but it does make me think that something doesn't sit right about the approach.
For example, let's say sit down and design my API - like a good architect, I start with the interfaces with a view to handing them off to my developers for implementation.
I might have something like:
[ServiceContract]
public interface ICalculator
{
int Add(int x, int y);
}
But I just don't know at this stage whether my developer is going to need access to the context. With WebApi as it stands, I'm encouraged to wrap my parameters - but it's ambigous. I could do any of:
int Add(HttpRequestMessage requestMessage, int x, int y);
int Add(HttpRequestMessage requestMessage<int> x, int y);
int Add(x, HttpRequestMessage requestMessage<int> y);
On top of this, I could elect to change the return type to HttpResponseMessage<int>.
All of these are changing the C# interface - even though they don't change the interface of the web service consumer. From a process point of view, it makes it hard to understand whether or not you are making breaking Api changes and to enforce consistency.
I wonder if it would be better to inject an object into my service implementation that I can call to get access to the context like so (this is illustrative and won't compile):
public interface IWebOperationContextProvider
{
WebOperationContext GetCurrent();
}
public class WebOperationContextProvider : IWebOperationContextProvider
{
public WebOperationContext { get { return WebOperationContext.Current; } }
}
public class CalculatorImpl : ICalculator
{
WebOperationContext OperationContext { get { return _contextProvider.GetCurrent(); } }
public CalculatorImpl(IWebOperationContextProvider contextProvider)
{
_contextProvider = contextProvider;
}
}
Neither is totally ideal, but at least the latter doesn't pollute my API. What do you think?
I'm having the exact same issues with context to the current user.
I did the same thing. I made a base class that implements User { get; set; } that returns an IUser built off Thread.CurrentPrincipal.
Still working on how to test it, because I can't seem to get injection working well with StructureMap.
As we integrate Web API with MVC one pattern we are looking at is using a property on a base class that you derive from to give you access to the HttpRequestMessage instance, so that you can write code like this:
public int Add(int x, int y)
{
var host = this.Request.Headers.Host;
…
}
The nice thing about this model is that you don’t have to change your signatures. You do have to derive from a base type though, similar to how you derive from Controller with MVC.
Daniel Roth
Problem is this won't work for testing. I need injection so our unit tests can build out a fake Request object because there is no HTTP context.
You can still do unit testing like this:
var mywebapi = new MyWebApi();
mywebapi.Request = new HttpRequestMessage(…) {…};
mywebapi.MyOp(…);
Sounds good, I can live with property injection.
<HTTP_RANT>
It really depends on what you are using HTTP for and how you design your apis. In your above example you are using HTTP in an RPC fashion to expose a calculator contract. You are taking your implementation and using HTTP as a transport protocol to expose
that contract to be invoked. If you are trying to do that, then I agree that HttpRequestMessage<T> / HttpResponseMessage<T> gets in the way and you may view it as a violation of concerns.
However.....
HTTP is not transport protocol[1], and it is not RPC[2].
I talked about this in more depth at my QCon London talk which you can access
here. Mike Amundsen also has a great article on the problems of trying to use HTTP for other than a transfer protocol here.
HTTP was designed to enable long lived evolvable systems that run for many years. It reduces coupling between clients by exposing resources in a variety of formats to a range of clients and using the uniform interface i.e. standard HTTP methods, headers,
etc. It is an application layer protocol that offers a lot of rich information which clients, intermediaries and servers can use to process the message. From an HTTP perspective that uniform interface IS the contract. Because that contract is fixed and does
not change, we get evolvability. New resources can be added without breaking backward compat. In your calculator example if the signature of the contract changes, all existing clients are broken. If however you stick strictly to the uniform interface that
contract will never change.
Back to web apis, they are a bridge between the HTTP world and your business domain, they are
not the business domain itself. At that bridge there are a whole set of HTTP concerns that need to get addressed like working with HTTP Status Codes, Headers like ETags, and dealing with the content. It is that philosophy that drove the design
of HttpRequestMessage<T> / HttpResponseMessage<T>. At that boundary where you use them they are not a separate concern, they are a
primary concern.
If we go with the grain of HTTP then we expose our system via the uniform interface rather than bleeding our implementation. SOAP for example went against that grain and that is why we have SOAP Contracts, WSDL etc.
That means instead of exposing an ICalculator, exposing a calculator resource. That resource can expose sub-resources which allow access to different aspects of the application. For example doing a GET with form url encoding in the query string with this
uri ".../calculator/adder?value1=5&value2=6" results in a response of 11.
The API implementation
public class CalculatorApi {
private ICalculator _calculator;
public CalculatorApi(ICalculator calculator) {
_calculator = calculator;
}
[WebGet(UriTemplate="adder?value1={value1}&value2={value2}")]
public HttpResponseMessage<AdderResult> GetAdder(double value1, double value2)
{
var result = new AdderResult();
result.sum = _calculator.Add(value1, value2);
var response = new HttpResponseMessage<AdderResult>(result);
//set browsers to cache this forever as it will never change
response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = new TimeSpan(999999999, 0, 0, 0) };
return response;
}
}
public class AdderResult {
public double sum {get;set;}
}
The implementation of the CalculatorApi.GetAdder method delegates to the calculator implementation to do the work. Now a calculator result never changes, so the Cache-Control header is set to a very large MaxAge thus telling clients they can cache it forever.
HttpResponseMessage<T> works perfectly here to allow returning the Sum as well as setting the headers.
This is just one simple example, but a realistic use case where accessing the headers allows the server to give the client special instructions on how to handle the response.
One could go further and decide to embed link headers instructing the client about other resources they can access related to the Adder, like Subtractor, Multiplier, etc.
These concerns as well as many others are completely valid from an HTTP standpoint and do not pollute the API as long as the purpose of my API is to be that bridge.
[1] - - 6.5.3
[2] - - 6.5.2
</HTTP_RANT>
Nice explanation. :)
Thanks :-)
Thanks Glen. I agree completely with what you are saying. In the real case rather than the simplified example I presented here, the concrete implementation is barely more than a protocol transition layer that passes requests through to ActiveMQ
and on to the real business logic. I left that detail out of my sample code for simplicity; I agree you wouldn't want business logic in here.
In this case, I think the root of the problem is that I've inherited a system that generates documentation, jschema and SMD by parsing the XML compiled from the triple slash comments - which is tantamount to reflecting over the interfaces. I can either fix
the documentation generator to account for HttpMessageRequest<T> and friends, or follow the wrap approach you suggested. In the later case this means duplicating all the interfaces just to get a handle on the HttpMessageRequest/Response, which seems
painful in this case as I am effectively wrapping wrappers.
We also have to handle the possibility of flash/javascript clients running in browsers that intercept non-200 status codes - exactly as you say this is a transfer protocol consideration unrelated to the underlying api that needs to be explicitly
handled at the HTTP level. [Practically speaking this can be handled in a WebApi error handler. We suppress non-200 status codes for clients that indicate that preference, much like the twitter API and others.]
I still think there is a problem with HttpRequestMessage coming in as a parameter to the method call and HttpResponseMessage being arbitrarily omittable. Particularly in light of what you have described, is it not hurting uniformity because I have so
many different ways of describing my intent? As I initially described, I can write several different method signatures that are all effectively the same. I think there should be a consistent mechanism for accessing HttpRequest/Response - like the base class
approach danroth suggested in this thread. In any case, shouldn't the WebApi mandate HttpResponseMessage as a return type given what you've said? Otherwise it's just encouraging bad behaviour. :)
Thanks again.
Hi Whirly
Glad to help. I hear you on the challenges of an existing system, those constraints can be very real.
Another alternative approach that is possible today is to use operation handlers to handle HTTP concerns. This way your API method signatures don't have the HTTP messages and can implement the contract. As Dan mentioned, once the MVC integration comes you'll
be able to use controllers which expose the messages as properties.
Cheers
Glenn
Glenn, sorry for nitpicking, but wouldn't you expose the calculator as "sum" instead of "adder" since the sum is really the resource you expose?
Whirly, you can already abstract the HttpRequestMessage into a base class like they mention above, it's actually quite easy. See my example here:
I wouldn't, because Adder expresses intent on the role of the resource. It is an Adder. When I access the resource I am sending it data it can use (via the url) to perform the add.
That doesn't mean sum is wrong. I just preferred modeling the role of the resource rather than it's output.
For that matter you could do something like calculator/4,5/sum i.e. give me the sum resource that is a child of the 4,5 resource. That may look odd, but it is valid :-)
@Glenn - The GetAdder method in your example takes in value1 and value2 but when you call the calculator's add method, you reference adder.value1 and adder.value2. Is this a mistake? Also where does HttpRequestMessage<T> fit in?
That approach works as long as you are per-request and not singleton which hopefully you are not since singleton creates a ton of problems.
@devtrends
Yes it was a mistake though I have now fixed it, thanks for pointing that out.
I don't show HttpRequestMessage<T> in that example, but I could for example looking at headers, etc. However using HttpResponseMessage<T> illustrates the same problem as it is part of the operation signature which is the issue that was raised.
@Siggi, that example there would be a pretty nice blog post, or even contrib. In particular for cases where there are legacy constraints it would be useful.
Very interesting, this expressing intent/roles of a resource is new to me. I've always been thinking about modelling the result of an operation and calculator/4,5/sum is exactly the kind of URL I've been going with. I would be worried that people
would just wrap their RPC ways into "intents", like /TheMethodRunner?method=CalculateSum&value1=5&value2=42.
Can you recommend any reading to further explain this?
The intent I am expressing is to the server not to the client, as ideally the uris would be opaque to the client. Meaning I am using resources that make sense for the domain of the application. Roy actually does recommend this if you read his thesis.
I understand your concern (your example) , and abuses like that can happen. However I am not doing that :-) I am creating a resource for a specific purpose and that resource does not violate the semantics of HTTP/REST.
Having a resource that performs something is fine as long as it obeys the semantics of HTTP. For example posting to Order/1/Approver could result in the order getting approved.
As far as reading, I'm not sure I have anything specific, but I'll hunt for you. What i can say is if you read Roy's dissertation it makes it very clear what the constraints are for REST and as long as you are not violating it you are in the clear.
Which constraint of REST does this violate? Well I know one :) which is cachability as some servers don't cache query strings so really it should be /calculator/adder/value1=5&value2=6 so that it is cachable.
Agree with you on cachability, I generally only use query params for filtering or input into an algorithm like search (an example that would be hard to model as only "results").
In your order example if you would post to Order/1/Approver to change an order, that wouldn't use the proxy cache invalidation that can happen if you would instead do a PUT on Order/1/ with the approved bit set to true.!).
You will still be able to self-host in a Windows Service or your own process. In fact, the new stack is at its core a simple message handler pipeline that you can host wherever you want. Parts of MVC that are
not relevant to Web API development (like views for example) are not pulled in, so what you end up with is a light-weight rehostable HTTP server. With the upcoming Beta we will have a complete set of docs and samples to help get you going on the new bits.
From: SonOfPirate [email removed]
Sent: Thursday, January 19, 2012 5:35 AM
To: Daniel Roth
Subject: Re: Is HttpRequestMessage<T> a good thing? [wcf:286557]
From: SonOfPirate!).
gblock wrote:
Which constraint of REST does this violate? Well I know one :) which is cachability as some servers don't cache query strings so really it should be /calculator/adder/value1=5&value2=6 so that it is cachable.
Ouch! I did not know that!
Am assessing the implications of this.... one of which is that my "?format=xml" vs "?format=json" has gone out the window, and I'll go back to the Accept header.
A question: if values for the OData system query options always give deterministic, reliable results (when used to query a service's collections) then presumably, wrt caching at least, they
shouldn't be query strings?!
Andrew how about using ".xml" and ".json"?
Hi SiggiG, thanks for the suggestion, but I've implement the Accept header now, via a MediaTypeMapping and it's working well.
My idea re. "?format=xml | json" was that a client would specify this in the entry-point / bookmark URI, and not have to do anything else after that. My JSON representations would include outgoing URIs with "?format=json" and XML representations would
have "?format=xml". Less work for the client. But Glenn's remark was an eye opener... potentially every resource representation would be uncached!
Now my clients can do nothing if they want XML, and set the Accept header on every request if they want JSON (may switch that around, not sure).
Reading around the subject, the conclusion is unescapable: the Accept header is the right thing to use. I believe Mark Masse's REST book argues against ".xml" and ".json" (or I may have seen it elsewhere).
I had never seen Glenn's technique of setting property values in the path and not the query string (/calculator/adder/value1=5&value2=6) but if the result is always going to be the same, and query strings bust cache, then it makes sense.
Hence my question about OData system query options: if they always give the same answers in your service, better to have them in the path and not as query strings, no? (from the pov of caching). Is that right, or have I missed something?
I think most people prefer to use the query string for filtering and, um, queries :) I use it for paging and filtering, but don't really have any queries.
Good to see you coming around to the Accept header, as per another discussion we've had ;)
>> I think most people prefer to use the query string for filtering and, um, queries
Yeah, but if "?$filter=PortfolioName eq 'FTSE100'" always gave the same results, couldn't / shouldn't that result be cached? That's what I'm getting at. But I probably will stick with having them as query strings.
>> Good to see you coming around to the Accept header, as per another discussion we've had ;)
Heh - you were right on that one! :)
Here's a question: if you have a number of different media types of the form "application/vnd.mycompany.myapp.XYZ+json" where XYZ varies, do you 'accept' the more generic "application/vnd.mycompany.myapp+json" (or even
"application/json") to match all of them?
I think we're starting to go a "bit" off topic, but here goes :)
For my project I accept application/json, */* or even an empty header, and I chose the +json formatter to be used as default in those cases. This is more to cater to clients that haven't bothered to include a specific media type (and they will probably
break when I have to offer v2 of the resource).
However if you do specify a certain media type I require you to specify the full name with a version.
Thanks Siggi! No more off-topic questions. Have a good w/e.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://wcf.codeplex.com/discussions/286557 | CC-MAIN-2016-50 | refinedweb | 3,178 | 62.48 |
new
In C#, the new keyword can be used as an operator or as a modifier.
- new operator Used to create objects on the heap and invoke constructors.
- new modifier Used to hide an inherited member from a base class member.
new Operator
The new operator is used to create objects and invoke constructors, for example:
It is also used to invoke the default constructor for value types, for example:
In the preceding statement,
myInt is initialized to
0, which is the default value for the type int. The statement has the same effect as:
For a complete list of default values, see Default Values Table.
Remember that it is an error to declare a default constructor for a struct, because every value type implicitly has a public default constructor. It is possible though to declare parameterized constructors on a struct type.
Value-type objects such as structs are created on the stack, while reference-type objects such as classes are created on the heap.
// cs_operator_new.cs // The new operator using System; class NewTest { struct MyStruct { public int x; public int y; public MyStruct (int x, int y) { this.x = x; this.y = y; } } class MyClass { public string name; public int id; public MyClass () { } public MyClass (int id, string name) { this.id = id; this.name = name; } } public static void Main() { // Create objects using default constructors: MyStruct Location1 = new MyStruct(); MyClass Employee1 = new MyClass(); // Display values: Console.WriteLine("Default values:"); Console.WriteLine(" Struct members: {0}, {1}", Location1.x, Location1.y); Console.WriteLine(" Class members: {0}, {1}", Employee1.name, Employee1.id); // Create objects using parameterized constructors:: MyStruct Location2 = new MyStruct(10, 20); MyClass Employee2 = new MyClass(1234, "John Martin Smith"); // Display values: Console.WriteLine("Assigned values:"); Console.WriteLine(" Struct members: {0}, {1}", Location2.x, Location2.y); Console.WriteLine(" Class members: {0}, {1}", Employee2.name, Employee2.id); } }
Output
Notice in the example that the default value of a string is null. Therefore, it was not displayed.
new Modifier
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
Consider the following class:
Declaring a member with the name
Invoke in a derived class will hide the method
Invoke in the base class, that is:
However, the field
x will not. For more information, see 3.6 Signatures and overloading.
- An indexer introduced in a class or struct hides all base class indexers with the same signature.
It is an error to use both new and override on the same member.
Using the new modifier in a declaration that does not hide an inherited member generates a warning.
For more information on hiding names, see 3.7.1 Name hiding.
For more information on fully qualified names, see 3.8.1 Fully qualified names.
Example
In this example, a base class,
MyBaseC, and a derived class,
MyDerivedC, use the same field name
x, thus hiding the value of the inherited field. The example demonstrates the use of the new modifier. It also demonstrates how to access the hidden members of the base class by using the fully qualified names.
// cs_modifier_new.cs // The new modifier using System; public class MyBaseC { public static int x = 55; public static int y = 22; } public class MyDerivedC : MyBaseC { new public static int x = 100; // Name hiding public static void Main() { // Display the overlapping value of x: Console.WriteLine(x); // Access the hidden value of x: Console.WriteLine(MyBaseC.x); // Display the unhidden member y: Console.WriteLine(y); } }
Output
If you remove the new modifier, the program will still compile and run, but you will get the warning:
You can also use the new modifier to modify a nested type if the nested type is hiding another type, as demonstrated in the following example.
Example
In this example, a nested class,
MyClass, hides a class with the same name in the base class. The example demonstrates using the new modifier to eliminate the warning message, as well as accessing the hidden class members by using the fully qualified names.
// cs_modifer_new_nested.cs // Using the new modifier with nested types using System; public class MyBaseC { public class MyClass { public int x = 200; public int y; } } public class MyDerivedC : MyBaseC { new public class MyClass // nested type hiding the base type members { public int x = 100; public int y; public int z; } public static void Main() { // Creating object from the overlapping class: MyClass S1 = new MyClass(); // Creating object from the hidden class: MyBaseC.MyClass S2 = new MyBaseC.MyClass(); Console.WriteLine(S1.x); Console.WriteLine(S2.x); } }
Output
See Also
C# Keywords | Operator Keywords | Modifiers | https://msdn.microsoft.com/en-us/library/51y09td4(VS.71).aspx | CC-MAIN-2016-36 | refinedweb | 776 | 55.44 |
JBossCache Plugin
Dependency:
compile "org.grails.plugins:jbosscache:0.1.9"
Summary
Description
JBossCache is an enterprise-grade replicated cache. This plugin allows easy installation of JBossCache library, @JBossCache annotation to inject cache, a JbosscacheService for Cache creation, and enhanced Cache with additional Groovy-style API
Play with a cache
see the CHANGES.txt for update
Author: Mingfai Ma (mingfai.ma at gmail dot com)
Feature
- provide all JBossCache and depended libraries
- provide a JBosscacheService for creating cache instance
- it creates a DefaultCacheFactory upon lazy-init
- it call CacheEnhancer to add some Grails style API to Cache (see the next bullet)
- Extend the JBossCache Cache API with some Groovy style APIs
- by default, JBossCache provides API argument as FQN or String
- in Groovy, we use '[1,2,3]' to define an ArrayList easily. The JBossCache Cache interface is enhanced with a set of methods that take a List as an argument to determine a node
- refer to Cache.java for all additional interface
- <0.1.4> @JBossCache annotation to inject a Cache instance for any Spring managed bean
- Remarks: from <0.1.4> demo controller is removed and sample configuration will not copied to your project folder.
- <0.1.6> added a org.grails.plugins.jbosscache.JBossCache class as a convenient constructor/builder for a cache
Demonstration
- <0.1.4> Demo controller is removed and the demonstration requires Grails Console Plugin
- pre-requisite: JDK and Grails are properly setup
- Create the first project named 'node1', , under any directory:
grails create-app node1 #create the Grails project cd node1 grails install-plugin jbosscache #install this plugin grails install-plugin console #install the console plugin for demo purpose grails run-app #start the node at the default port 8080
- create the 2nd node named 'node2', but start it at port 8081
grails create-app node2 #create the Grails project cd node1 grails install-plugin jbosscache #install this plugin grails install-plugin console #install the console plugin for demo purpose grails -Dserver.port=8081 run-app #start the node at the port 8081
- Access the console
- Access the console at node1 with
- Access the console at node2 with another browser window:
- Remarks: please use a browser supported by the Console Plugin. IE6 is not supported in 0.1
- At node1
def cacheService = context.getBean("jbosscacheService") cache = cacheService.getCache("demo") //create the cache and store in a 'cache' variable //press Execute button
- At node2
def cacheService = context.getBean("jbosscacheService") cache = cacheService.getCache("demo") //create the cache and store in a 'cache' variable //press Execute button
- At node1
cache.put('/','foo','bar') //press Execute button
- At node2
cache.get('/','foo') //press Execute button
Cache usage
API
- This plugin is for helping you to use JBossCache. You have to know about JBossCache in order to use it. Check the JBossCache documentation page. For application developers, you will want to check the API docs to know about the Cache interface.
@JBossCache annotation
- <0.1.4> You could use an @JBossCache annotation to inject a cache to a field for your Spring-managed bean
- example
import org.grails.plugins.jbosscache.annotation.JBossCache class Bar{ @JBossCache(name="foobar") bar }
- See test case at svn
- The @JBossCache annotation injected cache will have a getDefaultNode() method, and you could utilize the put(key,value) and get(key) interface. The default node is the 'name' in the annotation or the full class name in Fqn. e.g. foo.bar.FoobarService.class will be the Fqn of "/foo/bar/FoobarService"
- In case you want to use JBossCache but will not use the annotation, you may disable it with 'plugins.jbosscache.annotation.disable=true' with system property or in Config.groovy. The annotation is enabled by default, but in future version, it is considering to require explicit enabling by default.
- remarks, the injection is done with a Spring BeanPostProcessor. If enabled, every field in every bean initialized in Spring will be scanned for the @JBossCache annotation. The property/configuration could avoid this very small resource usage.
JBossCache class
- From <0.1.6>, other than using the original JBossCache API or the jbosscacheService, there is an additional way to create a cache instance with org.grails.plugins.jbosscache.JBossCache.
Version and Compatiability
- Last tested with Grails 1.1 RC 1 / Groovy 1.6.0
- JDK 5+
- Plugin 0.1.1+ - JBossCache Core Edition 3.0.2 GA
Reference Links
- Hibernate 2nd level cache
Roadmap
- The next version will configure JBossCache as Hibernate 2nd level cache
- Provide a interactive cluster demo together with Cometd and GridGain Plugin
- check the TODO list in svn trunk
Contact and Author
- Please send any question to the grails user mail list. For JBossCache issues, please go to JBossCache's forum. There is no issue tracking yet. | http://www.grails.org/plugin/jbosscache | CC-MAIN-2016-40 | refinedweb | 786 | 55.03 |
tensorflow::
serving:: ServableHandle
#include <servable_handle.h>
A smart pointer to the underlying servable object T retrieved from the Loader.
Summary
Frontend code gets these handles from the ServableManager. The handle keeps the underlying object alive as long as the handle is alive. The frontend should not hold onto it for a long time, because holding it can delay servable reloading.
The T returned from the handle is generally shared among multiple requests, which means any mutating changes made to T must preserve correctness vis-a-vis the application logic. Moreover, in the presence of multiple request threads, thread-safe usage of T must be ensured.
T is expected to be a value type, and is internally stored as a pointer. Using a pointer type for T will fail to compile, since it would be a mistake to do so in most situations.
Example use:
// Define or use an existing servable: class MyServable { public: void MyMethod(); }; // Get your handle from a manager. ServableHandle
handle; TF_RETURN_IF_ERROR(manager->GetServableHandle(id, &handle)); // Use your handle as a smart-pointer: handle->MyMethod(); | https://www.tensorflow.org/tfx/serving/api_docs/cc/class/tensorflow/serving/servable-handle?hl=da | CC-MAIN-2022-27 | refinedweb | 177 | 55.95 |
18 September 2012 07:34 [Source: ICIS news]
By Fanny Zhang
SINGAPORE (ICIS)--Japanese firms, including major car producer Toyota, have temporarily stopped operations in China for at least two days, as anti-Japan protests sweep across Asia’s biggest emerging market economy over a territorial dispute on islands in the east China sea, industry sources said on Tuesday.
Public demonstrations in ?xml:namespace>
There are concerns that protests will escalate on Tuesday, as the date - 18 September - in 1931 marked the start of
Other Japanese carmakers Honda and Mazda have decided to halt production in
The automotive industry is a major end-user of petrochemicals, including styrene butadiene rubber (SBR) and plastics.
With calls in
In August, sales of Japanese cars in China fell by 2% year on year, while sales in Germany, American, Korean and French cars sales in China increased by 26.5%, 19.9%, 13.0% and 4.21%, respectively, according to China Association of Automobile Manufacturers.
Japanese car sales in September are expected to plummet, sources said.
Many Japanese cars are burned or damaged in the protests. In
Despite current heightened tensions between the two countries, analysts said that the issue should soon calm down since neither of the two Asian economic giants would want a lasting damage to bilateral trade ties.
It remains uncertain how the issue will be resolved.
“Policy makers are wise enough to prevent it from escalating into trade wars. For
“For
Sources said that the current jolt is unlikely to result in Japanese companies closing their
Long-term impacts are yet to be evaluated, according to industry sources.
($1 = €0.76)
Additional reporting by Dolly Wu, Viola Pan | http://www.icis.com/Articles/2012/09/18/9596247/japan-firms-halt-china-operations-protests-mount-over-islands-row.html | CC-MAIN-2013-48 | refinedweb | 278 | 50.67 |
Created on 2013-02-03 04:01 by ncoghlan, last changed 2020-06-18 11:19 by inada.naoki. This issue is now closed.
The]
I tried running with Python 3.4 the following code
import sys
print(sys.argv[1])
print(b'bytes')
And I ran as follows trying to run with a different encoding.
$ python ~/a.py `echo priya|iconv -t latin1`
priya
bytes
There was no unicode encode error generated! Is it because the problem is fixed?
> There was no unicode encode error generated! Is it because the problem
> is fixed?
No, it's not fixed.
First, it seems you are testing with Python 2 (otherwise you would get "b'bytes'", not "bytes"). Python 2 won't have a problem here, since it treats everything as bytestrings.
Second, to evidence the issue you must pass a non-ASCII string. For example:
$ ./python a.py `echo éléphant|iconv -t latin1`
Traceback (most recent call last):
File "a.py", line 4, in <module>
print(sys.argv[1])
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 0: surrogates not allowed
You are right. Instead of running ./python inside the python directory, I ran the default python of older version! Based on the stackoverflow link given, I tried to make some documentation. I am attaching the patch!
Hmm, I'm not sure where those explanations belong but I'm not sure should be in the sys module docs (especially as they are quite lengthy, and they also apply to other data such as os.environ). Perhaps the Unicode HOWTO?
New changeset 38f4e468d4b55551e135c67337c18ae142193ba8 by Inada Naoki in branch 'master':
bpo-17110: doc: add note how to get bytes from sys.argv (GH-12602)
New changeset 5b80cb5584a72044424f2d82d0ae79c720f24c47 by Miss Islington (bot) in branch '3.7':
bpo-17110: doc: add note how to get bytes from sys.argv (GH-12602)
The actual startup code uses Py_DecodeLocale() for converting argv from bytes to unicode. Since which Python version is it guaranteed that Py_DecodeLocale() and os.fsencode() roundtrip?
There is no strict guarantee.
I think ASCII, UTF-8, latin1 with surrogateescape guarantee roundtrip.
Other legacy encodings like cp932 may not roundtrip. But it is not a huge problem because only Windows use them typically.
On Windows:
* wchar_t is used in most case, instead of fsencoding
* fsencoding is now UTF-8 by default
In other words, if you are using legacy encoding on Unix, it may be not roundtripping.
If the encoding supports it, since which Python version do Py_DecodeLocale() and os.fsencode() roundtrip?+.
>
> Manuel Jacob <me@manueljacob.de> added the comment:
>
> If the encoding supports it, since which Python version do
> Py_DecodeLocale() and os.fsencode() roundtrip?
>
Maybe, since Python 3.2. FWIW, fsencode is added by Victor in
>+.
>
>
>
I think it is a right approach.
One of the important use case of os.fsencode is using file path from
sys.argv even if it can not be decoded by filesystem encoding. | https://bugs.python.org/issue17110 | CC-MAIN-2020-40 | refinedweb | 488 | 68.97 |
Klaus Schmidinger wrote: > Artur Skawina wrote: >>)? As I haven't run vdr w/o this patch for a long time, i'm not sure. Apparently things are not ok, as this thread shows, but other vdr-1.3.38+ users with a 2.6 kernel could answer the above question better... For me it was the sync calls that made me look at this code; w/o them things weren't as bad, IIRC. I ended up disabling the fdatasyncs completely even when using fadvise. >. it started as a debugging knob, so i could test the impact of the sync calls, compare cutting speed w/ fadvise on/off etc. (Setup.WriteStrategy==1) meant no POSIX_FADV_DONTNEED calls while accessing a file (the calls were always made when closing a file). > So, if you can provide a patch against the latest VDR version that > still uses "#ifdef USE_FADVISE" to completely turn the fadvise > stuff off, and does _not_ introduce another setup option, I might > consider including it for the final version 1.4. i did the minimal fix to the existing vdr code -- note it's far from optimal, and i suspect there are cases where the fadvise-enabled version isn't necessarily an improvement. An option which basically turns USE_FADVISE into a runtime switch would be useful. As i haven't needed the option myself lately, in fact didn't even remember what exactly it did and had to check the code, i just killed it, patch attached. It's vs 1.3.39 because the UI/channel-switch posts scared me away from upgrading vdr, still remembering the broken menu key experience... ;) cutter.c part is entirely optional (affects only cutting speed). artur -------------- next part -------------- --- vdr-1.3.39.org/cutter.c 2005-10-31 12:26:44.000000000 +0000 +++ vdr-1.3.39/cutter.c 2006-01-28 21:33:39.000000000 +0000 @@ -66,6 +66,8 @@ void cCuttingThread::Action(void) toFile = toFileName->Open(); if (!fromFile || !toFile) return; + fromFile->SetReadAhead(MEGABYTE(20)); + toFile->SetReadAhead(MEGABYTE(20)); int Index = Mark->position; Mark = fromMarks.Next(Mark); int FileSize = 0; @@ -90,6 +92,7 @@ void cCuttingThread::Action(void) if (fromIndex->Get(Index++, &FileNumber, &FileOffset, &PictureType, &Length)) { if (FileNumber != CurrentFileNumber) { fromFile = fromFileName->SetOffset(FileNumber, FileOffset); + fromFile->SetReadAhead(MEGABYTE(20)); CurrentFileNumber = FileNumber; } if (fromFile) { @@ -118,10 +121,11 @@ void cCuttingThread::Action(void) break; if (FileSize > MEGABYTE(Setup.MaxVideoFileSize)) { toFile = toFileName->NextFile(); - if (toFile < 0) { + if (!toFile) { error = "toFile 1"; break; } + toFile->SetReadAhead(MEGABYTE(20)); FileSize = 0; } LastIFrame = 0; @@ -158,10 +162,11 @@ void cCuttingThread::Action(void) cutIn = true; if (Setup.SplitEditedFiles) { toFile = toFileName->NextFile(); - if (toFile < 0) { + if (!toFile) { error = "toFile 2"; break; } + toFile->SetReadAhead(MEGABYTE(20)); FileSize = 0; } } --- vdr-1.3.39.org/tools.c 2006-01-15 14:31:45.000000000 +0000 +++ vdr-1.3.39/tools.c 2006-01-28 21:48:22.000000000 +0000 @@ -1040,10 +1040,9 @@ bool cSafeFile::Close(void) // --- cUnbufferedFile ------------------------------------------------------- -//#define USE_FADVISE +#define USE_FADVISE -#define READ_AHEAD MEGABYTE(2) -#define WRITE_BUFFER MEGABYTE(10) +#define WRITE_BUFFER KILOBYTE(800) cUnbufferedFile::cUnbufferedFile(void) { @@ -1059,8 +1058,17 @@ int cUnbufferedFile::Open(const char *Fi { Close(); fd = open(FileName, Flags, Mode); - begin = end = ahead = -1; + curpos = 0; + begin = lastpos = ahead = 0; + readahead = 128*1024; + pendingreadahead = 0; written = 0; + totwritten = 0; + if (fd >= 0) { + // we could use POSIX_FADV_SEQUENTIAL, but we do our own readahead + // disabling the kernel one. + posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM); + } return fd; } @@ -1068,15 +1076,10 @@ int cUnbufferedFile::Close(void) { #ifdef USE_FADVISE if (fd >= 0) { - if (ahead > end) - end = ahead; - if (begin >= 0 && end > begin) { - //dsyslog("close buffer: %d (flush: %d bytes, %ld-%ld)", fd, written, begin, end); - if (written) - fdatasync(fd); - posix_fadvise(fd, begin, end - begin, POSIX_FADV_DONTNEED); - } - begin = end = ahead = -1; + if (totwritten) // if we wrote anything make sure the data has hit the disk before + fdatasync(fd); // calling fadvise, as this is our last chance to un-cache it. + posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); + begin = lastpos = ahead = 0; written = 0; } #endif @@ -1085,45 +1088,95 @@ int cUnbufferedFile::Close(void) return close(OldFd); } -off_t cUnbufferedFile::Seek(off_t Offset, int Whence) -{ - if (fd >= 0) - return lseek(fd, Offset, Whence); - return -1; -} - +// When replaying and going eg FF->PLAY the position jumps back 2..8M +// hence we might not want to drop that data at once. +// Ignoring this for now to avoid making this even more complex, +// but we could at least try to handle the common cases. +// (PLAY->FF->PLAY, small jumps, moving editing marks etc) + +#define KREADAHEAD MEGABYTE(4) // amount (guess) of kernel/fs prefetch that + // could happen in addition to our own. +#define FADVGRAN 4096 // AKA fadvise-chunk-size; PAGE_SIZE or + // getpagesize(2) would also work. + ssize_t cUnbufferedFile::Read(void *Data, size_t Size) { if (fd >= 0) { #ifdef USE_FADVISE - off_t pos = lseek(fd, 0, SEEK_CUR); - // jump forward - adjust end position - if (pos > end) - end = pos; - // after adjusting end - don't clear more than previously requested - if (end > ahead) - end = ahead; - // jump backward - drop read ahead of previous run - if (pos < begin) - end = ahead; - if (begin >= 0 && end > begin) - posix_fadvise(fd, begin - KILOBYTE(200), end - begin + KILOBYTE(200), POSIX_FADV_DONTNEED);//XXX macros/parameters??? - begin = pos; + off_t jumped = curpos-lastpos; // nonzero means we're not at the last offset + if (jumped) { // ie some kind of jump happened. + pendingreadahead += ahead-lastpos+KREADAHEAD; + // jumped forward? - treat as if we did read all the way to current pos. + if (jumped >= 0) { + lastpos = curpos; + // but clamp at ahead so we don't clear more than previously requested. + // (would be mostly harmless anyway, unless we got more than one reader of this file) + if (lastpos > (ahead+KREADAHEAD)) + lastpos = ahead+KREADAHEAD; + } + // jumped backward? - drop both last read _and_ read-ahead + else + if (curpos < begin) + lastpos = ahead+KREADAHEAD; + // jumped backward, but still inside prev read window? - pretend we read less. + else /* if (curpos >= begin) */ + lastpos = curpos; + } + #endif ssize_t bytesRead = safe_read(fd, Data, Size); #ifdef USE_FADVISE + // Now drop data accessed during _previous_ Read(). (ie. begin...lastpos) + // fadvise() internally has page granularity; it drops only whole pages + // from the range we specify (since it cannot know if we will be accessing + // the rest). This is why we drop only the previously read data, and do it + // _after_ the current read() call, while rounding up the window to make + // sure that even not PAGE_SIZE-aligned data gets freed. + // We're also trying merge the fadvise calls a bit in order to reduce overhead + // (to avoid a fadvise() call here for every read() above). + if (begin >= 0 && lastpos > begin) + if (jumped || (size_t)(lastpos-begin) > readahead) { + //dsyslog("taildrop: %ld..%ld size %ld", begin, lastpos, lastpos-begin); + posix_fadvise(fd, begin-(FADVGRAN-1), lastpos-begin+(FADVGRAN-1)*2, POSIX_FADV_DONTNEED); + begin = curpos; + } +; + curpos += bytesRead; + //dsyslog("jump: %06ld ra: %06ld size: %ld", jumped, (long)readahead, (long)Size); + + // no jump? (allow small forward jump still inside readahead window). + if (jumped>=0 && jumped<=(off_t)readahead) { + // Trigger the readahead IO, but only if we've used at least + // 1/4 of the previously requested area. This avoids calling + // fadvise() after every read() call. + if ((ahead-curpos)<(off_t)(readahead-readahead/4)) { + posix_fadvise(fd, curpos, readahead, POSIX_FADV_WILLNEED); + ahead = curpos + readahead; + } + if ( readahead < Size*64 ) { // automagically tune readahead size. + readahead = Size*64; + //dsyslog("Readahead for fd: %d increased to %ld", fd, (long)readahead); + } + } + else { + // jumped - we really don't want any readahead now. otherwise + // eg fast-rewind gets in trouble. + ahead = curpos; + + // Every now and then, flush all cached data from this file; mostly + // to get rid of nonflushed readahead coming from _previous_ jumps + // (if the readahead I/O hasn't finished by the time we called + // fadvice() to undo it, the data could still be cached). + // The accounting does not have to be 100% accurate, as long as + // this triggers after _some_ jumps we should be ok. + if (pendingreadahead>MEGABYTE(40)) { + pendingreadahead = 0; + posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); + } + } } - else - end = pos; + lastpos = curpos; #endif return bytesRead; } @@ -1132,29 +1185,37 @@ ssize_t cUnbufferedFile::Read(void *Data ssize_t cUnbufferedFile::Write(const void *Data, size_t Size) { + //dsyslog("Unbuffered:Write: fd: %d %8ld..%8ld size: %5ld", fd, curpos, curpos+Size, (long)Size); if (fd >=0) { -#ifdef USE_FADVISE - off_t pos = lseek(fd, 0, SEEK_CUR); -#endif ssize_t bytesWritten = safe_write(fd, Data, Size); #ifdef USE_FADVISE - if (bytesWritten >= 0) { + if (bytesWritten > 0) { + begin = min(begin, curpos); + curpos += bytesWritten; written += bytesWritten; - if (begin >= 0) { - if (pos < begin) - begin = pos; - } - else - begin = pos; - if (pos + bytesWritten > end) - end = pos + bytesWritten; + lastpos = max(lastpos, curpos); if (written > WRITE_BUFFER) { - //dsyslog("flush buffer: %d (%d bytes, %ld-%ld)", fd, written, begin, end); - fdatasync(fd); - if (begin >= 0 && end > begin) - posix_fadvise(fd, begin, end - begin, POSIX_FADV_DONTNEED); - begin = end = -1; + //dsyslog("flush buffer: %d (%d bytes, %ld-%ld)", fd, written, begin, lastpos); + if (lastpos>begin) { + off_t headdrop = min(begin, WRITE_BUFFER*2L); + posix_fadvise(fd, begin-headdrop, lastpos-begin+headdrop, POSIX_FADV_DONTNEED); + } + begin = lastpos = max(0L, curpos-4095); + totwritten += written; written = 0; + //); + off_t headdrop = min(curpos-totwritten, totwritten*2L); + posix_fadvise(fd, curpos-totwritten-headdrop, totwritten+headdrop, POSIX_FADV_DONTNEED); + totwritten = 0; + } } } #endif --- vdr-1.3.39.org/tools.h 2006-01-08 11:40:37.000000000 +0000 +++ vdr-1.3.39/tools.h 2006-01-28 21:32:26.000000000 +0000 @@ -237,22 +237,40 @@ public: /// cUnbufferedFile is used for large files that are mainly written or read /// in a streaming manner, and thus should not be cached. +#include <sys/types.h> +#include <sys/mman.h> +#include <unistd.h> + class cUnbufferedFile { private: int fd; + off_t curpos; off_t begin; - off_t end; + off_t lastpos; off_t ahead; - ssize_t written; + size_t pendingreadahead; + size_t readahead; + size_t written; + size_t totwritten; public: cUnbufferedFile(void); ~cUnbufferedFile(); int Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE); int Close(void); - off_t Seek(off_t Offset, int Whence); + off_t Seek(off_t Offset, int Whence) + { + //dsyslog("Seek: fd: %d offs: %ld whence: %d diff: %ld", fd, (long)Offset, Whence, Offset-curpos); + if (Whence == SEEK_SET && Offset == curpos) + return curpos; + + curpos = lseek(fd, Offset, Whence); + return curpos; + } + { | http://www.linuxtv.org/pipermail/vdr/2006-January/007529.html | CC-MAIN-2015-35 | refinedweb | 1,619 | 51.89 |
Production guidelines on Kubernetes
Cluster capacity requirements
For a production ready Kubernetes cluster deployment, it is recommended you run a cluster of at least 3 worker nodes to support a highly-available control plane installation. Use the following resource settings might serve as a starting point. Requirements will vary depending on cluster size and other factors, so individual testing is needed to find the right values for your environment:
Note: For more info on CPU and Memory resource units and their meaning, see this link
Helm
When installing Dapr using Helm, no default limit/request values are set. Each component has a
resources option (for example,
dapr_dashboard.resources), which you can use to tune the Dapr control plane to fit your environment. The Helm chart readme has detailed information and examples. For local/dev installations, you might simply want to skip configuring the
resources options.
Optional components
The following Dapr control plane deployments are optional:
- Placement - Needed for Dapr Actors
- Sentry - Needed for mTLS for service to service invocation
- Dashboard - Needed for operational view of the cluster
Sidecar resource settings
To set the resource assignments for the Dapr sidecar, see the annotations here. The specific annotations related to resource constraints are:
dapr.io/sidecar-cpu-limit
dapr.io/sidecar-memory-limit
dapr.io/sidecar-cpu-request
dapr.io/sidecar-memory-request
If not set, the dapr sidecar will run without resource settings, which may lead to issues. For a production-ready setup it is strongly recommended to configure these settings.
For more details on configuring resource in Kubernetes see Assign Memory Resources to Containers and Pods and Assign CPU Resources to Containers and Pods.
Example settings for the dapr sidecar in a production-ready setup:
Note: Since Dapr is intended to do much of the I/O heavy lifting for your app, it’s expected that the resources given to Dapr enable you to drastically reduce the resource allocations for the application
The CPU and memory limits above account for the fact that Dapr is intended to a high number of I/O bound operations. It is strongly recommended that you use a monitoring tool to baseline the sidecar (and app) containers and tune these settings based on those baselines.
Highly-available mode
When deploying Dapr in a production-ready configuration, it’s recommended to deploy with a highly available (HA) configuration of the control plane, which creates 3 replicas of each control plane pod in the dapr-system namespace. This configuration allows for the Dapr control plane to survive node failures and other outages.
For a new Dapr deployment, the HA mode can be set with both the Dapr CLI and with Helm charts.
For an existing Dapr deployment, enabling the HA mode requires additional steps. Please refer to this paragraph for more details.
Deploying Dapr with Helm
For a full guide on deploying Dapr with Helm visit this guide.
Parameters file
It is recommended to create a values file instead of specifying parameters on the command-line. This file should be checked in to source control so that you can track changes made to it.
For a full list of all available options you can set in the values file (or by using the
--set command-line option), see.
Instead of using either
helm install or
helm upgrade as shown below, you can also run
helm upgrade --install - this will dynamically determine whether to install or upgrade.
# add/update the helm repo helm repo add dapr helm repo update # See which chart versions are available helm search repo dapr --devel --versions # create a values file to store variables touch values.yml cat << EOF >> values.yml global.ha.enabled: true EOF # run install/upgrade helm install dapr dapr/dapr \ --version=<Dapr chart version> \ --namespace dapr-system \ --create-namespace \ --values values.yml \ --wait # verify the installation kubectl get pods --namespace dapr-system
This command will run 3 replicas of each control plane service in the dapr-system namespace.
Note: The Dapr Helm chart automatically deploys with affinity for nodes with the label
kubernetes.io/os=linux. You can deploy the Dapr control plane to Windows nodes, but most users should not need to. For more information see Deploying to a Hybrid Linux/Windows K8s Cluster
Upgrading Dapr with Helm
Dapr supports zero downtime upgrades. The upgrade path includes the following steps:
- Upgrading a CLI version (optional but recommended)
- Updating the Dapr control plane
- Updating the data plane (Dapr sidecars)
Upgrading the CLI
To upgrade the Dapr CLI, download the latest version of the CLI and ensure it’s in your path.
Upgrading the control plane
See steps to upgrade Dapr on a Kubernetes cluster.
Updating the data plane (sidecars)
The last step is to update pods that are running Dapr to pick up the new version of the Dapr runtime.
To do that, simply issue a rollout restart command for any deployment that has the
dapr.io/enabled annotation:
kubectl rollout restart deploy/<Application deployment name>
To see a list of all your Dapr enabled deployments, you can either use the Dapr Dashboard or run the following command using the Dapr CLI:
dapr list -k APP ID APP PORT AGE CREATED nodeapp 3000 16h 2020-07-29 17:16.22
Enabling high-availability in an existing Dapr deployment
Enabling HA mode for an existing Dapr deployment requires two steps.
First, delete the existing placement stateful set:
kubectl delete statefulset.apps/dapr-placement-server -n dapr-system
Second, issue the upgrade command:
helm upgrade dapr ./charts/dapr -n dapr-system --set global.ha.enabled=true
The reason for deletion of the placement stateful set is because in the HA mode, the placement service adds Raft for leader election. However, Kubernetes only allows for limited fields in stateful sets to be patched, subsequently failing upgrade of the placement service.
Deletion of the existing placement stateful set is safe. The agents will reconnect and re-register with the newly created placement service, which will persist its table in Raft.
Recommended security configuration
When properly configured, Dapr ensures secure communication. It can also make your application more secure with a number of built-in features.
It is recommended that a production-ready deployment includes the following settings:
Mutual Authentication (mTLS) should be enabled. Note that Dapr has mTLS on by default. For details on how to bring your own certificates, see here
App to Dapr API authentication is enabled. This is the communication between your application and the Dapr sidecar. To secure the Dapr API from unauthorized application access, it is recommended to enable Dapr’s token based auth. See enable API token authentication in Dapr for details
Dapr to App API authentication is enabled. This is the communication between Dapr and your application. This ensures that Dapr knows that it is communicating with an authorized application. See Authenticate requests from Dapr using token authentication for details
All component YAMLs should have secret data configured in a secret store and not hard-coded in the YAML file. See here on how to use secrets with Dapr components
The Dapr control plane is installed on a dedicated namespace such as
dapr-system.
Dapr also supports scoping components for certain applications. This is not a required practice, and can be enabled according to your security needs. See here for more info.
Tracing and metrics configuration
Dapr has tracing and metrics enabled by default. It is recommended that you set up distributed tracing and metrics for your applications and the Dapr control plane in production.
If you already have your own observability set-up, you can disable tracing and metrics for Dapr.
Tracing
To configure a tracing backend for Dapr visit this link.
Metrics
For metrics, Dapr exposes a Prometheus endpoint listening on port 9090 which can be scraped by Prometheus.
To setup Prometheus, Grafana and other monitoring tools with Dapr, visit this link.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve. | https://docs.dapr.io/operations/hosting/kubernetes/kubernetes-production/ | CC-MAIN-2021-43 | refinedweb | 1,334 | 53.21 |
Use rtl-sdr to receive EnergyCount 3000 transmissions.
Project description
This module allows you to receive and decode radio transmissions from EnergyCount 3000 energy loggers using a RTL-SDR supported radio receiver and the GNU Radio software defined radio framework.
EnergyCount 3000 transmitters plug between a device and an AC power outlet and monitor electrical energy usage. They transmit a packet with a status update every 5 seconds on the 868 MHz SRD band. Reported values include id of the device, current and maximum seen electrical power, total energy used and device on time.
Module content
The module exports a class that represents the radio receiver. You provide it with a callback function that is called each time a new status update is received:
def callback(state): print state my_ec3k = ec3k.EnergyCount3K(callback=callback) my_ec3k.start() while not want_stop: time.sleep(2) print "Noise level: %.1f dB" % (my_ec3k.noise_level,) my_ec3k.stop()
The example above prints out the following on each status update:
id : .... time total : .... seconds time on : .... seconds energy : .... Ws power current : .... W power max : .... W reset counter : ....
You can also get the last received state by calling the get method on the EnergyCount3K object. See docstrings for details.
Also included is an example command-line client ec3k_recv that prints received packets to standard output.
Requirements
You need the GNU Radio framework, rtl-sdr and the gr-osmosdr package.
Combination of versions last known to work:
- GNU Radio release 3.7.5
- rtl-sdr git commit d447a2e9 (2014-08-26)
- gr-osmosdr git commit 48045b59 (2015-01-10)
For baseband decoding a pure Python implementation is included in this package (capture.py) and should work out of the box.
For more efficient decoding a C implementation can also be used. Obtain the source from the address below, compile it and make sure capture binary is in PATH. It should then get used automatically instead of the Python implementation.
Installation
Install ec3k as you would most other Python packages:
$ python setup.py install $ python setup.py test
To try it out, run the example command-line client:
$ ec3k_recv
Please note that the receiver needs some time to adapt to the signal and noise level in your environment. It might take a few minutes before ec3k_recv prints out any decoded packets.
Known problems
Occasionally the GNU Radio pipeline isn’t setup correctly. If this happens the noise level constantly stays at -90 dB and no packets are ever received. Restarting the program usually helps. Updating gr-osmosdr and rtl-sdr usually fixes this problem.
Stopping the receiver sometimes causes a segfault. Updating gr-osmosdr and rtl-sdr usually fixes this problem.
Feedback
Please send patches or bug reports to <tomaz.solc@tablix.org>
Source
You can get a local copy of the development repository with:
git clone git://github.com/avian2/ec3k.git
License
ec3k, software receiver for EnergyCount 3000
Protocol reverse. | https://pypi.org/project/ec3k/ | CC-MAIN-2019-26 | refinedweb | 481 | 51.24 |
@anthony_ricaud @yoavweiss It sounds like you’d be better served by a browser extension for a complex-ish setup like this.
@sid_vishnoi @kennethrohde @dandclark1 You can `try…catch` a dynamic import assertion to check if the type is supported:
“`js
const type = ‘foo’;
try {
await import(‘./foo.json’, {
assert: { type }
});
} catch (err) {
iferr.name
Using CSS Module Scripts to import stylesheets web.dev/css-module-scr…, by @dandclark1.
“`js
import sheet from ‘./styles.css’ assert { type: ‘css’ };
document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];
“`
@Gian_albert02 @ChromiumDev You can always file a new.crbug.com.
@Gian_albert02 @ChromiumDev That’s the UI of the @brave browser. You’re tweeting to Chrome.
@pepelsbey_ The problem with toggles is that you’re actively fighting the browser if you choose a theme different than the system theme; there is just no way around it. FWIW, my toggle supports both approaches, the `class` attribute or the `link[media]` agithub.com/GoogleChromeLa…
@Gian_albert02 @ChromiumDev This is the tabs overview that you have chosen to fill with new tabs. In the general case this overview looks different. 😃
ChromiumDev Help @tomayac by answering a short (promised!) survey 📋 about his efforts to reboot the 📶 Network Information API: forms.gle/7fqGn3X5134EzG….
More context and background in the quoted tweet ⤵️ twitter.com/ChromiumDev/st… | https://tomayac.com/tweets/2021/08/17 | CC-MAIN-2022-33 | refinedweb | 211 | 61.02 |
Yesterday, I showed you how to create a Woot! Off notifier using Python. As promised, I’m now going to show you how to create a Woot! Off notifier using C#. In case you didn’t read yesterday’s article, it basically told how I love Woot! Off’s, but hate having to constantly refresh my browser to check for new items. Instead, I decided to write a tool that does that for me. In the Python version I wrote, it only displays the item name and price. In today’s article, I’m taking it a bit further by showing you how to create a Windows Form that displays the item description along with the item name and price. And, I even show you how to display the item image and the progress bar that shows how many items are left just like on the Woot! site. So, let’s get started.
The first thing you need to do is to fire up Visual C# and create yourself a new Windows Form application. Once you have your application built, you will need to add a few controls to your form. So, go ahead and add a picture box control for displaying the item image, a rich text box control for displaying the item information such as name, price, and description, a progress bar for showing how many items are remaining, a numeric up / down control for setting the wait interval, and a button control for starting and stopping the thread that we’ll use for our timer. You can layout your form however you want. Here’s what my layout looks like:
For this demo, I’ll be working with System.Threading.Thread to give our application a way to repeat the check for new items. But, you don’t have to use threads. If you’d prefer, you can use the Background Worker Control found in your toolbox. The reason you need to use either a Thread or a Background Worker is because your app will freeze, preventing you from changing your wait interval or clicking the Stop button while the application waits. Here are the dependencies I’m working with and the thread I’m using to do the work. You’ll also see that I’ve declared the Woot! url as a global variable as well. This isn’t really needed, but I did it anyways.
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
private Thread _workerThread;
private string _url = ““;
Typically, when working with threads, you will need to use delegates when accessing form components to prevent cross thread exceptions. But, to keep things simple, we’re just going to tell our app to not check for illegal cross thread calls. To do that, we only need to add one line to our form’s constructor.
CheckForIllegalCrossThreadCalls = false;
Next, you will need to add a click event listener to the button you added earlier. This event handler is where we will create and start our worker thread. When you build your new thread, you will need to pass it a function which will be where the work actually takes place. I called my thread function “Run” as shown below, but you can call yours whatever you want.
_workerThread = new Thread(new ThreadStart(Run));
_workerThread.Start();
After you’ve setup your thread, make sure you have a function created with the same name as the name you passed to your ThreadStart above. That’s where we’ll be doing all of the heavy lifting. Instead of getting into all of the details about how to make your call to Woot!, I’m just going to go ahead and show you the code.
private void Run() { WebClient wc = new WebClient(); wc.UseDefaultCredentials = true; wc.Proxy = WebRequest.DefaultWebProxy; wc.Proxy.Credentials = CredentialCache.DefaultCredentials; while (true) { txtDescription."); if (m.Success) { string title = m.Groups[1].Value; txtDescription.AppendText(title + "\n\n"); } m = Regex.Match(html, "<span class=\"amount\">(.*?)</span>"); if (m.Success) { string amount = m.Groups[1].Value; txtDescription.AppendText("$" + amount + "\n\n"); } m = Regex.Match(html, "<meta property=\"og:image\" content=\"(.*?)\" />"); if (m.Success) { string imgUrl = m.Groups[1].Value; pctImage.ImageLocation = imgUrl; } m = Regex.Match(html, "<div class='wootOffProgressBarValue' style='width:(.*?)%'></div>"); if (m.Success) { int s = int.Parse(m.Groups[1].Value); status.Value = s; } m = Regex.Match(html.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", ""), "<dt>Product:</dt><dd>(.*?)</dd>"); if (m.Success) { string description = m.Groups[1].Value.Trim(); txtDescription.AppendText(description + "\n"); } Thread.Sleep(Convert.ToInt32(interval.Value) * 1000); } }
The most important piece to note here is that I’m using System.Net.WebClient to make the call to Woot! to download the HTML which we’ll be scraping to find the important pieces. You’ll also notice that I’ve wrapped a good portion of this code with a “while” loop that never ends. That’s because I want this app to continuously check for new items either until I close the app or click the Stop button. I’m using System.Text.RegularExpressions.Regex to search for the item name, price, description, and image URL. Once found, that information gets appended to the rich text box we created earlier. If we hadn’t added the “CheckForIllegalCrossThreadCalls = false” line earlier, this is where we would’ve hit the Illegal Cross Thread Exception.
At the end of the function, you’ll see that I’m also System.Threading.Thread to tell the application to “wait” for a given amount of time. The Sleep method expects a time interval in milliseconds. Since our numeric up / down control only has the time in seconds, we simply multiply that value times 1000 to get the time into milliseconds.
Well, that’s pretty much it. If everything worked accordingly, you should be able to run your app and should see something like shown below. Keep in mind that this is only intended to be used on days that there’s a Woot! Off happening. Even though it’ll probably work on other days, it hasn’t been tested and might not work as expected. If you are interested, I have provided the entire application solution available for download from. It contains a couple of extra things not mentioned here that make the app complete such as checking if the worker thread is not null and is active and killing it if it is when closing the app.
As always, please leave your comments, questions, and suggestions in the comments section below and I’ll answer you as soon as possible. Until next time, HAPPY CODING!
PayPal will open in a new tab. | http://www.prodigyproductionsllc.com/articles/programming/c-woot-off-notifier/ | CC-MAIN-2017-04 | refinedweb | 1,118 | 67.76 |
In this series we are building a Twitter client for the Android platform using the Twitter4J library. This tutorial will focus on implementing tweeting, retweeting, and replying to tweets. We will create a new Activity for tweeting and replying, with retweet and reply buttons implemented for each tweet in the user's home timeline.
In the first four tutorials we:
- Registered the app with Twitter.
- Imported the Twitter4J library.
- Handled user authentication.
- Built the user interface using XML resources.
- Created an SQLite database to store the tweets for the user's home timeline.
- Mapped the data to the visible Views using an Adapter.
- Fetched new updates periodically using a Service and Broadcast..
Step 2: Prepare to Tweet
Add the "setupTweet" method to your class as follows:
/** * Method called whenever this Activity starts * - get ready to tweet * Sets up twitter and onClick listeners * - also sets up for replies */ private void setupTweet() { //prepare to tweet }
Inside this method, we need to prepare the class to send ordinary tweets as well as replies. First let's use the Shared Preferences to instantiate our Twitter object:
//get preferences for user twitter details tweetPrefs = getSharedPreferences("TwitNicePrefs", 0); //get user token and secret for authentication String userToken = tweetPrefs.getString("user_token", null); String userSecret = tweetPrefs.getString("user_secret", null); //create a new twitter configuration usign user details Configuration twitConf = new ConfigurationBuilder() .setOAuthConsumerKey(TWIT_KEY) .setOAuthConsumerSecret(TWIT_SECRET) .setOAuthAccessToken(userToken) .setOAuthAccessTokenSecret(userSecret) .build(); //create a twitter instance tweetTwitter = new TwitterFactory(twitConf).getInstance();
Here we create a Twitter object using the user's authentication information together with the developer key and secret for the application. When we take users to this Activity class, we are going to pass in the ID and username if a tweet is being replied to. We get these from the Intent:
//get any data passed to this intent for a reply Bundle extras = getIntent().getExtras();
If the tweet is an ordinary update rather than a reply, there will be no extras. If there are extras, we know the tweet is a reply:
if(extras !=null) { //get the ID of the tweet we are replying to tweetID = extras.getLong("tweetID"); //get the user screen name for the tweet we are replying to tweetName = extras.getString("tweetUser"); //use the passed information }
Here we retrieve the ID and screen-name for the tweet to reply to. Next we use this information to add the username to the text-field, still inside the "if" statement:
//get a reference to the text field for tweeting EditText theReply = (EditText)findViewById(R.id.tweettext); //start the tweet text for the reply @username theReply.setText("@"+tweetName+" "); //set the cursor to the end of the text for entry theReply.setSelection(theReply.getText().length());
We set the username as the first part of the tweet text, placing the cursor at the end so that the user can type their reply text straight away.
Next let's take care of cases where the tweet is not a reply:
else { EditText theReply = (EditText)findViewById(R.id.tweettext); theReply.setText(""); }
Here we simply set the text to an empty String, again using the ID we gave the text-field in the layout XML. Now we can finish the "setupTweet" method by adding click listeners for the "send" button and the "home" button for returning to the main timeline screen:
//set up listener for choosing home button to go to timeline LinearLayout tweetClicker = (LinearLayout)findViewById(R.id.homebtn); tweetClicker.setOnClickListener(this); //set up listener for send tweet button Button tweetButton = (Button)findViewById(R.id.dotweet); tweetButton.setOnClickListener(this);
We again use the ID values we specified in our layout files.
Step 3: Detect Clicks
Remember that the Tweet Activity is going to contain a button to take users back to the home timeline as well as the button to send the tweet. Let's now add the "onClick" method to handle users clicking these buttons:
/** * Listener method for button clicks * - for home button and send tweet button */ public void onClick(View v) { //handle home and send button clicks }
First get a reference to the text-field:
EditText tweetTxt = (EditText)findViewById(R.id.tweettext);
Now we need to work out which button was clicked using switch and case statements:
//find out which view has been clicked switch(v.getId()) { case R.id.dotweet: //send tweet break; case R.id.homebtn: //go to the home timeline break; default: break; }
Inside the "dotweet" case statement, before the break statement, implement sending a tweet as follows:
String toTweet = tweetTxt.getText().toString(); try { //handle replies if(tweetName.length()>0) tweetTwitter.updateStatus(new StatusUpdate(toTweet).inReplyToStatusId(tweetID)); //handle normal tweets else tweetTwitter.updateStatus(toTweet); //reset the edit text tweetTxt.setText(""); } catch(TwitterException te) { Log.e("NiceTweet", te.getMessage()); }
Here we check whether the tweet is a reply or not. The "if" statement executes if the tweet is a reply, including the text from the text-field and the ID of the status update we are replying to. The "else" statement takes care of sending ordinary tweets, in which only the text is passed as parameter. The try and catch blocks are necessary as we are attempting to connect to Twitter over the network. After sending the tweet, whether a reply or not, we set the text-field back to empty in preparation for the next tweet update.
For the "homebtn" case statement, simply set the text-field to an empty String:
tweetTxt.setText("");
Finally, after the switch statement but still inside the "onClick" method, finish the Activity so that it returns to the home timeline:
finish();
Whether the tweet is a reply or an ordinary update, we immediately take the user back to the main screen when it is sent, which we also do when they press the home button - the finish statement will execute in all three cases.
Step 4: Model Tweet Data for Retweets and Replies
To implement retweeting and replying, we need to store the tweet ID and user screen-name within the retweet and reply buttons for each tweet in the timeline. By storing this data within the button Views for retweet and reply, we will be able to detect which tweet is being retweeted or replied to when the user presses a button.
Because the information we need to store comprises a number and some text, we will create a class to model it. Create a new class in your project and name it "StatusData". Your new class should begin as follows:
public class StatusData {
Inside the class, add instance variables for the tweet ID and username:
/**tweet ID*/ private long tweetID; /**user screen name of tweeter*/ private String tweetUser;
The ID is modeled as a long, with the screen-name a text String. Add a constructor method to the class:
/** * Constructor receives ID and user name * @param ID * @param screenName */ public StatusData(long ID, String screenName) { //instantiate variables tweetID=ID; tweetUser=screenName; }
The method simply instantiates the two variables. Next add a public method so that we can retrieve the tweet ID elsewhere:
/** * Get the ID of the tweet * @return tweetID as a long */ public long getID() {return tweetID;}
Then add a method to return the screen-name:
/** * Get the user screen name for the tweet * @return tweetUser as a String */ public String getUser() {return tweetUser;}
These methods will allow us to retrieve this information when users click the retweet or reply button for a particular tweet.
Step 5: Extend Binding for Retweets and Replies
Now we need to extend the code in the Adapter class we created ("UpdateAdapter"). In the "bindView" method, we tailored the mapping of data to the user interface Views. Now we will add further processing to include the tweet data within each retweet and reply button. Before the end of your "bindView" method, begin as follows:
//get the status ID long statusID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); //get the user name String statusName = cursor.getString(cursor.getColumnIndex("user_screen"));
Remember that the "bindView" method is passed a Cursor object for traversing the data. Here we use the Cursor to retrieve the long ID value and String username for the current tweet. You will need the following additional import:
import android.provider.BaseColumns;
Now we will instantiate an object of our new StatusData class, passing the tweet data to the constructor method:
//create a StatusData object to store these StatusData tweetData = new StatusData(statusID, statusName);
The StatusData object contains everything necessary to send a retweet or reply for the tweet in question. We will now attach a reference to this object within the retweet and reply buttons for the tweet, so that we can access the information following user clicks. We use the "setTag" method:
//set the status data object as tag for both retweet and reply buttons in this view row.findViewById(R.id.retweet).setTag(tweetData); row.findViewById(R.id.reply).setTag(tweetData);
The "bindView" method also receives a parameter representing the row View in which the tweet is going to be displayed. If you look back at the update XML layout file, you will see that these two ID values are included for the buttons. We set the tag in each button to reflect the StatusData object holding the ID and username for the tweet displayed. Now we need to setup button clicks for these:
//setup onclick listeners for the retweet and reply buttons row.findViewById(R.id.retweet).setOnClickListener(tweetListener); row.findViewById(R.id.reply).setOnClickListener(tweetListener);
Here we specify a click listener to handle button clicks. Inside the listener method, we will be able to retrieve the StatusData objects of any retweet and reply buttons clicked. We are also going to allow users to click the username for a tweet in order to open the user profile in the Web browser. Add a click listener to that View here as well:
//setup onclick for the user screen name within the tweet row.findViewById(R.id.userScreen).setOnClickListener(tweetListener);
This will allow us to link into the Twitter Web interface so that users can access functions we have not provided within the app itself.
Step 6: Handle Button and Username Clicks
In your UpdateAdapter class, create an "onClickListener" to handle clicks, using the name "tweetListener" to match what we specified in the "bindView" method:
/** * tweetListener handles clicks of reply and retweet buttons * - also handles clicking the user name within a tweet */ private OnClickListener tweetListener = new OnClickListener() { //onClick method public void onClick(View v) { } };
Add the following additional imports to the Adapter class:
import android.view.View.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.widget.Toast; import android.net.Uri; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder;
Inside the "onClick" method we will implement clicks of both buttons plus the username. To detect which one has been clicked, add a switch statement:
//which view was clicked switch(v.getId()) { //reply button pressed case R.id.reply: //implement reply break; //retweet button pressed case R.id.retweet: //implement retweet break; //user has pressed tweet user name case R.id.userScreen: //implement visiting user profile break; default: break; }
Inside the reply case statement, we start the Tweet Activity class, passing the reply data so that the reply ID and username can be included when sending the tweet:
//create an intent for sending a new tweet Intent replyIntent = new Intent(v.getContext(), NiceTweet.class); //get the data from the tag within the button view StatusData theData = (StatusData)v.getTag(); //pass the status ID replyIntent.putExtra("tweetID", theData.getID()); //pass the user name replyIntent.putExtra("tweetUser", theData.getUser()); //go to the tweet screen v.getContext().startActivity(replyIntent);
Notice that we retrieve the tag for the pressed View, casting it as a StatusData object. We then call the public methods we provided within the StatusData class to return the tweet ID and user screen-name. We pass these to the Tweet Activity as extras, then start the Activity. At this point the user will be taken to the Tweet screen where the reply data will be used to implement replying to the correct tweet.
In the retweet case statement, we will retweet the relevant tweet directly, using the Twitter4J methods. First instantiate a Twitter object using the Shared Preferences plus your developer key and secret for the app:
//get context Context appCont = v.getContext(); //get preferences for user access SharedPreferences tweetPrefs = appCont.getSharedPreferences("TwitNicePrefs", 0); String userToken = tweetPrefs.getString("user_token", null); String userSecret = tweetPrefs.getString("user_secret", null); //create new Twitter configuration Configuration twitConf = new ConfigurationBuilder() .setOAuthConsumerKey(TWIT_KEY) .setOAuthConsumerSecret(TWIT_SECRET) .setOAuthAccessToken(userToken) .setOAuthAccessTokenSecret(userSecret) .build(); //create Twitter instance for retweeting Twitter retweetTwitter = new TwitterFactory(twitConf).getInstance();
This is the same technique we have used to instantiate the Twitter class before. We can now use the Twitter object to send the retweet. First we need to retrieve the StatusData object from the button that has been clicked:
//get tweet data from view tag StatusData tweetData = (StatusData)v.getTag();
Now we can attempt to retweet the update in a try block:
try { //retweet, passing the status ID from the tag retweetTwitter.retweetStatus(tweetData.getID()); } catch(TwitterException te) {Log.e(LOG_TAG, te.getMessage());}
All the Twitter object needs to send a retweet is the ID of the original tweet. However, let's give the user confirmation that their retweet was sent, still inside the try block:
//confirm to use CharSequence text = "Retweeted!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(appCont, text, duration); toast.show();
You can of course alter the message if you like. This is what it looks like:
Now let's allow the user to visit a Twitter profile page in the Web browser by clicking the screen-name within the current tweet, inside the "userScreen" case statement:
//get the user screen name TextView tv = (TextView)v.findViewById(R.id.userScreen); String userScreenName = tv.getText().toString(); //open the user's profile page in the browser Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(""+userScreenName)); v.getContext().startActivity(browserIntent);
Here we retrieve the user name as a text String from the View itself, which displays the screen-name as a String anyway. We build this into a Twitter profile page address, parsing it as a URI and instructing the browser to open it.
Step 7: Implement Moving from Home to Tweet
Remember that our main app Activity displays a button to take users straight to the Tweet screen. Let's implement that now. In your main Activity class, add the following inside your "setupTimeline" method, anywhere after you set the main content view:
//setup onclick listener for tweet button LinearLayout tweetClicker = (LinearLayout)findViewById(R.id.tweetbtn); tweetClicker.setOnClickListener(this);
The Tweet button ID matches what we included in the main timeline XML layout file. The main Activity class is going to handle clicks of the Tweet button. If you look at your "onClick" method within the main Activity ("TwitNiceActivity" if you used the name in the first tutorial), you should see a switch statement with one case statement for the "signin" button. Add a second case statement for the Tweet button as follows (before the default statement):
//user has pressed tweet button case R.id.tweetbtn: //launch tweet activity startActivity(new Intent(this, NiceTweet.class)); break;
Here we simply start the Tweet Activity. We do not need to pass any information to the Activity as in this case the user is simply launching it to send an ordinary tweet.
That's It!
That's our Twitter app complete! Run the app on an emulator or device to see it function. On first run you will of course have to consent to let the app use your Twitter account. You can optionally create a separate Twitter account to test the app with, rather than using your normal account. After authorization, you should be presented with the home timeline representing the most recent tweets from the accounts you follow. Test tweeting, retweeting and replying, as well as making sure your timeline is automatically updating at your chosen interval.
Advanced Topics
In this tutorial series we have created a basic Twitter client for Android. There are many ways in which you could enhance and improve upon the app, such as including the ability to view direct messages or to view user profiles within the app rather than having to use the Web browser. You could also make mentions of users within tweets clickable (i.e. linking any text String preceded by "@" to the profile page for that user). A similar process would allow you to support hashtags. More advanced Twitter clients also display conversations when selecting an individual tweet, showing replies in chronological order.
In terms of the application implementation, there are also enhancements you could consider. For example, in case the user has low connectivity, you could implement downloading the profile images as a background process. You could also implement some form of image caching to maximize on efficiency. Rather than the app automatically refreshing the ListView with new Tweets, you could implement a button at the top of the timeline, for users to control the display, with the button indicating how many new tweets are available. Finally, you could improve efficiency by running the Service in a separate Thread.
Thanks For Reading
Hope you've enjoyed this series on Creating a Twitter Client for the Android platform! As well as learning how to connect your apps to Twitter, you now have experience of using an external library plus a variety of Android platform resources such as Databases, Adapters, Services and Broadcasts. These are all key skills your future Android projects will benefit from. The downloadable source code contains additional notes you may find helpful.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/creating-a-twitter-client-for-android-tweeting-retweeting-and-replying--pre-30666 | CC-MAIN-2018-22 | refinedweb | 2,956 | 53.81 |
LoPy4 stops receiving LoRa messages
Device A: LoPy4 (the one experiencing the problem)
Device B: LoPy4 (works fine)
The system works as follows:
Device A:
- A transmits a message to B
- A then waits for acknowledgement from B
Device B:
- B waits for message from A
- B then transmits an acknowledgement to A
The system works fine for some time, but eventually device A becomes unable to receive messages. Device B is definitely transmitting the acknowledgement message (confirmed by listening using another device), but device A behaves as if it is not receiving any messages.
I then set device A to perform a hard reset (with machine.reset()) once it gets to this stage of being unable to receive, but once it boots back up and continues the operation it is still unable to receive anything. The only way get it to start working is to physically disconnect and reconnect the power. The issue occurs very unpredictably; sometimes the system works for a long time before it happens, other times its quite quick.
I am unsure if a soft reset will work, because Im not sure how to get the program running again afterwards.
The issue is not the device hardware because I tied using a different LoPy4 but the issue persisted.
Im using different channels to transmit and receive for other parts of the system, therefore every time the device switches between transmitting and receiving for the various different functions it recalls the LoRa() constructor and defines all the parameters (including the power mode as always on). Additionally, the socket is opened and closed for every transmission or reception. (Maybe this has an effect?)
- Paul Thornton last edited by
Glad you (sort of) fixed your issue. Ill ask internally about this. I dont see why it should fail with both Wifi + Lora running.
Ok so I never figured out why it happens but the problem occurs when you remain connected to Wi-Fi and continue to perform LoRa communication. The workaround for this was to disconnect Wi-Fi before doing LoRa comms, and then reconnecting to do the Internet stuff.
Ok, so I've discovered that the issue doesnt occur if I remove all of the code regarding connecting to Wi-Fi and the sockets for communicating with the database, meaning that all thats running is the LoRa comms between the devices. This was confirmed by allowing the cleaned up (no Wi-FI or DB) system to run for over 500 iterations. The issue usually presents itself from anywhere between 5 to 100 iterations. If I simply add back the code for connecting to Wi-Fi, then continue with the rest of the program (not doing anything with the internet connection like opening INET sockets) the issue occurs, whereby eventually Node A stops being able to receive any LoRa messages. I have the following code in boot.py for connecting to Wi-Fi, and It is this code that seems to be causing the issue, but I havent yet discovered how to solve or isolate it further.
import machine from network import WLAN wifi_pwd = wifi_ssid = wlan = WLAN() if machine.reset_cause() != machine.SOFT_RESET: wlan.init(mode=WLAN.STA) wlan.antenna(WLAN.INT_ANT) wlan.ifconfig(config=('192.168.0.144', '255.255.255.0', '192.168.0.1', '192.168.0.1')) if not wlan.isconnected(): wlan.connect(wifi_ssid,auth=(WLAN.WPA2,wifi_pwd)) while not wlan.isconnected(): machine.idle() # save power while waiting print("Connected to Wifi\n") print(wlan.ifconfig()) machine.main('main0.py')
The following code comes from the relevant parts of Node A.
_BANDWIDTH = LoRa.BW_250KHZ _SF = 7 _RSSiTHRES = -100 _TXPOWER = 14 _PR = 8 _CR = LoRa.CODING_4_8 _PM = LoRa.ALWAYS_ON _CH1 = 867875000 _CH2 = 868875000 while (1): # RF1 try : # TRANSMIT TRIGGER(10) msg = "BS2RF1" pkg = struct.pack(_LATERAL_DL_FORMAT % len(msg),RF1,DEVICE_ID,len(msg),1,measCount, msg) while(lora.ischannel_free(_RSSiTHRES) == False): print("__________________Channel is busy____________________") lora_sock.send(pkg) print('SENT RF1 TRIGGER') pycom.rgbled(0x0F0F00) # RECEIVE CONFIRMATION(TT) while (True): received_pkg = lora_sock.recv(64) if (len(received_pkg) > 2): if (received_pkg[0] == DEVICE_ID) and (received_pkg[1] == RF1): received_msg_len = received_pkg[2] dest, src, _,cd, rx_msg = struct.unpack(_LATERAL_UL_FORMAT % received_msg_len, received_pkg) if ((received_pkg[3] == 3) or (rx_msg == b'RF12BS')): print(src,' sends: ',rx_msg) break time.sleep(0.02) print("Done receiving RF1 CONFIRMATION") pycom.rgbled(0x00FFFF) time.sleep(0.1) break except usocket.timeout as err: print("----------------timed out rf1 reception")
The Node is able to transmit the trigger (as I can see that it gets received on Node B), but when trying to receive it doesnt detect any messages, and therefore gets stuck in an infinite loop. Ive tried breaking it from the loop once it gets stuck and continuing with the other TX and RX operations but its meets the same issue of not being able to receive.
@jokr2 I think you'll have to share the relevant parts of your code so that other people are able to reproduce your issue. | https://forum.pycom.io/topic/3981/lopy4-stops-receiving-lora-messages/1 | CC-MAIN-2019-13 | refinedweb | 824 | 53.41 |
.
Recently I added support for asynchronous operations to the Python client of PackageKit. And on top of this a set of PyGTK widgets which make using PackageKit quite comfortable. The code is part of today's 0.3.10 release.
The following widgets help to visualise the status and progress of a transaction:
* PackageKitStatusIcon
* PackageKitStatusAnimation
* PackageKitStatusLabel
* PackageKitProgressBar
* PackageKitCancelButton - allows to cancel a running transaction
* PackageKitProgressDialog - provides an all-in-one solution of the above widgets
* PackageKitMessageDialog - presents messages and errors from PackageKit
Here you can see a video of the demo application in action. As a prove of concept I replaced the call of Synaptic in gnome-app-install by PackageKit. Here is the corresponding screencast.
The following code snippet installs the package xterm with a graphical progress dialog:
from packagekit.client import PackageKitClient
from packagekit.gtkwidgets import PackageKitProgressDialog
from packagekit.enums import *
def on_exit(trans, exit, runtime):
'''Handle exit state of a transaction e.g. erros or EULAs'''
pass
# Initialize the client
pk = PackageKitClient()
# Get packages which provide xterm
packages = pk.Resolve(FILTER_NONE, "xterm")
# Setup the transaction to install the first package
trans = pk.InstallPackages([packages[0].id], exit_handler=on_exit)
# Initialize the dialog window
dia = PackageKitProgressDialog()
# Connect the transaction to the dialog and run it
dia.set_transaction(trans)
dia.run()
The API is not yet set into stone. So I am open for comments and feedback!. …
Derzeit läuft im Deutschen Theater in München noch das Musical “In nomine patris”. Wollte ich unbedingt sehen, die Werbung vorab machte mich neugierig. Und zudem ist Münchens Musicalbühne während des Umbaus ihres Stammsitzes in ein interessantes Zeltkonstrukt am Stadtrand ausgelagert - allein das war schon interessant zu sehen. Dank der Freikarten einer Kollegin (danke Nadine & Steffi) durfte ich dann auch auf den besten Plätzen dem Musicalerlebnis beiwohnen.
War für mein Empfinden guter Durchschnitt, nicht sonderlich schlecht, aber keinesfalls auch nur annähernd in der Reihe der echten Erlebnisse. Aber das ist ja nicht verwerflich, es kann nicht nur Top-Events geben.
Tja, und heute flattert mir eine Werbemail des Deutschen Theaters in den Posteingang:
Wer´s glaubt wird selig!
„… banal, handgreiflich wirkungsbewusst konstruriert (…) für den jeweils billigsten Geschmack…“
(Süddeutsche Zeitung 1961 über die Deutschlandpremiere der „West Side Story“)
„Was für ein Kaiserinnen-Schmarrn“
(Die Presse Wien 1992 über die Uraufführung von „Elisabeth“)
„Himmelschreiender Blödsinn (…) Da hilft nur beten”
(Münchner Merkur 2008 über „In Nomine Patris“)
Auch Kritiker können irren. Viele Stücke, die nach ihren Premieren den Verrissfedern zum Opfer fielen, wurden dennoch große Erfolge. Und wir machen nach wie vor Programm für unser Publikum und nicht für die Kritiker.
“Hier ist eine Panne unterlaufen, allerdings nicht der Eröffnungspremiere oder dem Musical, sondern Frau Dultz; nicht das Stück ist „himmelschreiender Blödsinn“ sondern die Kritik, deren flapsiger Ton alles andere als angemessen ist. …”
Ähm, ja. Geht’s noch? “In nomine patris” auch nur annähernd mit der “West Side Story” zu vergleichen - Blödsinn. Und dann ist natürlich die böse Presse wieder mal schuld.
Bleibt mir nur zu sagen: Amen..
Every now and then I try to do some more clean up of developer.gnome.org, aiming to move any good content to.
I.
You can now import CSV (comma-separated) data in to the current table. The assistant helps you to choose the field mapping, showing you sample data for the first few rows.
Johannes implemented this..
Armin built Glom and its dependencies (apart from Avahi) on Windows and created an experimental installer.
Armin and Johannes also updated Glom’s client-only Maemo.
Interesting, this year’s IT trade fair SYSTEMS, which currently takes place in Munich, is the last after 40 years. The concept will be reorganized and next year there will be two more specialized events in Munich. See the press release.
So it is the last time the “Perspektive Open Source” is active, I think.
I’m looking forward to see what will happen next year
I just copy the text from:
The City of Munich is currently looking for new Java developers to support our office migration. One of your main tasks would be working on the improvement of the WollMux.
For more information on all open jobs see
or use the direct link to the Java Developer job offerin.
And we’re also looking for developers in the field of Linux, especially Debian GNU/Linux. For more Information on this topic see this page.
Today the IT trade fair SYSTEMS starts in Munich. If you are interested in the progress of LiMux, the functionality of WollMux or have any other questions please feel free to visit our booth at hall B2.
We share the booth with our cooperation partner, the german Ministry of Foreign Affairs - they are also switching to Open Source.
See you at SYSTEMS (I’ll be there on thursday).
Nevertheless he managed to get a lot of momentum to the team by doing a great job in the last weeks!
You can download Jochens and mine presentation as PDF or as ODP.
So Facebook pretty much missed the German market. There is StudiVZ which has about 10 times as many users in Germany than Facebook has, and which is sometimes called "red facebook" because of the similarities. Then there is "green facebook", Lokalisten, which had started quite regional (and invitation-only), but expanded since, and also is like 2-3 times the size of german Facebook.
So apaprently Facebook now decided they need to compete more in the German market, and started a marketing campaign. As part of this campaign, Mark Zuckerberg, founder and CEO, gave a talk in Berlin and Munich. The marketing company uses a strategy where they try to push these two cities to compete for having the largest fb userbase in Germany.
The talk was okay, I would have wished for more entrepreneural chat; but only a few of the questions were along these lines (e.g.: "when did you know you had something big?"), instead some usual feature requests came up ("Why can't I prevent others from tagging me on photos?")
But the largest kudos I have to give to facebook is for actually finding so many "ambassadors" that will do advertisement for them for free. Well, they got a T-Shirt (that does a word play on "blue" and "taking a day off", although it should probably say "I'm doing free promotion for fb and all I got is this T-Shirt")
It probably only works because Facebook on one hand has always been free, is a "hip web2.0 thing", and they're trying to play "good guys" just like Google does ("don't be evil"). Many people don't understand how despite the privacy functions in Facebook people can still get their data with just some old-style social engineering very easily (so no actual data manipulation or abuse required, but when you do it the right way, just about everybody on facebook will just give you his data voluntarily).
Sometimes all this Web2.0 fanboying can be quite scary, but I figure that is just the way people and societies work.
Catching up a bit (this was like three weeks ago):
The Google Developer Day in Munich in September. Lots of people there (500?). The event was mostly what you'd expect from Google (colors everywhere, geek toys around to play with, ...). Although I had expected that, I still was somewhat disappointed. The talks mostly covered APIs. Some at least showed demos of what is possible with the latest revisions, but some where a bit like "this is how you query the number of views for a YouTube video". For someone who has been using different APIs for years it's just much more convenient to look it up in the online documentation when needed.
But I don't blame Google for that; I think it was what many visitors expected. The reason I actually went there wasn't for the talks, but to talk to Google people, to maybe establish some link between the university and Google (however it seems that Google in Munich mostly does mobile stuff, which is not too relevant for our group).
Jochen Skulj and I are doing an introduction talk to Ubuntu translations and especially the German speaking team at this year's Ubucon which will happen this weekend. See ubucon.de/index.php/programm
Furthermore there will be a translation sprint on Saturday afternoon. This is a great chance if you are interested in the translation, want to become a translator or know of any highly visible bug that we haven't spotted yet.
Am letzten Freitag (10.10.08) haben sich Kathrin und ich das gegenseitige JA-Wort gegeben. Danach ging’s mit der Kutsche durch den Englischen Garten und zur Feier ins Seehaus, wo uns die geladenen Gäste schon erwarteten.
Ein schöner Tag
For.
On my parents' small laptop, Windows would just reboot. Even the repair functions of Windows would just reboot. No error message you could read, just reboot, repeat. Linux still worked fine (and my family is fine with using Linux, fortunately).
Linux also allowed us to quickly find out what is wrong with Windows: the hard disk is damaged (I like operating systems that give you useful error messages such as "Unrecoverable Error" on your harddisk). And most likely the laptop is out of warrenty since a month ago, as usual.
So I'm now investigating if the Linux partition also contains hardware errors, or if we might get away with just disabling Windows altogether for some time, until I get around to buy a replacement harddisk (and a replacement battery, too). So far, our experiences with Medion/Aldi/Tchibo have been rather bad. The TFT screen for the main computer is often flickering, but they failed to repair it in two attempts now. The MP3-CD-Player had stopped reading and the replacement didn't play MP3 at all. And the laptops batteries were crap (and why did they put in two small batterys instead of a reasonably sized one?), I know of a friend where the CD drive of that same model doesn't work anymore, and now our harddisk is dead with just some 11 days of use total (it was meant to be a portable system, and my parents have better computers for daily use at home).
If we buy a replacement, it will most likely be a so called "Netbook" with Linux preinstalled. These tiny systems often come preinstalled with Linux (because a Windows licence would increase the price by like 50%) and would fit our requirements pretty well. Not sure which one, though. Maybe an EEE.:
I:
Compare for yourself: Which of the two statements is positive, psychologically:.
Ich kann meinen Landsleuten an dieser Stelle nur gratulieren, sofern sich die Hochrechnungen einigermaßen bewahrheiten (man denke nur an die legendäre “wir haben die Wahl gewonnen”-Rede von Eddi).
Als letztes deutsches Bundesland hat Bayern heute, immerhin fast 19 Jahre nach dem Fall der Mauer, die “Diktatur” einer Partei abgeschafft.
Zeit wurde es und Demokratie funktioniert anscheinend doch noch!
Und der stärksten Kraft im Landtag gratuliere ich auch zu 40+x
Eine Demokratie ist krank, wenn es eine absolute Mehrheit gibt. Eine gesunde Demokratie hat mehrere starke Parteien und schwache Parteien (ohne übermäßig zu zersplittern), die nur zusammen eine Regierung bilden können. Nur so ist ein Pluralismus gewährleistet, und dass der Normalbürger mit seinem Wahlverhalten noch Einfluss üben kann, und nicht die "Parteioberen" alleine entscheiden was passiert.
Sein Wahlverhalten sollte man an diese Situation anpassen, und mit beispielsweise den Freien Wählern steht ja inzwischen eine sehr ähnlich orientierte Partei flächendeckend als Alternative zur Union zu verfügung. Wer etwas offener für neue Ansätze und Reformen ist, der ist aber nach wie vor besser bei den Grünen aufgehoben.
Kleine Parteien wie die ÖDP - so sympathisch sie auch sein mögen - werden bei dieser Wahl vermutlich keine Chance haben, diesen eine Stimme zu geben ist eher kontraproduktiv, und erreicht eigentlich nur das nominelle Ergebniss der anderen Parteien zu reduzieren und die Wahlbeteiligung zu verbessern. Solange aber eine andere Partei nicht gerade eben unter die 5 %-Marke rutscht ändert sich nichts am Ergebnis (d.h. das wäre eine Stimme für "Hauptsache nicht Die Linke")
Für die Demokratie in Bayern wäre ein Ergebnis wie CSU 40%, SPD 20%, Grüne 12%, Freie Wähler 11%, FDP 10%, Sonstige zusammen 7% ganz realistisch und wünschenswert.
Dazu brächten wir nur ein paar mehr Wähler für die kleinen Parteien. Sucht euch eine aus, es ist für jeden etwas dabei!
[Disclaimer: Ich bin Mitglied bei den Grünen in Bayern.].
I retired from the German Ubuntu translation team. I already stopped translating some time ago and it was getting harder and harder for me to find the motivation and time to work on the coordnation of the team. So it was time for a clear cut.
The troubles of an Ubuntu translator are well known and documented, so I won't complain here again.
Thanks to all the translators and the Rosetta developers. who are not always in a nice position.
I am still open to technical questions and will be at the Ubucon, the German Ubuntu Users Conference, in Götting from 17th to 19th October.
Ma.
Jetzt sind langsam wieder alle da, die bayrischen Sommerferien enden heute. Nichtsdestotrotz liefen die Planungen weiter und ab dem morgigen Montag beginnt die Herbsttour.
Zunächst steht am 16.9.08 in Leipzig ein Treffen mit Vertretern des Sächsischen Landkreistages auf der Mittelstandsmesse Komkom an. Gerade in den neuen Bundesländern ist freie Software zuletzt immer öfter ein Thema, das Interesse seit Jahren auffällig groß.
Als nächstes wird das Open Source Observatory and Repository der EU Kommission (OSOR) auch offiziell eröffnet. Das findet im Rahmen der OpenSourceWorldConference in Malaga am 20.10.08 statt - und wir sind mit unserem WollMux als Gründungsmitglied natürlich vertreten. Derzeit läuft auch noch eine Anfrage, ob wir im allgemeinen Teil der imho überwiegend von Spaniern besuchten Konferenz über LiMux an sich informieren möchten… mal schauen ob’s was wird.
Direkt danach beginnt in München vom 21.10. bis 24.10.08 die SYSTEMS und diesmal ist LiMux sogar an zwei Ständen im Themenpark Perspektive Open Source vertreten. Einmal zusammen mit dem Auswärtigen Amt (dazu später mal mehr) und dann noch genau gegenüber zusammen mit unserem für Personal- und Organisation zuständigen Bereich. Nachdem München seit Monaten immerwieder gute Jobs im IT-Bereich an ganz unterschiedlichen Stellen bietet, möchten wir gemeinsam die attraktive IT-Arbeitgeberin “Stadtverwaltung München” darstellen.
Und zu guter Letzt noch ein kleines Schmankerl: auf Einladung der OpenOffice.org Community präsentiere und diskutiere ich unser Projekt auf der diesjährigen OpenOffice.org Conference vom 5. bis 7.11.08 in Peking. Dazu sicher später mehr.
I.
Today.
Mal wieder typisch, die kleinen Wahl-Fast-Lügen der Parteien.
z.B. die CSU, die "verspricht" in Bildung und Forschung zu investieren.
Nur dass das überhaupt nicht der CSU-Politik entspricht:
Statt ein Studium attraktiver zu machen wurden Studiengebühren eingeführt und Mittel gekürzt. Und das obwohl wir vor einem enormen Defizit an Hochqualifizierten Arbeitskräften stehen!
Dann währe da noch die Schulreform, bekannt als G8. Statt hier in den dringend benötigten technischen Fächern wie Physik auszubauen wird dort gekürzt, einiges gar zu "ferner liefen" degradiert. Nicht sehr zukunftsträchtig für das Ingenieursland Deutschland.
Der Trick der CSU ist ganz einfach:
Sie versprechen über 1000 neue Stellen - mit dem Wissen dass sie diese nicht besetzen können. So kann man leicht "investieren", ohne das Geld konkret ausgeben zu müssen.
Angeblich hat das Kultusministerium schon jetzt Finanzmittel eingeplant für 2000 neue Lehrerstellen, es gibt nur keine Lehrer um diese Stellen zu besetzen. Und nach Berechnungen der Grünen wurden übrigens seit 2004 über 320 Lehrer-Stellen gestrichen.
Update: ich habe noch einen Trick der CSU gelernt: die Stellen sind alle befristet auf 1 Jahr. Dadurch kann man jedes Jahr wieder 1000 "neue" Lehrer einstellen ... ohne dass sich wirklich irgend etwas ändert, außer dem Verwaltungsaufwand und dass es halt technisch gesehen keine "Lüge" ist.
If you are working with Eclipse on a Java project, make sure to try a regular (ant) build from time to time. The eclipse compiler sometimes differs quite a lot in what it accepts (especially when it comes to generics it seems to be a bit more clever) or considers a warning.
No, I did not just disable a warning. Eclipse did report some "serialVersionUID" warnings, but it missed lots of them, too. I have the vague impression that the Eclipse java compiler didn't recognize that a class implementing the "Externalizable" interface also should have a serial version UID.
And unfortunately I didn't find a way to reach the serial UID generation quickfix without having an eclipse warning... Well, after all there is not much wrong with starting the serial version at 1L.
Due to their implementation by erasure, they face certain limitations.
For example, the following constructor for a class with both compile time and runtime type checking:
class BagOf<T> { BagOf(Class<T> restrictionClass); }is not satisfiable when T is a generic class itself (since there is no ArraySet<Double>.class syntax, for example). The best work-around I know is to drop the T subclassing restriction for restrictionClass:
class BagOf<T> { BagOf(Class<?> restrictionClass); }
The cost is low (obviously no difference at runtime) - you just don't assert that the developer using your class specifies a restriction class derived from the class T used in the generics. That won't prevent certain programming errors such as this anymore
BagOf<Integer> bar = BagOf<Integer>(Double.class)but these shouldn't be too hard to find/fix anyway.
Before submitting too clever suggestions, please make sure you've tested them. For example "if (obj instanceof T)" is not valid java code: since generics are implemented by erasure, T cannot be referenced in runtime statements.
P.S. It would obviously be nice if the Java syntax would allow Foo<Bar>.class (which at runtime would be the same as Foo.class, and at complie time would have the result type Class<Foo<Bar>>), but currently it does not for all I know.
P.P.S. I'm not looking for "Class<? extends T>", that is a different situation. The difficult case is when T is a Generic itself, not a subclass.
Update: JM Ibanez pointed me to Neal Gafter's Super Type Tokens, which apparently are the same as TypeLiteral in Google Guice. Thanks!
... might be due to a bug in Sun Java 6. Try upgrading to Java 6 Update 10 release candidate (also known as 'beta') or using a different Java VM such as IBMs or GNU. Worked for me.
Bug reported in Feb 2008 and Bug reported in Oct 2008 at Sun (note: they are marked as 'fix delivered' but that includes beta releases such as the 6u10RC linked above.
Seit Anfang dieses Jahrzehnts kombinieren sich zwei Arten des Projektcontrollings auf unheimliche Weise.
Zunächst einmal wird aus dem innerbetrieblichen Controlling, das aufgrund bewährter Strukturen bereits per se in der Lage ist, effizient und effektiv zu arbeiten, immer öfter das externe Controlling. Denn nur externe sind tatsächlich objektiv.
Des Weiteren wird aus dem normalen Controlling, das den Auftraggeber und die Lenkungsrunde bei der Steuerung unterstützt, das proaktive Controlling. Dieses greift bereits während der Entstehung von Ergebnissen ein und steuert hilft bereits der Projektleitung beim Steuern.
In Kombination natürlich richtig effizient. Proaktives externes Projektcontrolling, der Traum aller Verantwortlichen Auftraggeber. Bei Projekten die damit gesteuert werden, kann eigentlich nichts mehr schief gehen. Ein Werbespruch: “diese 2-5% des Projektbudgets sind ihre Lebensversicherung”.
Braucht man pEPC wirklich? Meiner Meinung nach nein, dahinter versteckt sich lediglich die von Beratungsunternehmen (neudeutsch: Consulting) geschickt verpackte Gelddruckmaschine.
Beispiel Ergebniscontrolling: Während früher z.B. Ergebniscontrolling darin bestand, die Erreichung von Meilensteinen (sowohl zeitlich als auch stichprobenweise inhaltlich) qualitätszusichern, wird im modernen pEPC bereits vorab der Prozess der Ergebnisfindung umfangreich begleitet. Klingt doch gut, oder?
Kann zu seltsamen Konstellationen führen, wenn für die Ergebniserstellung ein anderer Dienstleister verantwortlich ist. Man stelle sich vor: eine ressortübergreifend besetzte Arbeitsgruppe erarbeitet zu einem Thema ein Ergebnis, das danach zunächst durch die Projektleitung und dann die Lenkungsrunde abgenommen werden soll. Da es sich um ein komplexes Thema handelt hilft dabei ein Dienstleister mit. Nimmt man das proaktiv in pEPC ernst, dann wird der pEPC bereits während der Ergebnisfindung eingebunden, nicht erst wie früher üblich bei der Ergebnisabnahme. Hallo? Zwei Dienstleister für das gleiche Thema? Noch dazu muss der pEPC definitiv irgendetwas sagen, sonst würde auffallen, dass er überflüssig ist. “ihre Lebensversicherung”.
Beispiel Kostencontrolling: Große Projekte drohen oftmals bei den Kosten aus dem Ruder zu laufen. Deshalb leuchtet es ein, dass sich außerhalb des Projektes (muss es außerhalb des Konzerns sein?) noch jemand mit dem Mittelverbrauch des Projektes beschäftigt. Es sollte dabei die Planung und der jeweils aktuell tatsächliche Verbrauch im Auge behalten werden und gerade bei längeren Verträgen mit externen stichprobenweise geprüft werden, ob die Leistungen mit dem Auftrag vereinbar sind. Ist nur oftmals nicht zuviel zu tun und das fördert die Tendenz des externen pEPC, sich allumfassend um jede Ausgabe zu kümmern. Da wird dann schnell mal hinterfragt, warum 21,50 Euro hier und nicht dort verbucht wurden. Arghs.
Klar ist der Controller der natürlich Feind des Projektleiters. Der Versuch, diese Tatsache durch die Neudefinition von Tätigkeiten zu verschleiern und letztlich die Auftraggeber in trügerischer Sicherheit zu wiegen, gleichzeitig jedoch nur Mehrausgaben zu erzeugen, halte ich für den falschen Weg.
Liebe Consultants die pEPC anbieten: beweist mir bitte, dass mit eurem Ansatz Projekte tatsächlich besser gelaufen sind und Überschreitungen (Zeit, Budget) vermieden wurden.
There.
As some might know, I've been working at the university for a few weeks now. I'm very happy how it all worked out, because of the people there and the subjects to work on. It's just great to think through some mind-bending index structure to improve reverse-k-nearest-neighbor queries. And the professor (who is very well known for his work on R*-Trees, the X-Tree, and the DBSCAN and OPTICS algorithms) really manages to aggregate excellent people.
(rkNN is the problem of finding those points for which a Nearest Neighbor Search [Wikipedia] would return the given point. There are many use cases for example in location based services.)
A lot of my work involves a framework which has been published recently on the SSDBM 2008 conference: ELKI - Environment for DeveLoping KDD-Applications Supported by Index-Structures
The goal of ELKI is to become what WEKA is for machine learning. And it's well on it's way for that.
ELKI aims at the data mining researcher, it's not designed to squeeze out the last bit of performance. Instead it allows you to compare different algorithms, try different index structures (including various spatial and metrical trees) and offers all kinds of functionality you can reuse. If you are planning to do some real world applications, it likely is still useful for prototyping.
In the last weeks I've already put quite some effort in ELKI, so expect the next version to be released with significant changes and new functionality. In fact some working functionality was just left out of the release because we hadn't cleaned up the code yet.
Currently, getting started with ELKI can be a bit tricky. It's not hard to use, but you just need to find out where to start. The next release will therefore include a "dummy algorithm" that mostly serves as being a template for implementing custom algorithms (it can also be used for benchmarking an index structure, though).
Many people are already aware of the amount of data Google can (and does) collect on them. Some people therefore refuse to use certain google applications altogether. Others just like them too much.
There are some services that won't work with heavy ad blocking and anonymizing services - others will work just fine. A prime example everybody uses is Google search.
Google search will work just fine if you use anonymizers. Google Mail won't.
Privoxy and TOR is a great combination for anonymizing, however you won't want to use them for bandwidth-heavy web surfing, and there is little benefit of using them for web sites where you authenticate anyway.
Here's a way to do a compromise:
function FindProxyForURL(url, host) { var google = /https?:\/\/([^/]*\.)?google\.[a-z]*($|\/)/; var tor = /https?:\/\/([^/]*)\.(exit|onion)($|\/)/; if (google.test(url)) { if (shExpMatch(url, "*.google.com/mail*")) { return "DIRECT"; } return "PROXY 127.0.0.1:8118"; } if (tor.test(url)) { return "PROXY 127.0.0.1:8118"; } if (shExpMatch(host, "config.privoxy.org")) { return "PROXY 127.0.0.1:8118"; } return "DIRECT"; }and point your browser to it.
{ +client-header-filter{hide-tor-exit-notation} } .exit { +filter{js-events} +crunch-all-cookies } .google./(search|blogsearch|scholar|images)And don't forget to reload privoxy.
When using Google Search (including image, blog and scholar search, feel free to add additional services) you should be seeing a login button, while you could be accessing Google Mail at the same time in another tab.
This list is of course not exhaustive. You might want to actually use privoxy and TOR by default, and only disable it for certain sites (or configure privoxy accordingly). You get the idea: this is just a very minimal approach to disable tracking exactly by the Google search site. It all depends on how serious you are about privacy and how important data throughput is for you.
Also it will allow you to access certain TOR functionality (such as hidden services) without running TOR all the time (after all, it is and will always be slower than direct access).
[Update: apparently some TOR exit nodes trigger a spam protection on Google, and without cookies you can't solve the captcha. So the use of TOR doesn't work well with Google. All the privoxy cookie blocking however is still recommended.]
Last._pcspto.
Before”.
YouTube video demoing a book with 3D pop-up letters. Very cool, even when the video requires Flash to watch.
From my security monitoring:
suhosin[25775]: ALERT - tried to register forbidden variable '_SERVER[DOCUMENT_ROOT]' through GET variables (attacker '67.19.104.82', file '[...]')
The web logs contained:
GET //?_SERVER[DOCUMENT_ROOT]=?? HTTP/1.1
Is this some new PHP attack vector (that happens to be blocked by the suhosin security module)? I thought it was related to ConPresso, but I've also found similar accesses in my logs that were on sites that don't use PHP (and thus did not trigger a suhosin alert). Obviously these don't relate to ConPresso, so it seems more like a brute force / mass attack?
Another host involved:
80.93.54.47 ... GET /index.php?_SERVER[DOCUMENT_ROOT]=? HTTP/1.1
That referenced URL still works, so if you want you can retrieve the 'exploit' code. But all it apparently does is to try various methods to execute "id", probably to locate web servers that are vulnerable and maybe even running as "root" user.
Obviously this is a brute force; that site doesn't have an index.php.
Is that anything new? Or is it just some script kiddie trying to re-use an aged exploit? But on the other hand, I havn't seen such a suhosin alert in months. Anybody knows which PHP script might be vulnerable to this attack vector.
If you've got any details, contact me at erich@debian.org; my blog intentionally does not have comments or trackbacks.
[Update: I've received two mails pointing out that such vulnerablities are found in some PHP apps every now and then, so it might just be some script kiddie scanning brute force once more. Supposedly this cannot be exploited when register_globals is off and/or suhosin is used.]
To give some update on the state of OpenSync in Debian, I have uploaded libsycml-0.4.7 to experimental a couple of days ago. This is significant in sofar as a lot of development and bug-fixing (mostly by Michael Bell) happened for this release, as well as some committment to maintaining an API and at least responsively versioning the library. In order to use libsyncml-0.4.7 with OpenSync, a newer libopensync than 0.36 is needed; however, current OpenSync trunk has seen a lot of changes in plugin handling and plugins need to get ported to the new API.
So I uploaded the last known-working revision of OpenSync along with corresponing revisions of the file-sync and syncml plugins, the vformat module and a rebuild of msynctool to experimental for now. I did not have the time or energy to migrate/upload the other plugins yet, and as it seems that OpenSync-0.37 will only ship with ported file-sync and syncml plugins, it might not make much sense. I also took over maintainership of the related wbxml2 package, and upload a patch by Michael Bell which seem to fix a lot issues people are having with SyncML.
The good news is that it seems all of the new features for a 0.40 stable OpenSync release have been finished according to the roadmap , most notably a common plugin configuration system and the machinery for a migration path from 0.22 to 0.40 configurations (plugins still need to support/implement that I believe), so no more big API changes are expected and the focus will be on bugfixing and plugin discovery from now on. This means developers will be able to start porting their plugins to the 0.40 API once 0.37 is out and front-end authors can start to take a look at the architectural changes which were made to facilitate their jobs.
My hope is that conduit will be able to leverage the OpenSync technology and introduce a solid GUI for this (as kitchensync does for KDE), making syncronization finally work on the desktops.
From the Debian packaging point of view, I have been mostly on my own now for the last couple of months. However, I recently registered an Alioth project in order to maintain the packages in a subversion repository (I have not yet decided whether it is worth importing the 0.22 packages targetted at lenny), and people who are interested in helping should contact me.
As mentioned earlier, I've uploaded a new Pyroman release to Debian. I've also updated the download at the download page on alioth for the non-Debian users.
There is just one single user-visible change (under the hood I switched some Python API so you need python 2.4+ now, which was available in sarge already):
This version has a new command line option, "--verification-cmd". This can be used to point to a script file to verify network connectivity. For example, you could try to send a ping to the next router, or you could ssh to another host, have it ssh back and touch a flag file in /tmp to signal success.
Similar to the --safe option, it is meant as a safety feature to avoid locking yourself out of your system. But while --safe needs to be used interactively, this new command could be used when automatically activating new firewall rules, e.g. triggered by cfengine or some other configuration management. If the verification command does not succeed, the firewall rules will automatically be rolled back to the previous state.
Note that I didn't get around to add IPv6 support yet. It would definitely be desirable to add ip6tables support, but I currently do not have any experience with IPv6, so I'm not sure I'd know how to do things right. Of course I'd welcome any patches.
(In case you havn't read about pyroman yet - it's yet another tool to configure iptables firewalls. It puts a thin abstraction layer on top of iptables, but the main benefit is that it uses "iptables-restore" to quickly mass-set all the firewall rules - other tools tend to invoke several hundred iptables processes to achieve the same - and if any error occurs it will both give you a clear indication of which rule caused the error and rolling back your firewall to the previous state.).
My advisors just told me my grade for my final thesis I handed in two weeks ago: a 1.0 (which is the best possible grade here).
Well, they've been quite clear about this being the likely result before, since the thesis worked out very well, with a publication on a good conference and such. So right now I'm looking forward to continuing this research and doing a PhD degree. Right now, this would be my favorite option, if I manage to get a position at the university.
N:
Since?
I.
It turns out that the tab implementations were just mockups. Have fun at GUADEC! | http://www.munichblogs.com/subcultures/opensource/ | crawl-002 | refinedweb | 5,455 | 63.19 |
$ cnpm install babel-plugin-transform-named-imports
This plugin attempts to transform named ES6 imports to default imports:
// from this import { myFunc } from 'mymodule'; // to this import myFunc from 'node_modules/mymodule/myFunc';
The former causes
mymodule/index.js to be imported, and therefor all other classes and methods to be imported as well. By transforming the import, tree shaking is far more effective and you can be assured that code that you're not using does not end up in your bundle.
This plugin aggressively transforms all imports thay pass to Babel. If you have any
index.js files that have side effects, i.e code that executes on import, do not use this plugin. That code will never make it into your bundle with this plugin. To be on the safe side, do not run your
node_modules through Babel. It might cause problems with libraries that rely on the behavior described above.
This is not a silver bullet. If your code does not rely on side effects, then you can expect this plugin to work well. If you do have code with side effects, then we strongly recommend that you do not use this plugin.
When you use a named export, Webpack actually pulls in the entire module. It should tree shake the things you don't actually use, leaving you with only what you actually use.
Unfortunately, Webpack often decides not to remove something because of potential side effects. By always importing from the file the function/class was declared in, you could avoid accidentely pulling in a large module. This would make importing very cumbersome.
This plugin attempts to rewrite your imports to always import from the file in which the function/class was declared in.
Install the package from NPM:
yarn add --dev babel-plugin-transform-named-imports
Add
transform-named-imports to your Babel configuration:
"plugins": [ "transform-named-imports": { "webpackConfig": "./webpack.config.js", "webpackConfigIndex": 0 } ]
Given a file that looks like this:
import { myFunc } from 'myModule';
For every import statement, resolve the full path to
mymodule and parse the file:
import myFunc from './myFunc'; export { myFunc };
Analyze the imports/exports in the resolved file and keep recursing until the file is found in which
myFunc was declared.
Rewrite the original import to lead to the file in which
myFunc was declared:
import myFunc from 'node_modules/mymodule/myFunc.js';
Why is my webpack configuration required?
In order for the plugin to find the file in which a function/class was declared, the plugin has to resolve imports. Babel itself doesn't concern itself with importing, just rewriting code. Your webpack configuration is required so the plugin can resolve paths exactly how they're supposed to be resolved.
Does this handle aliases?
Yes.
Can I exclude certain paths?
No.
Does it transform CommonJS imports?
No.
Is it safe to run on any code base?
There could be side-effects. If you're relying on a
index.js being imported and executed, then this might screw that behavior. It could also be that there are third-party packages which this does not play nice with. If you have a reasonably clean code base that doesn't do anything out of the ordinay and doesn't pass
node_modules through Babel, then this plugin will most likely work for you.
By how much will it decrease my bundle size?
This highly depends on how large the modules are you are importing from and how much of it you actually use. The improvements are more visible in code bases that split their bundle into chunks or have multiple endpoints.
Some more detailed logging is available when using the DEBUG environment variable:
DEBUG=transform-named-imports some-command-that-runs-transpilation
Thanks to the author of babel-plugin-transform-imports for the initial idea of rewriting the imports.
The major difference with
babel-plugin-transform-imports is that it requires defining every module you want rewritten. This plugin goes a step further and rewrites all your imports. | https://npm.taobao.org/package/babel-plugin-transform-named-imports | CC-MAIN-2019-47 | refinedweb | 665 | 56.66 |
Next Thread | Thread List | Previous Thread
Start a Thread | Settings
Hi,
We are attempting to run PC-Lint (version 8.00u) on our
Keil project which uses the RL-ARM Real-Time Library Version
V3.24.
We have set up PC-Lint to use the latest example PC-Lint
Configuration File for the CARM Compiler as downloaded from Keil's
web-site. File name:CO-RV.LNT
Lint reports the following error in RTX's rtl.h header file.
C:\Keil\ARM\RV31\INC\rtl.h(351,7): Error 129: declaration
expected, identifier 'FINFO' ignored
FINFO is a defined structure in rtl.h as follows
typedef struct {
S8 name[256];
U32 size;
U16 fileID;
U8 attrib;
struct {
U8 hr;
U8 min;
U8 sec;
U8 day;
U8 mon;
U16 year;
} time;
} FINFO;
Obviously we are loathe to start changing any of the supplied RTX
OS header files.
To simplify the problem we created a new empty project with just
the include directive:
#include <rtl.h>
Error 129 in rtl.h is still reported by PC-Lint.
Does anyone know how to resolve this Lint error?
Thank you
John
I've resolved the problem.
Keil's CO-RV.LNT Lint configuration file does not cover the use of
__swi functions.
The Lint error suggested the structure FINFO was the issue but
PC-Lint reports no errors when the __swi definitions in rtl.h are
commented out.
In order to get Lint to accept __swi declarations you
need to add an additional rule to the lint configuration file. I call
CO-RV.LNT from within another .LNT file and put the additional rule
in my own .LNT file.
So, my file, called STD_ARM.LNT contains:
// Keil RealView compiler
// Standard lint options
CO-RV.LNT
+d__swi=_to_brackets
+rw(_to_brackets)
The _to_brackets option removes the associated error. PC-Lint
returns no errors.
Just now I got the same error when I started linting my new
Cortex-M3 project first time. I fixed it like above mentioned. -
John, many thanks for your posting! | http://www.keil.com/forum/14153/ | CC-MAIN-2014-42 | refinedweb | 337 | 68.47 |
With App Engine, you only pay for the resources that you use beyond the free quotas. After you exceed the free quotas, your costs will scale with the amount of traffic your application receives.
To limit the costs of your App Engine app, you can use any of the following mechanisms:
- Specify the maximum number of instances
- Create budget alerts
- Disable your app manually
- Disable your app programmatically
Specify the maximum number of instances
Since App Engine costs usually scale based on the amount of traffic your app receives, you can limit your costs by limiting the number of instances App Engine can create.
Setting the maximum to 1 instance usually keeps your instance hour usage within the free tier. However, setting the maximum too low may prevent your app from having enough instances to adequately serve incoming requests.
To specify the maximum number of instances, use the
max_instances
setting
in your app's
app.yaml file.
Create budget alerts
Budget alerts send a notification when your costs rise above a threshold you
specify. When you receive a notification, you can limit costs by lowering the
value of the
max_instances setting or disabling your app.
To get started with budget alerts, see Set Budget Alerts.
Selecting the scope of a budget alert
You can create budget alerts for the total cost of all Google Cloud services in one or more projects, or just for the cost of App Engine.
To create a budget alert just for costs from App Engine, in the Budget alert's Products field, select App Engine. The alert will trigger when the total cost from all App Engine resources exceed the amount you specify, including:
- Instance hours in the Standard environment
- Instance hours and RAM in the Flexible environment
- Bundled App Engine services
For the full list of billable App Engine resources, see App Engine SKUs.
Disable your app manually
Disabling your app temporarily stops it from serving and incurring billing charges related to serving your app. All of your app's data and configuration settings remain unchanged, and when you are ready to start running your app again, you can enable it.
While the app is disabled, requests to your app will fail. You may continue to incur charges from other Google Cloud products. For example, if your project has exceeded the free quota for Cloud Storage, you will continue to incur charges for storage.
For more information, see Disabling an app.
Disable your app programmatically
You can use Budget Alerts, Pub/Sub, and Cloud Functions to automatically disable your app when your costs exceed a threshold you specify.
As with manually disabling an app:
- All of your app's data and configuration settings remain unchanged.
- When you are ready to start running your app again, you can enable it.
- Requests to your app will fail while the app is disabled.
- You may continue to incur charges from other Google Cloud products while your app is disabled.
To programmatically disable your app:
Create a budget alert that sends a notification to a Pub/Sub topic. For details, see Manage programmatic notifications.
To create a budget alert just for costs from App Engine, in the Budget's Products field, select App Engine. For information about the resources that can trigger this alert, see Create budget alerts.
In Cloud Functions create a function that is triggered by the Pub/Sub topic. For details, see Create a Cloud Function.
When creating the function:
Use the following source code:
import base64 import json import os from googleapiclient import discovery APP_NAME = os.getenv('GCP_PROJECT') def limit_use_appengine(data, context): pubsub_data = base64.b64decode(data['data']).decode('utf-8') pubsub_json = json.loads(pubsub_data) cost_amount = pubsub_json['costAmount'] budget_amount = pubsub_json['budgetAmount'] if cost_amount <= budget_amount: print(f'No action necessary. (Current cost: {cost_amount})') return appengine = discovery.build( 'appengine', 'v1', cache_discovery=False ) apps = appengine.apps() # Get the target app's serving status target_app = apps.get(appsId=APP_NAME).execute() current_status = target_app['servingStatus'] # Disable target app, if necessary if current_status == 'SERVING': print(f'Attempting to disable app {APP_NAME}...') body = {'servingStatus': 'USER_DISABLED'} apps.patch(appsId=APP_NAME, updateMask='serving_status', body=body).execute()
Add the following dependencies to your function's
requirements.txtfile:
google-api-python-client==1.12.2
Under Function to execute enter
limit_use_appengine.
Click Environment variables, networking, timeouts and more.
Select a service account that has the App Engine Admin role. The App Engine default service account has this role by default.
-
When the budget alert is triggered, an email is sent to users in your Cloud Billing account, and your function starts disabling your app. It may take few minutes to complete this process.
To verify that the function ran successfully, view the App Engine dashboard. A message appears near the top to indicate that your app is disabled.
Go to the App Engine dashboard
When you want your app to continue serving requests, go to the Application settings page and click Enable application.
Go to the application settings page
Changing or removing a spending limit
Older App Engine apps could create spending limits to specify an approximate maximum amount you can be charged for using App Engine resources. | https://cloud.google.com/appengine/docs/managing-costs?hl=ru | CC-MAIN-2020-45 | refinedweb | 851 | 55.24 |
Description
Sam and his sister Sara have one that contains n × A table of m squares. They want to dye each of their squares red or blue.
For personal preference, they want each 2 in the table × The square area of 2 contains an odd number (1 or 3) of red squares.
But last night, someone had dyed some squares in the form! Now Sam and Sara are very angry. However, they wanted to know if it was possible to color the remaining squares so that the whole form still met their requirements. If possible, how many dyeing schemes can meet their requirements?
Input
The first row of the input contains three integers n,m and k, representing the number of rows, columns and stained squares of the table respectively.
The next k lines describe the stained squares. The i-th row contains three integers \ (x_i,y_i,c_i \), representing the row number, column number and color of the i-th stained square respectively\ A value of (c_i \) of 1 indicates that the square is dyed red, and a value of \ (c_i \) of 0 indicates that the square is dyed blue.
Output
Output an integer representing the value obtained by the number of possible dyeing schemes W module \ (10 ^ 9 \).
Sample Input
3 4 3 2 2 1 1 2 0 2 3 1
Sample Output
8
HINT
\(2\leq n,m\leq10^6,0\leq k\leq10^6,1\leq x_i\leq n,1\leq y_i\leq m\).
Solution
Set red as 1 and blue as 0, and the problem constraint can be transformed into 2 for each requirement × The XOR sum of the square area of 2 is 1
If the first row has been determined, each subsequent row is either the odd column xor 1 of the previous row or the even column xor 1 of the previous row. Then the number of schemes is \ (\ large{2 ^ {empty rows} \)
Now we need to confirm whether there is such a legal first line, that is, whether the color XOR relationship between each two grids is contradictory
For each dyed lattice \ (x,y \) in row I, if their column numbers are the same as parity, their relationship in the first row is \ (c_x\;xor\;c_y \); If their column numbers are different from parity, it has made a total (i-1) transformation to the first row, and their relationship in the first row is \ (c_x\;xor\;c_y\;xor\;(i-1) \)
Then maintain the number of columns with the union query set, merge the dyed lattices of the same row, and record the XOR relationship with the father (it is convenient to O(1) find the XOR relationship between the lattices of the same connected block to judge the legitimacy). The number of schemes in the first row is \ (\ large{2 ^ {number of uncolored connected blocks in the first row} \)
#define N 1000005 #define M 1000000000 typedef long long ll; struct grid{ int x,y,c; bool friend operator <(grid a,grid b){ if(a.x!=b.x) return a.x<b.x; return a.y<b.y; } }a[N]; int c[N]/*col[1][i]^col[1][f[i]]*/,f[N],n,m,k,tot; bool b[N],v[N]; inline int gf(int k){ if(f[k]==k) return k; int fa=gf(f[k]); c[k]^=c[f[k]]; return f[k]=fa; } inline bool chk(int x,int y,int t){ int p=gf(x),q=gf(y); if(p^q){ if(b[p]||b[q]) b[p]=b[q]=true; f[p]=q;c[p]=c[x]^c[y]^t; return true; } else return (c[x]^c[y])==t; } inline int po(int x,int k){ int ret=1; while(k){ if(k&1) ret=1ll*ret*x%M; x=1ll*x*x%M;k>>=1; } return ret; } inline void Aireen(){ n=read();m=read();k=read(); for(int i=1;i<=k;++i){ a[i]=(grid){read(),read(),read()}; if(a[i].x==1) b[a[i].y]=true; v[a[i].x]=true; } sort(a+1,a+1+k); for(int i=1;i<=m;++i) f[i]=i; for(int i=2,x,y,t;i<=k;++i){ while(a[i].x==a[i-1].x){ x=a[i].y;y=a[i-1].y; t=a[i].c^a[i-1].c; if((x&1)^(y&1)) t^=((a[i].x-1)&1); if(!chk(x,y,t)){ puts("0");return; } ++i; } } for(int i=1;i<=m;++i) if(gf(i)==i&&!b[i]) ++tot; for(int i=2;i<=n;++i) if(!v[i]) ++tot; printf("%d\n",po(2,tot)); }
2017-05-03 17:56:48 | https://programmer.help/blogs/bzoj2303-apio2011-checkered-staining.html | CC-MAIN-2021-49 | refinedweb | 786 | 63.93 |
Customizing MSN Live Messenger to fullfill one's requirement is a great idea. Micosoft offer great Add-In feature to write the Add-Ins for your MSN Live Messenger. Writing an Add-in with Dot.Net Framework 2.0 is just a piece of Cake. So why dont try eating it. Tell me after eating that it was delicious.....ammm..
There are three steps to consider for watching your Add-In working.
hey dont worry, this is also an easy step.
Just follow the instructions
Run your Registry Editor
Start--> Run--> Regedit
Scroll to following Registry KeyHKEY_CURRENT_USER\Software\Microsoft\MSNMessenger
create a new DWORD entry AddInFeatureEnabled, if it is not there. then set its value to 1.
Now restart your Messenger
Create a new C# or whatever .Net language you like.
File--> New--> Project-->Class Library
Now Add Reference to MessengerClient.dll
Right Click on your Solution Name-->Add Refrence
Browse for MessengerClient.dll (most probably at C:\Program Files\MSN Messenger )
Now to avoid fully qualified names of types that we are going to use , you should add
using
The next step is to go on writing a class named AddIn(You can choose whatever name you like). But mind one thing that this class should me implementing an Interface
{
Client.SendNudgeMessage(userFrom);
Client.SendTextMessage(
}
Now just build or compile your solution. This will create a dll called your_namespace_name.dll in bin folder of your application. Just browse to that folder and rename that dll. to
your_namespace_name.yourClassName.dll
Now your done with all the Code effort.
Open up your Live Messenger
Tools--> Options, Your will have an Add-In option click it and browse to your dll created in above steps.
Run Messenger and get your Add-In working.
NOTE: This Article just gives an idea about working with Add-Ins for Windows Live Messenger. A thorough understanding of of Windows Live Messenger Add-In API can be found at
Here is the complete listing of Code
namespace
IMessengerAddIn
public class AddIn:IMessengerAddIn
IMessengerAddIn offers Initialize Method that must be implemented.
public
Since we are aiming to send only an Auto Reply, we just need register with the
IncomingTextMessage event as new EventHandler<IncomingTextMessageEventArgs>(Client_IncomingTextMessage);
Client.IncomingTextMessage+=
Now just go on writing Event. | https://www.codeproject.com/Articles/17348/Set-Your-MSN-Live-Messenger-to-Auto-Reply | CC-MAIN-2018-22 | refinedweb | 375 | 58.99 |
.NET has some really easy-to-use facilities for creating and editing XML. Many of these facilities were introduced to make Linq to XML work better, but you can make use of them in more general situations.
There always was good XML support in .NET but Linq adds a set of classes that makes it easier to work with XML, particularly if you’re not an XML specialist.
There are a number of standard protocols and ways of working with XML – Xpath, SAX, DOM and so on.
All of them are good but they all focus on some specific particular aspect of XML and a particular way of getting the job done. Linq’s version of XML goes “back to basics”.
It is important to realise that much of what we are about to investigate can be used without the need to make use of Linq - it all just happens to be a very easy way to work with XML in general.
Even if you aren’t interested in working with XML looking at how Linq handles a more complicated data structure, a tree in this case, is instructive and has a lot to teach you about the way Linq is designed, how it works and how you might extend it to other data structures.
In this article we look at how to construct the tree structure that XML is all about and in a future article we look at how to use such structures with Linq.
The core of XML is the tag as in
The rules for XML are simple – tags occur, almost always, in matched pairs and you can nest tags as if they were brackets.
The only exception to the matched pairs rule is a tag that is its own closing tag – as in <Record/> which opens and closes the tag in one go.
It’s not difficult to see that you can use tags to build a general tree structure and all you need to represent it in a program is a class that has a collection of itself as a property.
This is exactly how the xNode class, and the more useful xElement descended from it via xContainer, operate.
The important point is that xElement has a Nodes collection which can be used to store an element’s child elements.
A simple example will make this clear.
First we need a root node:
XElement root = new XElement("Record");
The string “Record” is automatically converted to an XName object and this is used to set the Name property of the new XElement.
An XName is used instead of a simple string because XML names have some additional behaviour because of namespaces – more later.
Now have a root for our tree let’s create a leaf node
XElement child1 = new XElement("Name");
and hang it off the tree….
root.Add(child1);
If you place a textbox on a form you can see the XML that the tree represents using:
textBox1.Text = root.ToString();
What you will see is:
<Record><Name /></Record>
You can carry on in the same way to build up a tree of any complexity you like.
For example:
XElement root=new XElement("Record");XElement child1=new XElement("Name");root.Add(child1);XElement child2=new XElement("First");XElement child3=new XElement("Second");child1.Add(child2);child1.Add(child3);XElement child4=new XElement("Address");root.Add(child4);
creates the following XML:
<Record> <Name> <First /> <Second /> </Name> <Address /></Record>
The idea of nesting XElements within XElements is fairly obvious but there are neater ways of achieving the same result.
For example, you can combine the two Add methods into a single call:
child1.Add(child2,child3);
The reason this works is due to an overload of Add not mentioned in the documentation:
public void Add(params object[] content);
You can, of course construct a list of child objects to insert into multiple XElements if you want to.
Another style of XML tree construction is based on the use of the XElement constructor.
One overloaded version allows you to specify the XElements content. So to create an XElement with two children you would use:
XElement root = new XElement("Record", new XElement("Name"), new XElement("Address"));
You can continue this nested construction to any level you need to.
For example, the following creates the same XML tree we had earlier:
XElement root = new XElement("Record", new XElement("Name", new XElement("First"), new XElement("Second")), new XElement("Address"));
This is generally referred to as “functional construction” and if you format it correctly then it looks like the tree it is constructing and it has the advantage that you can pass it directly to any method that cares to make use of it.
Of course in this style of construction you don’t get variables to keep track of each node but in most cases you don’t need them.
There are two additional very easy ways of converting XML into an XElement tree – the static Load and Parse methods.
Load will take a file specification as a URI or as a TextReader or XmlReader and parse the text stream into an XElement tree.
The Parse method does the same but by accepting a string of XML tags.
For example, to construct the same XML tree given earlier:
string XML = @" <Name> <First /> <Second /> </Name> <Address /></Record>";XElement root= XElement.Parse(XML) ;
If the XML you try to load or parse is syntactically incorrect then you will have to handle the resulting exception.
If you want to go the other way then there is a Save method and you can specify options on the Save and the ToString methods that control some aspects of formatting.
Now you can see how to build an XElement tree but what about content?
A tree of XML tags isn’t usually the whole story. The main data payload in XML is suppose to be anything you put between opening and closing tags.
In the XElement tree any text between tags is stored as an XText node in the node collection i.e. it is just another type of child node.
As such you can add XText nodes using all of the methods described earlier – if you try to add a string object as a child then the methods simply convert it to an XText object and add it to the collection of nodes.
XElement root = new XElement("Record","Address Record", new XElement("Name", new XElement("First","Mike"), new XElement("Second")), new XElement("Address"));
This adds “Address Record” and “Mike” as text between the specified tags. It is also worth knowing that if an XElement object has only a single XText child then this is also its string Value property.
Text between the tags isn’t the only sort of data carried by XML.
You can also specify any number of name value pairs within the tags themselves as attributes.
Attributes are supposed to be used as “metadata”, i.e. they describe the nature of the data between the tags - formatting, time zone, context etc - and within the XElement tree they are stored as XAttribute objects within the Attributes collection.
The reason for this is that if you enumerate the tree you will list each of the tags and text between tags but not the attributes. Once you have found a tag, i.e. an XElement object, you can enumerate its attributes.
Viewed in this way it should be clear that the main distinction between attributes and other nodes is that attributes are not part of the tree structure being simply stored at each node of the tree.
The rule that you have to keep in mind is that if you add an XAttribute object to an XElement object then it will automatically be added to the Attributes collection.
XAttribute Att1=new XAttribute("Epoc",2000);root.Add(Att1);
adds an attribute Epoc= “2000” to the Attributes collection. The XML generated reads:
<Record Epoc="2000"> …<Record>
You can achieve the same result using the function method of constructing an XML tree:
XElement root = new XElement("Record", new XAttribute("Epoc", 2000), new XElement("Name", new XElement("First","Mike"), new XElement("Second")), new XElement("Address"));
<ASIN:0596007647>
<ASIN:161729134X>
<ASIN:1840783370
<ASIN:0321658701>
<ASIN:067232797X> | http://www.i-programmer.info/programming/c/1030-xml-in-c.html | CC-MAIN-2016-50 | refinedweb | 1,366 | 66.07 |
These rules apply to pure JS, as well as JSA inside of Polymer. Follow the Google Style Guide as a baseline, except as follows below.
As a baseline, be consistent with standard Polymer style as used by Polymer elements themselves. Some exceptions and clarifications are listed below.
Instead of
<iron-ajax>, prefer using the family of sk.request methods, found in common.js
Rationale: It is easier to debug procedural code over the declarative element. iron-ajax requires looking between template and the JS in the element declaration, which is sometimes a lot of scrolling. It is easier to read when the logic is all in one place. Some legacy code may use iron-ajax, but do not follow that example.
Behaviors should exist one per file, with the file name ending in “-behaviors.html”. If a Behavior is not used by any templating logic, consider implementing the logic in pure JS, using a namespace as appropriate.
Rationale: If methods are not used for templating, pure JS is more portable.
Elements should exist one per file, with the file name being the same as the element. If an Element has a helper element that should not be used alone, it may be included in the same file. Example: details-summary.html
Properties should be named using one word (if possible) or using snake_case. Private properties and methods should be prefixed with an underscore (e.g. _super_private).
Rationale: The names are consistent in Javascript and HTML land. Polymer will automatically convert camelCase into sausage-case otherwise, which leads to hilarity and/or tears.
Python code follows the Google Python Style Guide. | https://skia.googlesource.com/buildbot/+/b791391a76a7e6adb42a1306248631020d044d23/STYLEGUIDE.md | CC-MAIN-2019-22 | refinedweb | 270 | 58.28 |
of clusters.
The K-means algorithm starts by randomly choosing a centroid value for each cluster..
A Simple Example
Let's try to see how the K-means algorithm works with the help of a handcrafted example, before implementing the algorithm in Scikit-Learn. It takes three lines of code to implement the K-means clustering algorithm in Scikit-Learn. However, to understand how it actually works, let's first solve a clustering problem using K-means clustering "on paper".
Suppose we have a set of the following two dimensional data instances named
D.
D = { (5,3), (10,15), (15,12), (24,10), (30,45), (85,70), (71,80), (60,78), (55,52), (80,91) }
We want to divide this data into two clusters, C1 and C2 based on the similarity between the data points.
The first step is to randomly initialize values for the centroids of both clusters. Let's name centroids of clusters C1 and C2 as
c1 and
c2 and initialize them with the values of the first two data points i.e. (5, 3) and (10, 15).
Now we have to start the iterations.
Iteration 1
In the table above, the second column contains all the data points. The third column contains the Euclidean distance between all the data points and centroid
c1. Similarly the fourth column contains distance between the
c2 centroid and the data points. Finally, in the fifth column we show which cluster the data point is assigned to based on the Euclidean distance between the two cluster centroids. For instance, look at the third data point (15, 12). It has a distance of 13.45 units from
c1 while a distance of 5.83 units from
c2; therefore it has been clustered in C2.
After assigning data points to the corresponding clusters, the next step is to calculate the new centroid values. These values are calculated by finding the means of the coordinates of the data points that belong to a particular cluster.
For cluster C1, there is currently only one point i.e. (5,3), therefore the mean of the coordinates remain same and the new centroid value for
c1 will also be (5,3).
For C2, there are currently 9 data points. We name the coordinates of data points as
x and
y. The new value for
x coordinate of centroid
c2 can be calculated by determining the mean of
x coordinates of all 9 points that belong to cluster C2 as given below:
c2(x) = (10 + 15 + 24 + 30 + 85 + 71 + 60 + 55 + 80) / 9 = 47.77
The new value for
y coordinate of centroid
c2 can be calculated by determining the mean of all
y coordinates of all 9 points that belong to cluster C2.
c2(y) = (15 + 12 + 10 + 45 + 70 + 80 + 78 + 52 + 91) / 9 = 50.33
The updated centroid value for
c2 will now be {47.77, 50.33}.
For the next iteration, the new centroid values for
c1 and
c2 will be used and the whole process will be repeated. The iterations continue until the centroid values stop updating. The next iterations are as follows:
Iteration 2
c1(x) = (5, 10, 15, 24) / 4 = 13.5 c1(y) = (3, 15, 12, 10) / 4 = 10.0
Updated
c1 to be (13.5, 10.0).
c2(x) = (30 + 85 + 71 + 60 + 55 + 80) / 6 = 63.5 c2(y) = (45 + 70 + 80 + 78 + 52 +91) / 6 = 69.33
Updated
c2 to be (63.5, 69.33).
Iteration).
Iteration).
At the end of fourth iteration, the updated values of C1 and C2 are same as they were at the end of the third iteration. This means that data cannot be clustered any further.
c1 and
c2 are the centroids for C1 and C2. To classify a new data point, the distance between the data point and the centroids of the clusters is calculated. Data point is assigned to the cluster whose centroid is closest to the data point.
K-means Clustering with Scikit-Learn
Now that we know how the K-means clustering algorithm actually works, let's see how we can implement it with Scikit-Learn.
To run the following script you need the matplotlib, numpy, and scikit-learn libraries. Check the following links for instructions on how to download and install these libraries.
Import Libraries
Let's start our script by first importing the required libraries:
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from sklearn.cluster import KMeans
Prepare Data
The next step is to prepare the data that we want to cluster. Let's create a
numpy array of 10 rows and 2 columns. The row contains the same data points that we used for our manual K-means clustering example in the last section. We create a
numpy array of data points because the Scikit-Learn library can work with
numpy array type data inputs without requiring any preprocessing.
X = np.array([[5,3], [10,15], [15,12], [24,10], [30,45], [85,70], [71,80], [60,78], [55,52], [80,91],])
Visualize the Data
You can see these are the same data points that we used in the previous example. Let's plot these points and check if we can eyeball any clusters. To do so, execute the following line:
plt.scatter(X[:,0],X[:,1], label='True Position')
The above code simply plots all the values in the first column of the X array against all the values in the second column. The graph will look like this:
From the naked eye, if we have to form two clusters of the above data points, we will probably make one cluster of five points on the bottom left and one cluster of five points on the top right. Let's see if our K-means clustering algorithm does the same or not.
Create Clusters
To create a K-means cluster with two clusters, simply type the following script:
kmeans = KMeans(n_clusters=2) kmeans.fit(X)
Yes, it is just two lines of code. In the first line, you create a
KMeans object and pass it 2 as value for
n_clusters parameter. Next, you simply have to call the
fit method on
kmeans and pass the data that you want to cluster, which in this case is the
X array that we created earlier.
Now let's see what centroid values the algorithm generated for the final clusters. Type:
print(kmeans.cluster_centers_)
The output will be a two dimensional array of shape 2 x 2.
[[ 16.8 17. ] [ 70.2 74.2]]
Here the first row contains values for the coordinates of the first centroid i.e. (16.8 , 17) and the second row contains values for the coordinates of the other centroid i.e. (70.2, 74.2). You can see that these values are similar to what we calculated manually for centroids
c1 and
c2 in the last section. In short, our algorithm works fine.
To see the labels for the data point, execute the following script.
print(kmeans.labels_)
The output is a one dimensional array of 10 elements corresponding to the clusters assigned to our 10 data points.
[0 0 0 0 0 1 1 1 1 1]
Here the first five points have been clustered together and the last five points have been clustered. Here 0 and 1 are merely used to represent cluster IDs and have no mathematical significance. If there were three clusters, the third cluster would have been represented by digit
2.
Let's plot the data points again on the graph and visualize how the data has been clustered. This time we will plot the data along with their assigned label so that we can distinguish between the clusters. Execute the following script:
plt.scatter(X[:,0],X[:,1], c=kmeans.labels_, cmap='rainbow')
Here we are plotting the first column of the
X array against the second column, however in this case we are also passing
kmeans.labels_ as value for the
c parameter that corresponds to labels. The
cmap='rainbow' parameter is passed for choosing the color type for the different data points. The output graph should look like this:
As expected, the first five points on the bottom left have been clustered together (displayed with blue), while the remaining points on the top right have been clustered together (displayed with red).
Now let's execute K-means algorithm with three clusters and see the output graph.
You can see that again the points that are close to each other have been clustered together.
Now let's plot the points along with the centroid coordinates of each cluster to see how the centroid positions effects clustering. Again we will use three clusters to see the effect of centroids. Execute the following script to draw the graph:
plt.scatter(X[:,0], X[:,1], c=kmeans.labels_, cmap='rainbow') plt.scatter(kmeans.cluster_centers_[:,0] ,kmeans.cluster_centers_[:,1], color='black')
Here in this case we are plotting the data points in rainbow colors while the centroids are in black. The output looks like this:
In case of three clusters, the two points in the middle (displayed in red) have distance closer to the centroid in the middle (displayed in black between the two reds), as compared to the centroids on the bottom left or top right. However if there were two clusters, there wouldn't have been a centroid in the center, hence the red points would have to be clustered together with the points in the bottom left or top right clusters. exploring blog posts like this is a great start, personally I tend to learn better with visuals, resources, and explanations from video courses like those linked above.
Conclusion
K-means clustering is a simple yet very effective unsupervised machine learning algorithm for data clustering. It clusters data based on the Euclidean distance between data points. K-means clustering algorithm has many uses for grouping text documents, images, videos, and much more.
Have you ever used K-means clustering in an application? If so, what for? Let us know in the comments! | https://stackabuse.com/k-means-clustering-with-scikit-learn/ | CC-MAIN-2021-17 | refinedweb | 1,682 | 71.75 |
#include <deal.II/grid/grid_out.h>
Flags specific to the output of grids in two space dimensions.
Definition at line 410 of file grid_out.h.
Constructor.
Definition at line 224 of file grid_out.cc.
Declare parameters in ParameterHandler.
Definition at line 245 of file grid_out.cc.
Parse parameters of ParameterHandler.
Definition at line 258 of file grid_out.cc.
If this flag is set, then we place the number of the cell into the middle of each cell. The default value is to not do this.
The format of the cell number written is
level.index, or simply
index, depending on the value of the following flag.
Definition at line 419 of file grid_out.h.
If the cell numbers shall be written, using the above flag, then the value of this flag determines whether the format shall be
level.index, or simply
index. If
true, the first format is taken. Default is
true.
The flag has obviously no effect if
write_cell_numbers is
false.
Definition at line 428 of file grid_out.h.
Vertex numbers can be written onto the vertices. This is controlled by the following flag. Default is
false.
Definition at line 434 of file grid_out.h. | http://www.dealii.org/developer/doxygen/deal.II/structGridOutFlags_1_1Eps_3_012_01_4.html | CC-MAIN-2015-48 | refinedweb | 196 | 71.51 |
messagelib/messageviewer/src
Overview
The messageviewer is a library that provides a widget that can show a KMime::Message in a nice way.
The message is displayed by first converting it to HTML and then displaying the HTML in a widget based on WebKit.
ObjectTreeParser
The class ObjectTreeParser is used to parse the KMime::Message and create a HTML representation out of it. An implementation of the ObjectTreeSource interface is passed to the ObjectTreeParser, which provides an interface for the ObjectTreeParser to interact with the viewer widget. The most import part of this interface is that it provides a HtmlWriter, which the ObjectTreeParser uses to write the HTML it generates to.
The HtmlWriter passed to the ObjectTreeParser can be a dummy implementation, like in EmptySource. This is used when one is not interested in the interaction between the ObjectTreeParser and the viewer. The most common use case is that one is not interested in the generated HTML, but only in the textual content that the ObjectTreeParser extracted, which can be retrieved with ObjectTreeParser::textualContent(). This is used for example when KMail creates an inline forward message.
The Viewer of course uses a non-dummy implementation of the ObjectTreeSource, the MailViewerSource. The HtmlWriter provided by the MailViewerSource is a WebKitPartHtmlWriter, which writes the HTML directly to the MailWebView widget, which is a KWebView.
The header of the message or the headers of any embedded messages are formatted in a special way. The user can chose between many styles of header formatting, like 'fancy' or 'brief'. The creation of the HTML code for these headers is handled by HeaderStyle. The ObjectTreeParser does not use the HeaderStyle classes directly; instead, it is delegated to ViewerPrivate::writeMsgHeader() via ObjectTreeSource::createMessageHeader().
The 'fancy' header style can display the spam status of the message in a nice way. To extract the spam information, SpamHeaderAnalyzer, AntiSpamConfig and SpamAgent are used.
The HeaderStrategy controls which parts of the header should be shown. Based on this strategy, the HeaderStyle implementations decide which header fields to include in the HTML code they generate.
Some parts of the appearance of the message can be customized by changing the CSS. For this, the CSSHelper class is used, which is passed to the ObjectTreeParser with ObjectTreeSource::cssHelper().
The ObjectTreeParser can have plugins that create the HTML for special MIME parts themselves. Those plugins are found in kdepim/plugins/messageviewer. Examples are plugins that render the vCard in a nice way when a vCard MIME type is encountered, or which do the same when a diff attachment is found. The classes used for this are the interfaces BodyPartFormatter and BodyPartFormatterPlugin and their helper interfaces in the interfaces/ subdirectory. The plugins only depend on these interfaces and are independent from the rest of the viewer.
Most MIME parts are handled internally, like all multipart types or text/plain and text/html. For text/html, a HTMLQuoteColorer is used to change the HTML of the message to include coloring of the quotes.
The AttachmentStrategy which is passed to the constructor or ObjectTreeParser controls how some of the MIME parts are handled: For example, an image MIME part might be displayed as an icon, or it might display the full image inline in the body.
For details on the internals of the ObjectTreeParser, especially the way it parses and changes a message, see the documentation of ObjectTreeParser.
Widgets
The Viewer consists of several widgets. The main widget is the MailWebView, which displays the HTML code that the ObjectTreeParser generated from the message. On the left side of that, a HtmlStatusBar displays the type of the displayed message. Below the MailWebView, a QTreeView shows the message structure by using a MimeTreeModel. The viewer can open an additional window to show the raw message source with the MailSourceViewer. The viewer also can show the properties of a MIME part of the message, which uses the AttachmentDialog class. When opening MIME parts that are vCards, they are displayed in a VCardViewer. When searching through the message, a FindBar is displayed at the bottom.
URL handling
The generated HTML has many different URLs in it. Those can be the normal URLs which are contained in the message text, the mailto URLs that are in the header, or special KMail URLs. These KMail URLs for example include the "Load external references" link for HTML mails with external images, the "Show details" link for signed messages, the URL to expand or collapse quoted text and many more.
Throughout the displayed message, there are links to attachments, either in the header when using some header styles, or at the place where the actual attachment is, in the body. These URLs all start with 'attachment:', followed by a number that describes the KMime::ContentIndex of the attachment. The attachment links also contain a parameter that describes whether the link is in the header of the message or in the body. This is needed because clicking on the links in the header should scroll to the attachment in the body.
These URLs are all written to the HTML code by ObjectTreeParser, but it is up to the Viewer to handle interaction with these URLs, such as clicking on them or hovering over them.
For this, the Viewer has a URLHandlerManager, which manages a list of URLHandler. An URLHandler is responsible for the interaction with exactly one type or URL. Interaction means executing an action when clicking the URL or showing a status bar message when hovering over it. Examples of these URLHandler are AttachmentURLHandler or ExpandCollapseQuoteURLManager. The special KMailProtocolURLHandler deals with multiple types of URLs that all start with 'kmail:'.
Note that the 'kmail:' URLs are only named like this for historic reasons, nowadays the viewer is independent of KMail.
Misc
There are various smaller and unimportant classes in this library.
PartNodeBodyPart is an implementation of the BodyPart interface. It is used by plugins to gain access to various properties of the MIME part the plugins are supposed to handle.
NodeHelper currently is a big mess that consists of mainly two things: First, it provides convenience methods for operations related to the MIME part class KMime::Content, such as nextSibling() or charset(). All these methods should eventually be moved away from here, either to kdepim/messagecore or to kdpimlibs/kmime. Secondly, it provides lists and maps which are used by the ObjectTreeParser and the Viewer during processing. Such can include a list of all KMime::Content that are currently being processed, a map of KMime::Content to their signature or encryption state, a map of KMime::Content to PartMetaData, and so on.
The class Global is used so that applications that use this library can set the correct config object. Those applications also can use the ConfigureWidget in their application to display some settings. Most of the settings use KConfigXT, and the file for the settings definitions is messageviewer.kcfg. The GlobalSettings class is a thin wrapper around the GlobalSettingsBase class, which is generated from the KCFG.
StringUtil is a namespace that groups various functions that mainly do string operations, for example on mail addresses.
Then there is the Util namespace, which again has some convenience functions that neither fit into StringUtil or into NodeHelper.
The last utilitly thing are the functions in stl_util.h, which are supposed to be used in combination with STL algorithms.
There are a bunch of smaller classes like AutoQPointer, EditorWatcher, IconNameCache, KCursorSaver, KleoJobExecutor, KabcBridge and many more. See the full class list if you're curious.
You should also read the documentation of the following classes, which are extensivly documented:
- See also
- MessageViewer::ViewerPrivate
- MessageViewer::ObjectTreeParser
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sat May 9 2020 04:29:56 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/4.x-api/pim-apidocs/messagelib/messageviewer/src/html/index.html | CC-MAIN-2020-29 | refinedweb | 1,301 | 53.61 |
Im a beginner programmer and im trying to complete this assignment but i need Help.
In this lab you have a prewritten Java program for a furniture company. The program is supposed to compute the price of any table a customer orders, based on the following facts:
The charge for all tables ia minimum of $150.00
If the surface(length * width) is over 750 square inches, add $50.00
If the wood is "mahogany" add $200.00; for "oak" add $100.00. No charge is added for "pine"
For extension leaves for the table, there is an additional $50.00 charge each.
You need to declare variables for the following, and initialize them where specified:
A Variable for the cost of the table initialized to 0.00
A variable for the length of the table initialized to 50 inches
A variable for the width of the table initialized to 40 inches
A variable for the surface area of the table
A variable for the wood type initialized with the value "oak"
A variable for the number of extension leaves initialized with the value 2.
Write the rest of the program using assignments statement and if statements as appropriate. The out statement is written for you. Your output should be: The charge for this table is $400.0.
This is what i have
public class Furniture { public static void main(String args[]) { // Declare and initialize variables here. // Charge for this table. double charge = 150.00; double table = 0.00; // Length of table in inches. int length = 50; // Width of table in inches. int width = 40; // Area of this table in square inches. int area = length * width; // Type of wood. String wood = oak; // Number of extension leaves. int leaves = 2; // Write assignment and if statements here as appropriate. table = 0.00; if (area > 750) {charge += 50;} if (wood = "mahogany") {charge += 200.00;} if (wood = "oak") {charge += 100.00;} // Output Charge for this table. System.out.println("The charge for this table is $" + charge); System.exit(0); } }
Can you tell me what i need to add or delete rather than just writing it out. But if you do write if out can you explain it please. | http://www.javaprogrammingforums.com/object-oriented-programming/24226-beginners-needing-help.html | CC-MAIN-2013-20 | refinedweb | 364 | 76.32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.